psub.pas 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl, Daniel Mantione
  3. Does the parsing and codegeneration at subroutine level
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit psub;
  18. {$i fpcdefs.inc}
  19. { $define debug_eh}
  20. interface
  21. uses
  22. globals,cclasses,
  23. node,nbas,nutils,
  24. symdef,procinfo,optdfa;
  25. type
  26. tcgprocinfo = class(tprocinfo)
  27. private type
  28. ttempinfo_flags_entry = record
  29. tempinfo : ptempinfo;
  30. flags : ttempinfoflags;
  31. end;
  32. ptempinfo_flags_entry = ^ttempinfo_flags_entry;
  33. private
  34. tempinfo_flags_map : TFPList;
  35. tempflags_swapped : boolean;
  36. procedure swap_tempflags;
  37. function store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  38. procedure CreateInlineInfo;
  39. { returns the node which is the start of the user code, this is needed by the dfa }
  40. function GetUserCode: tnode;
  41. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  42. procedure add_entry_exit_code;
  43. procedure setup_tempgen;
  44. procedure OptimizeNodeTree;
  45. protected
  46. procedure generate_code_exceptfilters;
  47. public
  48. { code for the subroutine as tree }
  49. code : tnode;
  50. { positions in the tree for init/final }
  51. entry_asmnode,
  52. loadpara_asmnode,
  53. exitlabel_asmnode,
  54. stackcheck_asmnode,
  55. init_asmnode : tasmnode;
  56. temps_finalized : boolean;
  57. dfabuilder : TDFABuilder;
  58. destructor destroy;override;
  59. function calc_stackframe_size : longint;override;
  60. procedure printproc(pass:string);
  61. procedure generate_code;
  62. procedure generate_code_tree;
  63. procedure generate_exceptfilter(nestedpi: tcgprocinfo);
  64. procedure resetprocdef;
  65. procedure add_to_symtablestack;
  66. procedure remove_from_symtablestack;
  67. procedure parse_body;
  68. procedure store_tempflags;
  69. procedure apply_tempflags;
  70. procedure reset_tempflags;
  71. function has_assembler_child : boolean;
  72. procedure set_eh_info; override;
  73. {$ifdef DEBUG_NODE_XML}
  74. procedure XMLPrintProc(FirstHalf: Boolean);
  75. {$endif DEBUG_NODE_XML}
  76. end;
  77. procedure printnode_reset;
  78. {$ifdef DEBUG_NODE_XML}
  79. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  80. procedure XMLFinalizeNodeFile(RootName: shortstring);
  81. {$endif DEBUG_NODE_XML}
  82. { reads the declaration blocks }
  83. procedure read_declarations(islibrary : boolean);
  84. { reads declarations in the interface part of a unit }
  85. procedure read_interface_declarations;
  86. { reads any routine in the implementation, or a non-method routine
  87. declaration in the interface (depending on whether or not parse_only is
  88. true) }
  89. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  90. { parses only the body of a non nested routine; needs a correctly setup pd }
  91. procedure read_proc_body(pd:tprocdef);
  92. procedure import_external_proc(pd:tprocdef);
  93. implementation
  94. uses
  95. sysutils,
  96. { common }
  97. cutils, cmsgs,
  98. { global }
  99. globtype,tokens,verbose,comphook,constexp,
  100. systems,cpubase,aasmbase,aasmtai,aasmdata,
  101. { symtable }
  102. symconst,symbase,symsym,symtype,symtable,defutil,defcmp,symcreat,
  103. paramgr,
  104. fmodule,
  105. { pass 1 }
  106. ngenutil,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  107. pass_1,
  108. {$ifdef state_tracking}
  109. nstate,
  110. {$endif state_tracking}
  111. { pass 2 }
  112. {$ifndef NOPASS2}
  113. pass_2,
  114. {$endif}
  115. { parser }
  116. scanner,gendef,
  117. pbase,pstatmnt,pdecl,pdecsub,pexports,pgenutil,pparautl,
  118. { codegen }
  119. tgobj,cgbase,cgobj,hlcgobj,hlcgcpu,dbgbase,
  120. ncgflw,
  121. ncgutil,
  122. optbase,
  123. opttail,
  124. optcse,
  125. optloop,
  126. optconstprop,
  127. optdeadstore,
  128. optloadmodifystore,
  129. optutils
  130. {$if defined(arm)}
  131. ,cpuinfo
  132. {$endif arm}
  133. {$ifndef NOOPT}
  134. ,aopt
  135. {$endif}
  136. ;
  137. function checknodeinlining(procdef: tprocdef): boolean;
  138. procedure _no_inline(const reason: TMsgStr);
  139. begin
  140. include(procdef.implprocoptions,pio_inline_not_possible);
  141. Message1(parser_n_not_supported_for_inline,reason);
  142. Message(parser_h_inlining_disabled);
  143. end;
  144. var
  145. i : integer;
  146. currpara : tparavarsym;
  147. begin
  148. result := false;
  149. { this code will never be used (only specialisations can be inlined),
  150. and moreover contains references to defs that are not stored in the
  151. ppu file }
  152. if df_generic in current_procinfo.procdef.defoptions then
  153. exit;
  154. if pi_has_assembler_block in current_procinfo.flags then
  155. begin
  156. _no_inline('assembler');
  157. exit;
  158. end;
  159. if (pi_has_global_goto in current_procinfo.flags) or
  160. (pi_has_interproclabel in current_procinfo.flags) then
  161. begin
  162. _no_inline('global goto');
  163. exit;
  164. end;
  165. if pi_has_nested_exit in current_procinfo.flags then
  166. begin
  167. _no_inline('nested exit');
  168. exit;
  169. end;
  170. if pi_calls_c_varargs in current_procinfo.flags then
  171. begin
  172. _no_inline('called C-style varargs functions');
  173. exit;
  174. end;
  175. { the compiler cannot handle inherited in inlined subroutines because
  176. it tries to search for self in the symtable, however, the symtable
  177. is not available }
  178. if pi_has_inherited in current_procinfo.flags then
  179. begin
  180. _no_inline('inherited');
  181. exit;
  182. end;
  183. if pio_nested_access in procdef.implprocoptions then
  184. begin
  185. _no_inline('access to local from nested scope');
  186. exit;
  187. end;
  188. { We can't support inlining for procedures that have nested
  189. procedures because the nested procedures use a fixed offset
  190. for accessing locals in the parent procedure (PFV) }
  191. if current_procinfo.has_nestedprocs then
  192. begin
  193. _no_inline('nested procedures');
  194. exit;
  195. end;
  196. if pi_uses_get_frame in current_procinfo.flags then
  197. begin
  198. _no_inline('get_frame');
  199. { for LLVM: it can inline things that FPC can't, but it mustn't
  200. inline this one }
  201. include(current_procinfo.procdef.implprocoptions,pio_inline_forbidden);
  202. exit;
  203. end;
  204. for i:=0 to procdef.paras.count-1 do
  205. begin
  206. currpara:=tparavarsym(procdef.paras[i]);
  207. case currpara.vardef.typ of
  208. arraydef :
  209. begin
  210. if is_array_of_const(currpara.vardef) or
  211. is_variant_array(currpara.vardef) then
  212. begin
  213. _no_inline('array of const');
  214. exit;
  215. end;
  216. { open arrays might need re-basing of the index, i.e. if you pass
  217. an array[1..10] as open array, you have to add 1 to all index operations
  218. if you directly inline it }
  219. if is_open_array(currpara.vardef) then
  220. begin
  221. _no_inline('open array');
  222. exit;
  223. end;
  224. end;
  225. else
  226. ;
  227. end;
  228. end;
  229. result:=true;
  230. end;
  231. {****************************************************************************
  232. PROCEDURE/FUNCTION BODY PARSING
  233. ****************************************************************************}
  234. procedure initializedefaultvars(p:TObject;arg:pointer);
  235. var
  236. b : tblocknode;
  237. begin
  238. if tsym(p).typ<>localvarsym then
  239. exit;
  240. with tabstractnormalvarsym(p) do
  241. begin
  242. if (vo_is_default_var in varoptions) and (vardef.size>0) then
  243. begin
  244. b:=tblocknode(arg);
  245. b.left:=cstatementnode.create(
  246. ccallnode.createintern('fpc_zeromem',
  247. ccallparanode.create(
  248. cordconstnode.create(vardef.size,sizeuinttype,false),
  249. ccallparanode.create(
  250. caddrnode.create_internal(
  251. cloadnode.create(tsym(p),tsym(p).owner)),
  252. nil
  253. )
  254. )
  255. ),
  256. b.left);
  257. end;
  258. end;
  259. end;
  260. procedure initializevars(p:TObject;arg:pointer);
  261. var
  262. b : tblocknode;
  263. begin
  264. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  265. exit;
  266. with tabstractnormalvarsym(p) do
  267. begin
  268. if assigned(defaultconstsym) then
  269. begin
  270. b:=tblocknode(arg);
  271. b.left:=cstatementnode.create(
  272. cassignmentnode.create(
  273. cloadnode.create(tsym(p),tsym(p).owner),
  274. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  275. b.left);
  276. end
  277. else
  278. initializedefaultvars(p,arg);
  279. end;
  280. end;
  281. procedure check_finalize_paras(p:TObject;arg:pointer);
  282. begin
  283. if (tsym(p).typ=paravarsym) then
  284. begin
  285. if tparavarsym(p).needs_finalization then
  286. begin
  287. include(current_procinfo.flags,pi_needs_implicit_finally);
  288. include(current_procinfo.flags,pi_do_call);
  289. end;
  290. end;
  291. end;
  292. procedure check_finalize_locals(p:TObject;arg:pointer);
  293. begin
  294. { include the result: it needs to be finalized in case an exception }
  295. { occurs }
  296. if (tsym(p).typ=localvarsym) and
  297. (tlocalvarsym(p).refs>0) and
  298. is_managed_type(tlocalvarsym(p).vardef) then
  299. begin
  300. include(current_procinfo.flags,pi_needs_implicit_finally);
  301. include(current_procinfo.flags,pi_do_call);
  302. end;
  303. end;
  304. procedure init_main_block_syms(block: tnode);
  305. var
  306. oldfilepos: tfileposinfo;
  307. begin
  308. { initialized variables }
  309. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  310. begin
  311. { initialization of local variables with their initial
  312. values: part of function entry }
  313. oldfilepos:=current_filepos;
  314. current_filepos:=current_procinfo.entrypos;
  315. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  316. current_filepos:=oldfilepos;
  317. end
  318. else if current_procinfo.procdef.localst.symtabletype=staticsymtable then
  319. begin
  320. { for program and unit initialization code we also need to
  321. initialize the local variables used of Default() }
  322. oldfilepos:=current_filepos;
  323. current_filepos:=current_procinfo.entrypos;
  324. current_procinfo.procdef.localst.SymList.ForEachCall(@initializedefaultvars,block);
  325. current_filepos:=oldfilepos;
  326. end;
  327. if assigned(current_procinfo.procdef.parentfpstruct) then
  328. begin
  329. { finish the parentfpstruct (add padding, ...) }
  330. finish_parentfpstruct(current_procinfo.procdef);
  331. end;
  332. end;
  333. function block(islibrary : boolean) : tnode;
  334. begin
  335. { parse const,types and vars }
  336. read_declarations(islibrary);
  337. { do we have an assembler block without the po_assembler?
  338. we should allow this for Delphi compatibility (PFV) }
  339. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  340. include(current_procinfo.procdef.procoptions,po_assembler);
  341. { Handle assembler block different }
  342. if (po_assembler in current_procinfo.procdef.procoptions) then
  343. begin
  344. block:=assembler_block;
  345. exit;
  346. end;
  347. {Unit initialization?.}
  348. if (
  349. assigned(current_procinfo.procdef.localst) and
  350. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  351. (current_module.is_unit or islibrary)
  352. ) then
  353. begin
  354. if (token=_END) then
  355. begin
  356. consume(_END);
  357. { We need at least a node, else the entry/exit code is not
  358. generated and thus no PASCALMAIN symbol which we need (PFV) }
  359. if islibrary then
  360. block:=cnothingnode.create
  361. else
  362. block:=nil;
  363. end
  364. else
  365. begin
  366. if token=_INITIALIZATION then
  367. begin
  368. { The library init code is already called and does not
  369. need to be in the initfinal table (PFV) }
  370. block:=statement_block(_INITIALIZATION);
  371. end
  372. else if token=_FINALIZATION then
  373. begin
  374. { when a unit has only a finalization section, we can come to this
  375. point when we try to read the nonh existing initalization section
  376. so we've to check if we are really try to parse the finalization }
  377. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  378. block:=statement_block(_FINALIZATION)
  379. else
  380. block:=nil;
  381. end
  382. else
  383. block:=statement_block(_BEGIN);
  384. end;
  385. end
  386. else
  387. begin
  388. { parse routine body }
  389. block:=statement_block(_BEGIN);
  390. init_main_block_syms(block);
  391. end;
  392. end;
  393. {****************************************************************************
  394. PROCEDURE/FUNCTION COMPILING
  395. ****************************************************************************}
  396. procedure printnode_reset;
  397. begin
  398. assign(printnodefile,treelogfilename);
  399. {$push}{$I-}
  400. rewrite(printnodefile);
  401. {$pop}
  402. if ioresult<>0 then
  403. begin
  404. Comment(V_Error,'Error creating '+treelogfilename);
  405. exit;
  406. end;
  407. close(printnodefile);
  408. end;
  409. procedure add_label_init(p:TObject;arg:pointer);
  410. begin
  411. if not assigned(setjmpresulttype) then
  412. setjmpresulttype:=search_system_proc('fpc_setjmp').returndef;
  413. if tstoredsym(p).typ=labelsym then
  414. begin
  415. addstatement(tstatementnode(arg^),
  416. cifnode.create(caddnode.create(equaln,
  417. ccallnode.createintern('fpc_setjmp',
  418. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  419. cordconstnode.create(1,setjmpresulttype,true))
  420. ,cgotonode.create(tlabelsym(p)),nil)
  421. );
  422. end;
  423. end;
  424. function generate_bodyentry_block:tnode;
  425. var
  426. srsym : tsym;
  427. para : tcallparanode;
  428. call : tcallnode;
  429. newstatement : tstatementnode;
  430. def : tabstractrecorddef;
  431. begin
  432. result:=internalstatements(newstatement);
  433. if assigned(current_structdef) then
  434. begin
  435. { a constructor needs a help procedure }
  436. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  437. begin
  438. if is_class(current_structdef) or
  439. (
  440. is_objectpascal_helper(current_structdef) and
  441. is_class(tobjectdef(current_structdef).extendeddef)
  442. ) then
  443. begin
  444. if is_objectpascal_helper(current_structdef) then
  445. def:=tabstractrecorddef(tobjectdef(current_structdef).extendeddef)
  446. else
  447. def:=current_structdef;
  448. srsym:=search_struct_member(def,'NEWINSTANCE');
  449. if assigned(srsym) and
  450. (srsym.typ=procsym) then
  451. begin
  452. { if vmt=1 then newinstance }
  453. addstatement(newstatement,cifnode.create(
  454. caddnode.create_internal(equaln,
  455. ctypeconvnode.create_internal(
  456. load_vmt_pointer_node,
  457. voidpointertype),
  458. cpointerconstnode.create(1,voidpointertype)),
  459. cassignmentnode.create(
  460. ctypeconvnode.create_internal(
  461. load_self_pointer_node,
  462. voidpointertype),
  463. ccallnode.create(nil,tprocsym(srsym),srsym.owner,
  464. ctypeconvnode.create_internal(load_self_pointer_node,cclassrefdef.create(current_structdef)),
  465. [],nil)),
  466. nil));
  467. end
  468. else
  469. internalerror(200305108);
  470. end
  471. else
  472. if is_object(current_structdef) then
  473. begin
  474. { parameter 3 : vmt_offset }
  475. { parameter 2 : address of pointer to vmt,
  476. this is required to allow setting the vmt to -1 to indicate
  477. that memory was allocated }
  478. { parameter 1 : self pointer }
  479. para:=ccallparanode.create(
  480. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  481. ccallparanode.create(
  482. ctypeconvnode.create_internal(
  483. load_vmt_pointer_node,
  484. voidpointertype),
  485. ccallparanode.create(
  486. ctypeconvnode.create_internal(
  487. load_self_pointer_node,
  488. voidpointertype),
  489. nil)));
  490. addstatement(newstatement,cassignmentnode.create(
  491. ctypeconvnode.create_internal(
  492. load_self_pointer_node,
  493. voidpointertype),
  494. ccallnode.createintern('fpc_help_constructor',para)));
  495. end
  496. else
  497. if is_javaclass(current_structdef) or
  498. ((target_info.system in systems_jvm) and
  499. is_record(current_structdef)) then
  500. begin
  501. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  502. not current_procinfo.ConstructorCallingConstructor then
  503. begin
  504. { call inherited constructor }
  505. if is_javaclass(current_structdef) then
  506. srsym:=search_struct_member_no_helper(tobjectdef(current_structdef).childof,'CREATE')
  507. else
  508. srsym:=search_struct_member_no_helper(java_fpcbaserecordtype,'CREATE');
  509. if assigned(srsym) and
  510. (srsym.typ=procsym) then
  511. begin
  512. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited],nil);
  513. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  514. addstatement(newstatement,call);
  515. end
  516. else
  517. internalerror(2011010312);
  518. end;
  519. end
  520. else
  521. if not is_record(current_structdef) and
  522. not (
  523. is_objectpascal_helper(current_structdef) and
  524. (tobjectdef(current_structdef).extendeddef.typ<>objectdef)
  525. ) then
  526. internalerror(200305103);
  527. { if self=nil then exit
  528. calling fail instead of exit is useless because
  529. there is nothing to dispose (PFV) }
  530. if is_class_or_object(current_structdef) then
  531. addstatement(newstatement,cifnode.create(
  532. caddnode.create(equaln,
  533. load_self_pointer_node,
  534. cnilnode.create),
  535. cexitnode.create(nil),
  536. nil));
  537. end;
  538. { maybe call BeforeDestruction for classes }
  539. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  540. is_class(current_structdef) then
  541. begin
  542. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  543. if assigned(srsym) and
  544. (srsym.typ=procsym) then
  545. begin
  546. { if vmt>0 then beforedestruction }
  547. addstatement(newstatement,cifnode.create(
  548. caddnode.create(gtn,
  549. ctypeconvnode.create_internal(
  550. load_vmt_pointer_node,ptrsinttype),
  551. ctypeconvnode.create_internal(
  552. cnilnode.create,ptrsinttype)),
  553. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  554. nil));
  555. end
  556. else
  557. internalerror(200305104);
  558. end;
  559. end;
  560. if m_non_local_goto in current_settings.modeswitches then
  561. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  562. end;
  563. function generate_bodyexit_block:tnode;
  564. var
  565. srsym : tsym;
  566. para : tcallparanode;
  567. newstatement : tstatementnode;
  568. oldlocalswitches: tlocalswitches;
  569. begin
  570. result:=internalstatements(newstatement);
  571. if assigned(current_structdef) then
  572. begin
  573. { Don't test self and the vmt here. The reason is that }
  574. { a constructor already checks whether these are valid }
  575. { before. Further, in case of TThread the thread may }
  576. { free the class instance right after AfterConstruction }
  577. { has been called, so it may no longer be valid (JM) }
  578. oldlocalswitches:=current_settings.localswitches;
  579. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  580. { a destructor needs a help procedure }
  581. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  582. begin
  583. if is_class(current_structdef) then
  584. begin
  585. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  586. if assigned(srsym) and
  587. (srsym.typ=procsym) then
  588. begin
  589. { if self<>0 and vmt<>0 then freeinstance }
  590. addstatement(newstatement,cifnode.create(
  591. caddnode.create(andn,
  592. caddnode.create(unequaln,
  593. load_self_pointer_node,
  594. cnilnode.create),
  595. caddnode.create(unequaln,
  596. ctypeconvnode.create(
  597. load_vmt_pointer_node,
  598. voidpointertype),
  599. cpointerconstnode.create(0,voidpointertype))),
  600. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  601. nil));
  602. end
  603. else
  604. internalerror(2003051001);
  605. end
  606. else
  607. if is_object(current_structdef) then
  608. begin
  609. { finalize object data, but only if not in inherited call }
  610. if is_managed_type(current_structdef) then
  611. begin
  612. addstatement(newstatement,cifnode.create(
  613. caddnode.create(unequaln,
  614. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  615. cnilnode.create),
  616. cnodeutils.finalize_data_node(load_self_node),
  617. nil));
  618. end;
  619. { parameter 3 : vmt_offset }
  620. { parameter 2 : pointer to vmt }
  621. { parameter 1 : self pointer }
  622. para:=ccallparanode.create(
  623. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  624. ccallparanode.create(
  625. ctypeconvnode.create_internal(
  626. load_vmt_pointer_node,
  627. voidpointertype),
  628. ccallparanode.create(
  629. ctypeconvnode.create_internal(
  630. load_self_pointer_node,
  631. voidpointertype),
  632. nil)));
  633. addstatement(newstatement,
  634. ccallnode.createintern('fpc_help_destructor',para));
  635. end
  636. else if is_javaclass(current_structdef) then
  637. begin
  638. { nothing to do }
  639. end
  640. else
  641. internalerror(200305105);
  642. end;
  643. current_settings.localswitches:=oldlocalswitches;
  644. end;
  645. end;
  646. {****************************************************************************
  647. TCGProcInfo
  648. ****************************************************************************}
  649. destructor tcgprocinfo.destroy;
  650. var
  651. i : longint;
  652. begin
  653. if assigned(tempinfo_flags_map) then
  654. begin
  655. for i:=0 to tempinfo_flags_map.count-1 do
  656. dispose(ptempinfo_flags_entry(tempinfo_flags_map[i]));
  657. tempinfo_flags_map.free;
  658. end;
  659. code.free;
  660. inherited destroy;
  661. end;
  662. function tcgprocinfo.calc_stackframe_size:longint;
  663. begin
  664. result:=Align(tg.direction*tg.lasttemp,current_settings.alignment.localalignmin);
  665. end;
  666. procedure tcgprocinfo.printproc(pass:string);
  667. begin
  668. assign(printnodefile,treelogfilename);
  669. {$push}{$I-}
  670. append(printnodefile);
  671. if ioresult<>0 then
  672. rewrite(printnodefile);
  673. {$pop}
  674. if ioresult<>0 then
  675. begin
  676. Comment(V_Error,'Error creating '+treelogfilename);
  677. exit;
  678. end;
  679. writeln(printnodefile);
  680. writeln(printnodefile,'*******************************************************************************');
  681. writeln(printnodefile, pass);
  682. writeln(printnodefile,procdef.fullprocname(false));
  683. writeln(printnodefile,'*******************************************************************************');
  684. printnode(printnodefile,code);
  685. close(printnodefile);
  686. end;
  687. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  688. var
  689. oldlocalswitches: tlocalswitches;
  690. srsym: tsym;
  691. constructionblock,
  692. exceptblock,
  693. newblock: tblocknode;
  694. newstatement: tstatementnode;
  695. pd: tprocdef;
  696. constructionsuccessful: tlocalvarsym;
  697. begin
  698. if assigned(procdef.struct) and
  699. (procdef.proctypeoption=potype_constructor) then
  700. begin
  701. withexceptblock:=
  702. withexceptblock and
  703. not(target_info.system in systems_garbage_collected_managed_types);
  704. { Don't test self and the vmt here. See generate_bodyexit_block }
  705. { why (JM) }
  706. oldlocalswitches:=current_settings.localswitches;
  707. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  708. { call AfterConstruction for classes }
  709. constructionsuccessful:=nil;
  710. if is_class(procdef.struct) then
  711. begin
  712. constructionsuccessful:=clocalvarsym.create(internaltypeprefixName[itp_vmt_afterconstruction_local],vs_value,ptrsinttype,[]);
  713. procdef.localst.insert(constructionsuccessful,false);
  714. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  715. if not assigned(srsym) or
  716. (srsym.typ<>procsym) then
  717. internalerror(200305106);
  718. current_filepos:=entrypos;
  719. constructionblock:=internalstatements(newstatement);
  720. { initialise constructionsuccessful with -1, indicating that
  721. the construction was not successful and hence
  722. beforedestruction should not be called if a destructor is
  723. called from the constructor }
  724. addstatement(newstatement,cassignmentnode.create(
  725. cloadnode.create(constructionsuccessful,procdef.localst),
  726. genintconstnode(-1))
  727. );
  728. { first execute all constructor code. If no exception
  729. occurred then we will execute afterconstruction,
  730. otherwise we won't (the exception will jump over us) }
  731. addstatement(newstatement,tocode);
  732. current_filepos:=exitpos;
  733. { if implicit finally node wasn't created, then exit label and
  734. finalization code must be handled here and placed before
  735. afterconstruction }
  736. if not ((pi_needs_implicit_finally in flags) and
  737. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  738. begin
  739. include(tocode.flags,nf_block_with_exit);
  740. if procdef.proctypeoption<>potype_exceptfilter then
  741. addstatement(newstatement,cfinalizetempsnode.create);
  742. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  743. temps_finalized:=true;
  744. end;
  745. { construction successful -> beforedestruction should be called
  746. if an exception happens now }
  747. addstatement(newstatement,cassignmentnode.create(
  748. cloadnode.create(constructionsuccessful,procdef.localst),
  749. genintconstnode(1))
  750. );
  751. { Self can be nil when fail is called }
  752. { if self<>nil and vmt<>nil then afterconstruction }
  753. addstatement(newstatement,cifnode.create(
  754. caddnode.create(andn,
  755. caddnode.create(unequaln,
  756. load_self_node,
  757. cnilnode.create),
  758. caddnode.create(unequaln,
  759. load_vmt_pointer_node,
  760. cnilnode.create)),
  761. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  762. nil));
  763. tocode:=constructionblock;
  764. end;
  765. if withexceptblock and (procdef.struct.typ=objectdef) then
  766. begin
  767. { Generate the implicit "fail" code for a constructor (destroy
  768. in case an exception happened) }
  769. pd:=tobjectdef(procdef.struct).find_destructor;
  770. { this will always be the case for classes, since tobject has
  771. a destructor }
  772. if assigned(pd) or is_object(procdef.struct) then
  773. begin
  774. current_filepos:=exitpos;
  775. exceptblock:=internalstatements(newstatement);
  776. { first free the instance if non-nil }
  777. if assigned(pd) then
  778. { if vmt<>0 then call destructor }
  779. addstatement(newstatement,
  780. cifnode.create(
  781. caddnode.create(unequaln,
  782. load_vmt_pointer_node,
  783. cnilnode.create),
  784. { cnf_create_failed -> don't call BeforeDestruction }
  785. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed],nil),
  786. nil))
  787. else
  788. { object without destructor, call 'fail' helper }
  789. addstatement(newstatement,
  790. ccallnode.createintern('fpc_help_fail',
  791. ccallparanode.create(
  792. cordconstnode.create(tobjectdef(procdef.struct).vmt_offset,s32inttype,false),
  793. ccallparanode.create(
  794. ctypeconvnode.create_internal(
  795. load_vmt_pointer_node,
  796. voidpointertype),
  797. ccallparanode.create(
  798. ctypeconvnode.create_internal(
  799. load_self_pointer_node,
  800. voidpointertype),
  801. nil))))
  802. );
  803. { then re-raise the exception }
  804. addstatement(newstatement,craisenode.create(nil,nil,nil));
  805. current_filepos:=entrypos;
  806. newblock:=internalstatements(newstatement);
  807. { try
  808. tocode
  809. except
  810. exceptblock
  811. end
  812. }
  813. addstatement(newstatement,ctryexceptnode.create(
  814. tocode,
  815. nil,
  816. exceptblock));
  817. tocode:=newblock;
  818. end;
  819. end;
  820. current_settings.localswitches:=oldlocalswitches;
  821. end;
  822. end;
  823. procedure tcgprocinfo.add_entry_exit_code;
  824. var
  825. finalcode,
  826. bodyentrycode,
  827. bodyexitcode,
  828. wrappedbody,
  829. newblock : tnode;
  830. codestatement,
  831. newstatement : tstatementnode;
  832. oldfilepos : tfileposinfo;
  833. is_constructor: boolean;
  834. begin
  835. is_constructor:=assigned(procdef.struct) and
  836. (procdef.proctypeoption=potype_constructor);
  837. oldfilepos:=current_filepos;
  838. { Generate code/locations used at start of proc }
  839. current_filepos:=entrypos;
  840. entry_asmnode:=casmnode.create_get_position;
  841. loadpara_asmnode:=casmnode.create_get_position;
  842. stackcheck_asmnode:=casmnode.create_get_position;
  843. init_asmnode:=casmnode.create_get_position;
  844. bodyentrycode:=generate_bodyentry_block;
  845. { Generate code/locations used at end of proc }
  846. current_filepos:=exitpos;
  847. exitlabel_asmnode:=casmnode.create_get_position;
  848. temps_finalized:=false;
  849. bodyexitcode:=generate_bodyexit_block;
  850. { Check if bodyexitcode is not empty }
  851. with tstatementnode(tblocknode(bodyexitcode).statements) do
  852. if (statement.nodetype<>nothingn) or assigned(next) then
  853. { Indicate that the extra code is executed after the exit statement }
  854. include(flowcontrol,fc_no_direct_exit);
  855. { Generate procedure by combining init+body+final,
  856. depending on the implicit finally we need to add
  857. an try...finally...end wrapper }
  858. current_filepos:=entrypos;
  859. newblock:=internalstatements(newstatement);
  860. { initialization is common for all cases }
  861. addstatement(newstatement,loadpara_asmnode);
  862. addstatement(newstatement,stackcheck_asmnode);
  863. addstatement(newstatement,entry_asmnode);
  864. cnodeutils.procdef_block_add_implicit_initialize_nodes(procdef,newstatement);
  865. addstatement(newstatement,init_asmnode);
  866. if assigned(procdef.parentfpinitblock) then
  867. begin
  868. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  869. begin
  870. { could be an asmn in case of a pure assembler procedure,
  871. but those shouldn't access nested variables }
  872. addstatement(newstatement,procdef.parentfpinitblock);
  873. end
  874. else
  875. procdef.parentfpinitblock.free;
  876. procdef.parentfpinitblock:=nil;
  877. end;
  878. addstatement(newstatement,bodyentrycode);
  879. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  880. (pi_needs_implicit_finally in flags) and
  881. { but it's useless in init/final code of units }
  882. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  883. not(target_info.system in systems_garbage_collected_managed_types) and
  884. (f_exceptions in features) then
  885. begin
  886. { Any result of managed type must be returned in parameter }
  887. if is_managed_type(procdef.returndef) and
  888. (not paramanager.ret_in_param(procdef.returndef,procdef)) and
  889. (not is_class(procdef.returndef)) then
  890. InternalError(2013121301);
  891. { Generate special exception block only needed when
  892. implicit finally is used }
  893. current_filepos:=exitpos;
  894. { Generate code that will be in the try...finally }
  895. finalcode:=internalstatements(codestatement);
  896. if procdef.proctypeoption<>potype_exceptfilter then
  897. addstatement(codestatement,cfinalizetempsnode.create);
  898. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,codestatement);
  899. temps_finalized:=true;
  900. current_filepos:=entrypos;
  901. wrappedbody:=ctryfinallynode.create_implicit(code,finalcode);
  902. { afterconstruction must be called after finalizetemps, because it
  903. has to execute after the temps have been finalised in case of a
  904. refcounted class (afterconstruction decreases the refcount
  905. without freeing the instance if the count becomes nil, while
  906. the finalising of the temps can free the instance) }
  907. maybe_add_constructor_wrapper(wrappedbody,true);
  908. addstatement(newstatement,wrappedbody);
  909. addstatement(newstatement,exitlabel_asmnode);
  910. addstatement(newstatement,bodyexitcode);
  911. { set flag the implicit finally has been generated }
  912. include(flags,pi_has_implicit_finally);
  913. end
  914. else
  915. begin
  916. { constructors need destroy-on-exception code even if they don't
  917. have managed variables/temps }
  918. maybe_add_constructor_wrapper(code,
  919. (cs_implicit_exceptions in current_settings.moduleswitches) and (f_exceptions in features));
  920. current_filepos:=entrypos;
  921. addstatement(newstatement,code);
  922. current_filepos:=exitpos;
  923. if assigned(nestedexitlabel) then
  924. addstatement(newstatement,clabelnode.create(cnothingnode.create,nestedexitlabel));
  925. addstatement(newstatement,exitlabel_asmnode);
  926. addstatement(newstatement,bodyexitcode);
  927. if not is_constructor then
  928. begin
  929. if procdef.proctypeoption<>potype_exceptfilter then
  930. addstatement(newstatement,cfinalizetempsnode.create);
  931. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  932. temps_finalized:=true;
  933. end;
  934. end;
  935. if not temps_finalized then
  936. begin
  937. current_filepos:=exitpos;
  938. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  939. end;
  940. do_firstpass(newblock);
  941. code:=newblock;
  942. current_filepos:=oldfilepos;
  943. end;
  944. procedure clearrefs(p:TObject;arg:pointer);
  945. begin
  946. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  947. if tabstractvarsym(p).refs>1 then
  948. tabstractvarsym(p).refs:=1;
  949. end;
  950. procedure translate_registers(p:TObject;list:pointer);
  951. begin
  952. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  953. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  954. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  955. begin
  956. if not(cs_no_regalloc in current_settings.globalswitches) then
  957. begin
  958. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  959. if (tabstractnormalvarsym(p).localloc.registerhi<>NR_NO) then
  960. cg.translate_register(tabstractnormalvarsym(p).localloc.registerhi);
  961. end;
  962. end;
  963. end;
  964. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(riscv32) or defined(riscv64) or defined(m68k)}
  965. const
  966. exception_flags: array[boolean] of tprocinfoflags = (
  967. [],
  968. [pi_uses_exceptions,pi_needs_implicit_finally,pi_has_implicit_finally]
  969. );
  970. {$endif}
  971. procedure tcgprocinfo.setup_tempgen;
  972. begin
  973. tg:=tgobjclass.create;
  974. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(m68k)}
  975. {$if defined(arm)}
  976. { frame and stack pointer must be always the same on arm thumb so it makes no
  977. sense to fiddle with a frame pointer }
  978. if GenerateThumbCode then
  979. begin
  980. framepointer:=NR_STACK_POINTER_REG;
  981. tg.direction:=1;
  982. end
  983. else
  984. {$endif defined(arm)}
  985. begin
  986. { try to strip the stack frame }
  987. { set the framepointer to esp if:
  988. - no assembler directive, those are handled in assembler_block
  989. in pstatment.pas (for cases not caught by the Delphi
  990. exception below)
  991. - no exceptions are used
  992. - no pushes are used/esp modifications, could be:
  993. * outgoing parameters on the stack on non-fixed stack target
  994. * incoming parameters on the stack
  995. * open arrays
  996. - no inline assembler
  997. or
  998. - Delphi mode
  999. - assembler directive
  1000. - no pushes are used/esp modifications, could be:
  1001. * outgoing parameters on the stack
  1002. * incoming parameters on the stack
  1003. * open arrays
  1004. - no local variables
  1005. - stack frame cannot be optimized if using Win64 SEH
  1006. (at least with the current state of our codegenerator).
  1007. }
  1008. if ((po_assembler in procdef.procoptions) and
  1009. (m_delphi in current_settings.modeswitches) and
  1010. { localst at main_program_level is a staticsymtable }
  1011. (procdef.localst.symtablelevel<>main_program_level) and
  1012. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  1013. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  1014. not(cs_generate_stackframes in current_settings.localswitches) and
  1015. not(cs_profile in current_settings.moduleswitches) and
  1016. not(po_assembler in procdef.procoptions) and
  1017. not ((pi_has_stackparameter in flags)
  1018. {$ifndef arm} { Outgoing parameter(s) on stack do not need stackframe on x86 targets
  1019. with fixed stack. On ARM it fails, see bug #25050 }
  1020. and (not paramanager.use_fixed_stack)
  1021. {$endif arm}
  1022. ) and
  1023. ((flags*([pi_has_assembler_block,pi_is_assembler,
  1024. pi_needs_stackframe]+
  1025. exception_flags[((target_info.cpu=cpu_i386) and (not paramanager.use_fixed_stack))
  1026. {$ifndef DISABLE_WIN64_SEH}
  1027. or (target_info.system=system_x86_64_win64)
  1028. {$endif DISABLE_WIN64_SEH}
  1029. ]))=[])
  1030. )
  1031. then
  1032. begin
  1033. { we need the parameter info here to determine if the procedure gets
  1034. parameters on the stack
  1035. calling generate_parameter_info doesn't hurt but it costs time
  1036. (necessary to init para_stack_size)
  1037. }
  1038. generate_parameter_info;
  1039. if not(procdef.stack_tainting_parameter(calleeside)) and
  1040. not(has_assembler_child)
  1041. { parasize must be really zero, this means also that no result may be returned
  1042. in a parameter }
  1043. and not((current_procinfo.procdef.proccalloption in clearstack_pocalls) and
  1044. not(current_procinfo.procdef.generate_safecall_wrapper) and
  1045. paramanager.ret_in_param(current_procinfo.procdef.returndef,current_procinfo.procdef)) then
  1046. begin
  1047. { Only need to set the framepointer }
  1048. framepointer:=NR_STACK_POINTER_REG;
  1049. tg.direction:=1;
  1050. end
  1051. {$if defined(arm)}
  1052. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1053. in case parameters are passed on the stack.
  1054. However, the draw back is, if the estimation fails, compilation will break later on
  1055. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1056. multipass compilation of subroutines must be supported
  1057. }
  1058. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1059. not(has_assembler_child) then
  1060. begin
  1061. { Only need to set the framepointer }
  1062. framepointer:=NR_STACK_POINTER_REG;
  1063. tg.direction:=1;
  1064. include(flags,pi_estimatestacksize);
  1065. set_first_temp_offset;
  1066. procdef.has_paraloc_info:=callnoside;
  1067. generate_parameter_info;
  1068. exit;
  1069. end;
  1070. {$endif defined(arm)}
  1071. end;
  1072. end;
  1073. {$endif defined(x86) or defined(arm) or defined(m68k)}
  1074. {$if defined(xtensa)}
  1075. { On xtensa, the stack frame size can be estimated to avoid using an extra frame pointer,
  1076. in case parameters are passed on the stack.
  1077. However, the draw back is, if the estimation fails, compilation will break later on
  1078. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1079. multipass compilation of subroutines must be supported
  1080. }
  1081. if procdef.stack_tainting_parameter(calleeside) then
  1082. begin
  1083. include(flags,pi_estimatestacksize);
  1084. set_first_temp_offset;
  1085. procdef.has_paraloc_info:=callnoside;
  1086. generate_parameter_info;
  1087. exit;
  1088. end;
  1089. {$endif defined(xtensa)}
  1090. { set the start offset to the start of the temp area in the stack }
  1091. set_first_temp_offset;
  1092. end;
  1093. procedure tcgprocinfo.OptimizeNodeTree;
  1094. var
  1095. i : integer;
  1096. RedoDFA: Boolean;
  1097. {RedoDFA : boolean;}
  1098. begin
  1099. { do this before adding the entry code else the tail recursion recognition won't work,
  1100. if this causes troubles, it must be if'ed
  1101. }
  1102. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1103. (pi_is_recursive in flags) then
  1104. do_opttail(code,procdef);
  1105. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1106. do_optconstpropagate(code);
  1107. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1108. { creating dfa is not always possible }
  1109. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1110. begin
  1111. dfabuilder:=TDFABuilder.Create;
  1112. dfabuilder.createdfainfo(code);
  1113. include(flags,pi_dfaavailable);
  1114. RedoDFA:=false;
  1115. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1116. { our induction variable strength reduction doesn't like
  1117. for loops with more than one entry }
  1118. and not(pi_has_label in flags) then
  1119. begin
  1120. RedoDFA:=OptimizeInductionVariables(code);
  1121. end;
  1122. if RedoDFA then
  1123. begin
  1124. dfabuilder.resetdfainfo(code);
  1125. dfabuilder.createdfainfo(code);
  1126. include(flags,pi_dfaavailable);
  1127. end;
  1128. RedoDFA:=OptimizeForLoop(code);
  1129. RedoDFA:=ConvertForLoops(code) or RedoDFA;
  1130. if RedoDFA then
  1131. begin
  1132. dfabuilder.resetdfainfo(code);
  1133. dfabuilder.createdfainfo(code);
  1134. include(flags,pi_dfaavailable);
  1135. end;
  1136. { when life info is available, we can give more sophisticated warning about uninitialized
  1137. variables ...
  1138. ... but not for the finalization section of a unit, we would need global dfa to handle
  1139. it properly }
  1140. if potype_unitfinalize<>procdef.proctypeoption then
  1141. { iterate through life info of the first node }
  1142. for i:=0 to dfabuilder.nodemap.count-1 do
  1143. begin
  1144. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1145. begin
  1146. { do not warn for certain parameters: }
  1147. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1148. { do not warn about parameters passed by var }
  1149. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1150. { function result is passed by var but it must be initialized }
  1151. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1152. { do not warn about initialized hidden parameters }
  1153. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1154. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1155. end
  1156. else
  1157. begin
  1158. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1159. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1160. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1161. end;
  1162. end;
  1163. end
  1164. else
  1165. begin
  1166. ConvertForLoops(code);
  1167. end;
  1168. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1169. do_optdeadstoreelim(code);
  1170. if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
  1171. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1172. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1173. procdef.isempty:=true;
  1174. end;
  1175. function tcgprocinfo.has_assembler_child : boolean;
  1176. var
  1177. hp : tprocinfo;
  1178. begin
  1179. result:=false;
  1180. hp:=get_first_nestedproc;
  1181. while assigned(hp) do
  1182. begin
  1183. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  1184. begin
  1185. result:=true;
  1186. exit;
  1187. end;
  1188. hp:=tprocinfo(hp.next);
  1189. end;
  1190. end;
  1191. procedure tcgprocinfo.set_eh_info;
  1192. begin
  1193. inherited;
  1194. if (tf_use_psabieh in target_info.flags) and
  1195. ((pi_uses_exceptions in flags) or
  1196. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1197. (pi_needs_implicit_finally in flags))) or
  1198. (pi_has_except_table_data in flags) then
  1199. procdef.personality:=search_system_proc('_FPC_PSABIEH_PERSONALITY_V0');
  1200. end;
  1201. function tcgprocinfo.store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  1202. var
  1203. nodeset : THashSet absolute arg;
  1204. entry : ptempinfo_flags_entry;
  1205. i : longint;
  1206. {hashsetitem: PHashSetItem;}
  1207. begin
  1208. result:=fen_true;
  1209. case n.nodetype of
  1210. tempcreaten:
  1211. begin
  1212. {$ifdef EXTDEBUG}
  1213. comment(V_Debug,'keeping track of new temp node: '+hexstr(ttempbasenode(n).tempinfo));
  1214. {$endif EXTDEBUG}
  1215. nodeset.FindOrAdd(ttempbasenode(n).tempinfo,sizeof(pointer));
  1216. end;
  1217. tempdeleten:
  1218. begin
  1219. {$ifdef EXTDEBUG}
  1220. comment(V_Debug,'got temp delete node: '+hexstr(ttempbasenode(n).tempinfo));
  1221. {$endif EXTDEBUG}
  1222. { don't remove temp nodes so that outside code can know if some temp
  1223. was only created in here }
  1224. (*hashsetitem:=nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer));
  1225. if assigned(hashsetitem) then
  1226. begin
  1227. {$ifdef EXTDEBUG}
  1228. comment(V_Debug,'no longer keeping track of temp node');
  1229. {$endif EXTDEBUG}
  1230. writeln('no longer keeping track of temp node');
  1231. nodeset.Remove(hashsetitem);
  1232. end;*)
  1233. end;
  1234. temprefn:
  1235. begin
  1236. {$ifdef EXTDEBUG}
  1237. comment(V_Debug,'found temp ref node: '+hexstr(ttempbasenode(n).tempinfo));
  1238. {$endif EXTDEBUG}
  1239. if not assigned(nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer))) then
  1240. begin
  1241. for i:=0 to tempinfo_flags_map.count-1 do
  1242. begin
  1243. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1244. {$ifdef EXTDEBUG}
  1245. comment(V_Debug,'comparing with tempinfo: '+hexstr(entry^.tempinfo));
  1246. {$endif EXTDEBUG}
  1247. if entry^.tempinfo=ttempbasenode(n).tempinfo then
  1248. begin
  1249. {$ifdef EXTDEBUG}
  1250. comment(V_Debug,'temp node exists');
  1251. {$endif EXTDEBUG}
  1252. exit;
  1253. end;
  1254. end;
  1255. {$ifdef EXTDEBUG}
  1256. comment(V_Debug,'storing node');
  1257. {$endif EXTDEBUG}
  1258. new(entry);
  1259. entry^.tempinfo:=ttempbasenode(n).tempinfo;
  1260. entry^.flags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1261. tempinfo_flags_map.add(entry);
  1262. end
  1263. else
  1264. begin
  1265. {$ifdef EXTDEBUG}
  1266. comment(V_Debug,'ignoring node');
  1267. {$endif EXTDEBUG}
  1268. end;
  1269. end;
  1270. else
  1271. ;
  1272. end;
  1273. end;
  1274. procedure tcgprocinfo.store_tempflags;
  1275. var
  1276. nodeset : THashSet;
  1277. begin
  1278. if assigned(tempinfo_flags_map) then
  1279. internalerror(2020040601);
  1280. {$ifdef EXTDEBUG}
  1281. comment(V_Debug,'storing temp nodes of '+procdef.mangledname);
  1282. {$endif EXTDEBUG}
  1283. tempinfo_flags_map:=tfplist.create;
  1284. nodeset:=THashSet.Create(32,false,false);
  1285. foreachnode(code,@store_node_tempflags,nodeset);
  1286. nodeset.free;
  1287. end;
  1288. procedure tcgprocinfo.swap_tempflags;
  1289. var
  1290. entry : ptempinfo_flags_entry;
  1291. i : longint;
  1292. tempflags : ttempinfoflags;
  1293. begin
  1294. if not assigned(tempinfo_flags_map) then
  1295. exit;
  1296. for i:=0 to tempinfo_flags_map.count-1 do
  1297. begin
  1298. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1299. tempflags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1300. ttempinfoaccessor.settempinfoflags(entry^.tempinfo,entry^.flags);
  1301. entry^.flags:=tempflags;
  1302. end;
  1303. end;
  1304. procedure tcgprocinfo.apply_tempflags;
  1305. begin
  1306. if tempflags_swapped then
  1307. internalerror(2020040602);
  1308. swap_tempflags;
  1309. tempflags_swapped:=true;
  1310. end;
  1311. procedure tcgprocinfo.reset_tempflags;
  1312. begin
  1313. if not tempflags_swapped then
  1314. internalerror(2020040603);
  1315. swap_tempflags;
  1316. tempflags_swapped:=false;
  1317. end;
  1318. {$ifdef DEBUG_NODE_XML}
  1319. procedure tcgprocinfo.XMLPrintProc(FirstHalf: Boolean);
  1320. var
  1321. T: Text;
  1322. W: Word;
  1323. syssym: tsyssym;
  1324. separate : boolean;
  1325. procedure PrintType(Flag: string);
  1326. begin
  1327. if df_generic in procdef.defoptions then
  1328. Write(T, ' type="generic ', Flag, '"')
  1329. else
  1330. Write(T, ' type="', Flag, '"');
  1331. end;
  1332. procedure PrintOption(Flag: string);
  1333. begin
  1334. WriteLn(T, PrintNodeIndention, '<option>', Flag, '</option>');
  1335. end;
  1336. begin
  1337. if current_module.ppxfilefail then
  1338. Exit;
  1339. Assign(T, current_module.ppxfilename);
  1340. {$push} {$I-}
  1341. Append(T);
  1342. if IOResult <> 0 then
  1343. begin
  1344. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  1345. current_module.ppxfilefail := True;
  1346. Exit;
  1347. end;
  1348. {$pop}
  1349. separate := (df_generic in procdef.defoptions);
  1350. { First half prints the header and the nodes as a "code" tag }
  1351. if FirstHalf or separate then
  1352. begin
  1353. Write(T, PrintNodeIndention, '<subroutine');
  1354. { Check to see if the procedure is a class or object method }
  1355. if Assigned(procdef.struct) then
  1356. begin
  1357. if Assigned(procdef.struct.objrealname) then
  1358. Write(T, ' struct="', SanitiseXMLString(procdef.struct.objrealname^), '"')
  1359. else
  1360. Write(T, ' struct="&lt;NULL&gt;"');
  1361. end;
  1362. case procdef.proctypeoption of
  1363. potype_none:
  1364. { Do nothing - should this be an internal error though? };
  1365. potype_procedure,
  1366. potype_function:
  1367. if po_classmethod in procdef.procoptions then
  1368. begin
  1369. if po_staticmethod in procdef.procoptions then
  1370. PrintType('static class method')
  1371. else
  1372. PrintType('class method');
  1373. end
  1374. else if df_generic in procdef.defoptions then
  1375. Write(T, ' type="generic"');
  1376. potype_proginit,
  1377. potype_unitinit:
  1378. PrintType('initialization');
  1379. potype_unitfinalize:
  1380. PrintType('finalization');
  1381. potype_constructor:
  1382. PrintType('constructor');
  1383. potype_destructor:
  1384. PrintType('destructor');
  1385. potype_operator:
  1386. PrintType('operator');
  1387. potype_class_constructor:
  1388. PrintType('class constructor');
  1389. potype_class_destructor:
  1390. PrintType('class destructor');
  1391. potype_propgetter:
  1392. PrintType('dispinterface getter');
  1393. potype_propsetter:
  1394. PrintType('dispinterface setter');
  1395. potype_exceptfilter:
  1396. PrintType('except filter');
  1397. potype_mainstub:
  1398. PrintType('main stub');
  1399. potype_libmainstub:
  1400. PrintType('library main stub');
  1401. potype_pkgstub:
  1402. PrintType('package stub');
  1403. end;
  1404. Write(T, ' name="', SanitiseXMLString(procdef.customprocname([pno_showhidden, pno_noclassmarker])), '"');
  1405. if po_hascallingconvention in procdef.procoptions then
  1406. Write(T, ' convention="', proccalloptionStr[procdef.proccalloption], '"');
  1407. WriteLn(T, '>');
  1408. PrintNodeIndent;
  1409. if Assigned(procdef.returndef) and not is_void(procdef.returndef) then
  1410. WriteLn(T, PrintNodeIndention, '<returndef>', SanitiseXMLString(procdef.returndef.typesymbolprettyname), '</returndef>');
  1411. if po_reintroduce in procdef.procoptions then
  1412. PrintOption('reintroduce');
  1413. if po_virtualmethod in procdef.procoptions then
  1414. PrintOption('virtual');
  1415. if po_finalmethod in procdef.procoptions then
  1416. PrintOption('final');
  1417. if po_overridingmethod in procdef.procoptions then
  1418. PrintOption('override');
  1419. if po_overload in procdef.procoptions then
  1420. PrintOption('overload');
  1421. if po_compilerproc in procdef.procoptions then
  1422. PrintOption('compilerproc');
  1423. if po_assembler in procdef.procoptions then
  1424. PrintOption('assembler');
  1425. if po_nostackframe in procdef.procoptions then
  1426. PrintOption('nostackframe');
  1427. if po_inline in procdef.procoptions then
  1428. PrintOption('inline');
  1429. if po_noreturn in procdef.procoptions then
  1430. PrintOption('noreturn');
  1431. if po_noinline in procdef.procoptions then
  1432. PrintOption('noinline');
  1433. end;
  1434. if Assigned(Code) then
  1435. begin
  1436. if FirstHalf then
  1437. WriteLn(T, PrintNodeIndention, '<code>')
  1438. else
  1439. begin
  1440. WriteLn(T); { Line for spacing }
  1441. WriteLn(T, PrintNodeIndention, '<firstpass>');
  1442. end;
  1443. PrintNodeIndent;
  1444. XMLPrintNode(T, Code);
  1445. PrintNodeUnindent;
  1446. if FirstHalf then
  1447. WriteLn(T, PrintNodeIndention, '</code>')
  1448. else
  1449. WriteLn(T, PrintNodeIndention, '</firstpass>');
  1450. end
  1451. else { Code=Nil }
  1452. begin
  1453. { Don't print anything for second half - if there's no code, there's no firstpass }
  1454. if FirstHalf then
  1455. WriteLn(T, PrintNodeIndention, '<code />');
  1456. end;
  1457. { Print footer only for second half }
  1458. if (not FirstHalf) or separate then
  1459. begin
  1460. PrintNodeUnindent;
  1461. WriteLn(T, PrintNodeIndention, '</subroutine>');
  1462. WriteLn(T); { Line for spacing }
  1463. end;
  1464. Close(T);
  1465. end;
  1466. {$endif DEBUG_NODE_XML}
  1467. procedure tcgprocinfo.generate_code_tree;
  1468. var
  1469. hpi : tcgprocinfo;
  1470. begin
  1471. { generate code for this procedure }
  1472. generate_code;
  1473. { process nested procedures }
  1474. hpi:=tcgprocinfo(get_first_nestedproc);
  1475. while assigned(hpi) do
  1476. begin
  1477. hpi.generate_code_tree;
  1478. hpi:=tcgprocinfo(hpi.next);
  1479. end;
  1480. resetprocdef;
  1481. end;
  1482. procedure tcgprocinfo.generate_code_exceptfilters;
  1483. var
  1484. hpi : tcgprocinfo;
  1485. begin
  1486. hpi:=tcgprocinfo(get_first_nestedproc);
  1487. while assigned(hpi) do
  1488. begin
  1489. if hpi.procdef.proctypeoption=potype_exceptfilter then
  1490. begin
  1491. hpi.apply_tempflags;
  1492. generate_exceptfilter(hpi);
  1493. hpi.reset_tempflags;
  1494. end;
  1495. hpi:=tcgprocinfo(hpi.next);
  1496. end;
  1497. end;
  1498. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  1499. which can be called by OS during stack unwind. This resembles nested procedures,
  1500. but finalizer procedures do not have their own local variables and work directly
  1501. with the stack frame of parent. In particular, the tempgen must be shared, so
  1502. 1) finalizer procedure is able to finalize temps of the parent,
  1503. 2) if the finalizer procedure is complex enough to need its own temps, they are
  1504. allocated in stack frame of parent, so second-level finalizer procedures are
  1505. not needed.
  1506. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  1507. procedure (after the parent) and have to do it inline.
  1508. This is called by platform-specific tryfinallynodes during pass2.
  1509. Here we put away the codegen (which carries the register allocator state), process
  1510. the 'nested' procedure, then restore previous cg and continue processing the parent
  1511. procedure. generate_code() will create another cg, but not another tempgen because
  1512. setup_tempgen() is not called for potype_exceptfilter procedures. }
  1513. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  1514. var
  1515. saved_cg: tcg;
  1516. saved_hlcg: thlcgobj;
  1517. {$ifdef cpu64bitalu}
  1518. saved_cg128 : tcg128;
  1519. {$else cpu64bitalu}
  1520. saved_cg64 : tcg64;
  1521. {$endif cpu64bitalu}
  1522. begin
  1523. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  1524. InternalError(201201141);
  1525. { flush code generated this far }
  1526. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1527. { save the codegen }
  1528. saved_cg:=cg;
  1529. saved_hlcg:=hlcg;
  1530. cg:=nil;
  1531. hlcg:=nil;
  1532. {$ifdef cpu64bitalu}
  1533. saved_cg128:=cg128;
  1534. cg128:=nil;
  1535. {$else cpu64bitalu}
  1536. saved_cg64:=cg64;
  1537. cg64:=nil;
  1538. {$endif cpu64bitalu}
  1539. nestedpi.generate_code;
  1540. { prevents generating code the second time when processing nested procedures }
  1541. nestedpi.resetprocdef;
  1542. cg:=saved_cg;
  1543. hlcg:=saved_hlcg;
  1544. {$ifdef cpu64bitalu}
  1545. cg128:=saved_cg128;
  1546. {$else cpu64bitalu}
  1547. cg64:=saved_cg64;
  1548. {$endif cpu64bitalu}
  1549. add_reg_instruction_hook:[email protected]_reg_instruction;
  1550. end;
  1551. procedure TCGProcinfo.CreateInlineInfo;
  1552. begin
  1553. new(procdef.inlininginfo);
  1554. procdef.inlininginfo^.code:=code.getcopy;
  1555. procdef.inlininginfo^.flags:=flags;
  1556. { The blocknode needs to set an exit label }
  1557. if procdef.inlininginfo^.code.nodetype=blockn then
  1558. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1559. procdef.has_inlininginfo:=true;
  1560. export_local_ref_syms;
  1561. export_local_ref_defs;
  1562. end;
  1563. procedure searchthreadvar(p: TObject; arg: pointer);
  1564. var
  1565. i : longint;
  1566. pd : tprocdef;
  1567. begin
  1568. case tsym(p).typ of
  1569. staticvarsym :
  1570. begin
  1571. { local (procedure or unit) variables only need finalization
  1572. if they are used
  1573. }
  1574. if (vo_is_thread_var in tstaticvarsym(p).varoptions) and
  1575. ((tstaticvarsym(p).refs>0) or
  1576. { global (unit) variables always need finalization, since
  1577. they may also be used in another unit
  1578. }
  1579. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  1580. (
  1581. (tstaticvarsym(p).varspez<>vs_const) or
  1582. (vo_force_finalize in tstaticvarsym(p).varoptions)
  1583. ) and
  1584. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  1585. not(vo_is_external in tstaticvarsym(p).varoptions) and
  1586. is_managed_type(tstaticvarsym(p).vardef) then
  1587. include(current_procinfo.flags,pi_uses_threadvar);
  1588. end;
  1589. procsym :
  1590. begin
  1591. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  1592. begin
  1593. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  1594. if assigned(pd.localst) and
  1595. (pd.procsym=tprocsym(p)) and
  1596. (pd.localst.symtabletype<>staticsymtable) then
  1597. pd.localst.SymList.ForEachCall(@searchthreadvar,arg);
  1598. end;
  1599. end;
  1600. else
  1601. ;
  1602. end;
  1603. end;
  1604. function searchusercode(var n: tnode; arg: pointer): foreachnoderesult;
  1605. begin
  1606. if nf_usercode_entry in n.flags then
  1607. begin
  1608. pnode(arg)^:=n;
  1609. result:=fen_norecurse_true
  1610. end
  1611. else
  1612. result:=fen_false;
  1613. end;
  1614. function TCGProcinfo.GetUserCode : tnode;
  1615. var
  1616. n : tnode;
  1617. begin
  1618. n:=nil;
  1619. foreachnodestatic(code,@searchusercode,@n);
  1620. if not(assigned(n)) then
  1621. internalerror(2013111004);
  1622. result:=n;
  1623. end;
  1624. procedure tcgprocinfo.generate_code;
  1625. procedure check_for_threadvars_in_initfinal;
  1626. begin
  1627. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  1628. begin
  1629. { this is also used for initialization of variables in a
  1630. program which does not have a globalsymtable }
  1631. if assigned(current_module.globalsymtable) then
  1632. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1633. TSymtable(current_module.localsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1634. end;
  1635. end;
  1636. var
  1637. old_current_procinfo : tprocinfo;
  1638. oldmaxfpuregisters : longint;
  1639. oldfilepos : tfileposinfo;
  1640. old_current_structdef : tabstractrecorddef;
  1641. oldswitches : tlocalswitches;
  1642. templist : TAsmList;
  1643. headertai : tai;
  1644. procedure delete_marker(anode: tasmnode);
  1645. var
  1646. ai: tai;
  1647. begin
  1648. if assigned(anode) then
  1649. begin
  1650. ai:=anode.currenttai;
  1651. if assigned(ai) then
  1652. begin
  1653. aktproccode.remove(ai);
  1654. ai.free;
  1655. anode.currenttai:=nil;
  1656. end;
  1657. end;
  1658. end;
  1659. begin
  1660. { the initialization procedure can be empty, then we
  1661. don't need to generate anything. When it was an empty
  1662. procedure there would be at least a blocknode }
  1663. if not assigned(code) then
  1664. begin
  1665. {$ifdef DEBUG_NODE_XML}
  1666. { Print out nodes as they appear after the first pass }
  1667. XMLPrintProc(True);
  1668. XMLPrintProc(False);
  1669. {$endif DEBUG_NODE_XML}
  1670. exit;
  1671. end;
  1672. { We need valid code }
  1673. if Errorcount<>0 then
  1674. exit;
  1675. { No code can be generated for generic template }
  1676. if (df_generic in procdef.defoptions) then
  1677. internalerror(200511152);
  1678. { For regular procedures the RA and Tempgen shall not be available yet,
  1679. but exception filters reuse Tempgen of parent }
  1680. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1681. internalerror(200309201);
  1682. old_current_procinfo:=current_procinfo;
  1683. oldfilepos:=current_filepos;
  1684. old_current_structdef:=current_structdef;
  1685. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1686. current_procinfo:=self;
  1687. current_filepos:=entrypos;
  1688. current_structdef:=procdef.struct;
  1689. { store start of user code, it must be a block node, it will be used later one to
  1690. check variable lifeness }
  1691. include(code.flags,nf_usercode_entry);
  1692. { add wrapping code if necessary (initialization of typed constants on
  1693. some platforms, initing of local variables and out parameters with
  1694. trashing values, ...) }
  1695. { init/final code must be wrapped later (after code for main proc body
  1696. has been generated) }
  1697. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1698. code:=cnodeutils.wrap_proc_body(procdef,code);
  1699. { automatic inlining? }
  1700. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1701. not(po_noinline in procdef.procoptions) and
  1702. { no inlining yet? }
  1703. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1704. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1705. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1706. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1707. (not(procdef.proccalloption in [pocall_safecall])) and
  1708. { rough approximation if we should auto inline:
  1709. - if the tree is simple enough
  1710. - if the tree is not too big
  1711. A bigger tree which is simpler might be autoinlined otoh
  1712. a smaller and complexer tree as well: so we use the sum of
  1713. both measures here }
  1714. (node_count(code)+node_complexity(code)<=25) then
  1715. begin
  1716. { Can we inline this procedure? }
  1717. if checknodeinlining(procdef) then
  1718. begin
  1719. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1720. include(procdef.procoptions,po_inline);
  1721. CreateInlineInfo;
  1722. end;
  1723. end;
  1724. templist:=TAsmList.create;
  1725. { add parast/localst to symtablestack }
  1726. add_to_symtablestack;
  1727. { clear register count }
  1728. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1729. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1730. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1731. if (procdef.localst.symtablelevel=main_program_level) and
  1732. (not current_module.is_unit) then
  1733. begin
  1734. include(flags,pi_do_call);
  1735. { the main program never returns due to the do_exit call }
  1736. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1737. include(procdef.procoptions,po_noreturn);
  1738. end;
  1739. { set implicit_finally flag when there are locals/paras to be finalized }
  1740. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1741. begin
  1742. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1743. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1744. end;
  1745. {$ifdef SUPPORT_SAFECALL}
  1746. { set implicit_finally flag for if procedure is safecall }
  1747. if (tf_safecall_exceptions in target_info.flags) and
  1748. (procdef.proccalloption=pocall_safecall) then
  1749. include(flags, pi_needs_implicit_finally);
  1750. {$endif}
  1751. {$ifdef DEBUG_NODE_XML}
  1752. { Print out nodes as they appear after the first pass }
  1753. XMLPrintProc(True);
  1754. {$endif DEBUG_NODE_XML}
  1755. { firstpass everything }
  1756. flowcontrol:=[];
  1757. do_firstpass(code);
  1758. {$if defined(i386) or defined(i8086)}
  1759. if node_resources_fpu(code)>0 then
  1760. include(flags,pi_uses_fpu);
  1761. {$endif i386 or i8086}
  1762. { Print the node to tree.log }
  1763. if paraprintnodetree <> 0 then
  1764. printproc( 'after the firstpass');
  1765. OptimizeNodeTree;
  1766. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1767. require a tls register, so check for such variables }
  1768. check_for_threadvars_in_initfinal;
  1769. { add implicit entry and exit code }
  1770. add_entry_exit_code;
  1771. if cs_opt_nodecse in current_settings.optimizerswitches then
  1772. do_optcse(code);
  1773. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1774. do_optloadmodifystore(code);
  1775. { only do secondpass if there are no errors }
  1776. if (ErrorCount<>0) then
  1777. begin
  1778. {$ifdef DEBUG_NODE_XML}
  1779. { Print out nodes as they appear after the first pass }
  1780. XMLPrintProc(False);
  1781. {$endif DEBUG_NODE_XML}
  1782. end
  1783. else
  1784. begin
  1785. create_hlcodegen;
  1786. setup_eh;
  1787. if (procdef.proctypeoption<>potype_exceptfilter) then
  1788. setup_tempgen;
  1789. { Create register allocator, must come after framepointer is known }
  1790. hlcg.init_register_allocators;
  1791. generate_parameter_info;
  1792. { allocate got register if needed }
  1793. allocate_got_register(aktproccode);
  1794. { allocate got register if needed }
  1795. allocate_tls_register(aktproccode);
  1796. { Allocate space in temp/registers for parast and localst }
  1797. current_filepos:=entrypos;
  1798. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1799. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1800. { Store temp offset for information about 'real' temps }
  1801. tempstart:=tg.lasttemp;
  1802. { Generate code to load register parameters in temps and insert local
  1803. copies for values parameters. This must be done before the code for the
  1804. body is generated because the localloc is updated.
  1805. Note: The generated code will be inserted after the code generation of
  1806. the body is finished, because only then the position is known }
  1807. {$ifdef oldregvars}
  1808. assign_regvars(code);
  1809. {$endif oldreg}
  1810. current_filepos:=entrypos;
  1811. hlcg.gen_load_para_value(templist);
  1812. { caller paraloc info is also necessary in the stackframe_entry
  1813. code of the ppc (and possibly other processors) }
  1814. procdef.init_paraloc_info(callerside);
  1815. CalcExecutionWeights(code);
  1816. { Print the node to tree.log }
  1817. if paraprintnodetree <> 0 then
  1818. printproc( 'right before code generation');
  1819. {$ifdef DEBUG_NODE_XML}
  1820. { Print out nodes as they appear after the first pass }
  1821. XMLPrintProc(False);
  1822. {$endif DEBUG_NODE_XML}
  1823. { generate code for the node tree }
  1824. do_secondpass(code);
  1825. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1826. { The position of the loadpara_asmnode is now known }
  1827. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1828. oldswitches:=current_settings.localswitches;
  1829. { first generate entry and initialize code with the correct
  1830. position and switches }
  1831. current_filepos:=entrypos;
  1832. current_settings.localswitches:=entryswitches;
  1833. cg.set_regalloc_live_range_direction(rad_backwards);
  1834. hlcg.gen_entry_code(templist);
  1835. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1836. hlcg.gen_initialize_code(templist);
  1837. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1838. { now generate finalize and exit code with the correct position
  1839. and switches }
  1840. current_filepos:=exitpos;
  1841. current_settings.localswitches:=exitswitches;
  1842. cg.set_regalloc_live_range_direction(rad_forward);
  1843. if assigned(finalize_procinfo) then
  1844. begin
  1845. if target_info.system in [system_aarch64_win64] then
  1846. tcgprocinfo(finalize_procinfo).store_tempflags
  1847. else
  1848. generate_exceptfilter(tcgprocinfo(finalize_procinfo));
  1849. end
  1850. else if not temps_finalized then
  1851. begin
  1852. hlcg.gen_finalize_code(templist);
  1853. { the finalcode must be concated if there was no position available,
  1854. using insertlistafter will result in an insert at the start
  1855. when currentai=nil }
  1856. aktproccode.concatlist(templist);
  1857. end;
  1858. { insert exit label at the correct position }
  1859. hlcg.a_label(templist,CurrExitLabel);
  1860. if assigned(exitlabel_asmnode.currenttai) then
  1861. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1862. else
  1863. aktproccode.concatlist(templist);
  1864. { exit code }
  1865. hlcg.gen_exit_code(templist);
  1866. aktproccode.concatlist(templist);
  1867. { reset switches }
  1868. current_settings.localswitches:=oldswitches;
  1869. {$ifdef OLDREGVARS}
  1870. { note: this must be done only after as much code as possible has }
  1871. { been generated. The result is that when you ungetregister() a }
  1872. { regvar, it will actually free the regvar (and alse free the }
  1873. { the regvars at the same time). Doing this too early will }
  1874. { confuse the register allocator, as the regvars will still be }
  1875. { used. It should be done before loading the result regs (so }
  1876. { they don't conflict with the regvars) and before }
  1877. { gen_entry_code (that one has to be able to allocate the }
  1878. { regvars again) (JM) }
  1879. free_regvars(aktproccode);
  1880. {$endif OLDREGVARS}
  1881. { generate symbol and save end of header position }
  1882. current_filepos:=entrypos;
  1883. hlcg.gen_proc_symbol(templist);
  1884. headertai:=tai(templist.last);
  1885. { insert symbol }
  1886. aktproccode.insertlist(templist);
  1887. { Free space in temp/registers for parast and localst, must be
  1888. done after gen_entry_code }
  1889. current_filepos:=exitpos;
  1890. { make sure the got/pic register doesn't get freed in the }
  1891. { middle of a loop }
  1892. if (tf_pic_uses_got in target_info.flags) and
  1893. (pi_needs_got in flags) and
  1894. (got<>NR_NO) then
  1895. cg.a_reg_sync(aktproccode,got);
  1896. if (pi_needs_tls in flags) and
  1897. (tlsoffset<>NR_NO) then
  1898. cg.a_reg_sync(aktproccode,tlsoffset);
  1899. gen_free_symtable(aktproccode,procdef.localst);
  1900. gen_free_symtable(aktproccode,procdef.parast);
  1901. { add code that will load the return value, this is not done
  1902. for assembler routines when they didn't reference the result
  1903. variable }
  1904. hlcg.gen_load_return_value(templist);
  1905. aktproccode.concatlist(templist);
  1906. { Already reserve all registers for stack checking code and
  1907. generate the call to the helper function }
  1908. if not(tf_no_generic_stackcheck in target_info.flags) and
  1909. (cs_check_stack in entryswitches) and
  1910. not(po_assembler in procdef.procoptions) and
  1911. (procdef.proctypeoption<>potype_proginit) then
  1912. begin
  1913. current_filepos:=entrypos;
  1914. hlcg.gen_stack_check_call(templist);
  1915. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1916. end;
  1917. { this code (got loading) comes before everything which has }
  1918. { already been generated, so reset the info about already }
  1919. { backwards extended registers (so their live range can be }
  1920. { extended backwards even further if needed) }
  1921. { This code must be }
  1922. { a) generated after do_secondpass has been called }
  1923. { (because pi_needs_got may be set there) }
  1924. { b) generated before register allocation, because the }
  1925. { got/pic register can be a virtual one }
  1926. { c) inserted before the entry code, because the entry }
  1927. { code may need global symbols such as init rtti }
  1928. { d) inserted after the stackframe allocation, because }
  1929. { this register may have to be spilled }
  1930. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1931. current_filepos:=entrypos;
  1932. { load got if necessary }
  1933. cg.g_maybe_got_init(templist);
  1934. aktproccode.insertlistafter(headertai,templist);
  1935. { init tls if needed }
  1936. cg.g_maybe_tls_init(templist);
  1937. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1938. { re-enable if more code at the end is ever generated here
  1939. cg.set_regalloc_live_range_direction(rad_forward);
  1940. }
  1941. {$ifndef NoOpt}
  1942. {$ifndef i386}
  1943. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1944. { do not optimize pure assembler procedures }
  1945. not(pi_is_assembler in flags) then
  1946. preregallocschedule(aktproccode);
  1947. {$endif i386}
  1948. {$endif NoOpt}
  1949. { The procedure body is finished, we can now
  1950. allocate the registers }
  1951. cg.do_register_allocation(aktproccode,headertai);
  1952. { translate imag. register to their real counter parts
  1953. this is necessary for debuginfo and verbose assembler output
  1954. when SSA will be implemented, this will be more complicated because we've to
  1955. maintain location lists }
  1956. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1957. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1958. if (tf_pic_uses_got in target_info.flags) and (pi_needs_got in flags) and
  1959. not(cs_no_regalloc in current_settings.globalswitches) and
  1960. (got<>NR_NO) then
  1961. cg.translate_register(got);
  1962. { Add save and restore of used registers }
  1963. current_filepos:=entrypos;
  1964. gen_save_used_regs(templist);
  1965. { Remember the last instruction of register saving block
  1966. (may be =nil for e.g. assembler procedures) }
  1967. endprologue_ai:=templist.last;
  1968. aktproccode.insertlistafter(headertai,templist);
  1969. current_filepos:=exitpos;
  1970. gen_restore_used_regs(aktproccode);
  1971. { We know the size of the stack, now we can generate the
  1972. parameter that is passed to the stack checking code }
  1973. if not(tf_no_generic_stackcheck in target_info.flags) and
  1974. (cs_check_stack in entryswitches) and
  1975. not(po_assembler in procdef.procoptions) and
  1976. (procdef.proctypeoption<>potype_proginit) then
  1977. begin
  1978. current_filepos:=entrypos;
  1979. hlcg.gen_stack_check_size_para(templist);
  1980. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1981. end;
  1982. current_procinfo.set_eh_info;
  1983. { Add entry code (stack allocation) after header }
  1984. current_filepos:=entrypos;
  1985. gen_proc_entry_code(templist);
  1986. aktproccode.insertlistafter(headertai,templist);
  1987. {$ifdef SUPPORT_SAFECALL}
  1988. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1989. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1990. (tf_safecall_exceptions in target_info.flags) and
  1991. (procdef.proccalloption=pocall_safecall) then
  1992. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1993. {$endif}
  1994. { Add exit code at the end }
  1995. current_filepos:=exitpos;
  1996. gen_proc_exit_code(templist);
  1997. aktproccode.concatlist(templist);
  1998. { check if the implicit finally has been generated. The flag
  1999. should already be set in pass1 }
  2000. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  2001. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  2002. (pi_needs_implicit_finally in flags) and
  2003. not(pi_has_implicit_finally in flags) and
  2004. not(target_info.system in systems_garbage_collected_managed_types) then
  2005. internalerror(200405231);
  2006. { sanity check }
  2007. if not(assigned(current_procinfo.procdef.personality)) and
  2008. (tf_use_psabieh in target_info.flags) and
  2009. ((pi_uses_exceptions in flags) or
  2010. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  2011. (pi_needs_implicit_finally in flags))) then
  2012. Internalerror(2019021005);
  2013. { Position markers are only used to insert additional code after the secondpass
  2014. and before this point. They are of no use in optimizer. Instead of checking and
  2015. ignoring all over the optimizer, just remove them here. }
  2016. delete_marker(entry_asmnode);
  2017. delete_marker(loadpara_asmnode);
  2018. delete_marker(exitlabel_asmnode);
  2019. delete_marker(stackcheck_asmnode);
  2020. delete_marker(init_asmnode);
  2021. {$ifndef NoOpt}
  2022. if not(cs_no_regalloc in current_settings.globalswitches) then
  2023. begin
  2024. if (cs_opt_level1 in current_settings.optimizerswitches) and
  2025. { do not optimize pure assembler procedures }
  2026. not(pi_is_assembler in flags) then
  2027. optimize(aktproccode);
  2028. {$ifndef i386}
  2029. { schedule after assembler optimization, it could have brought up
  2030. new schedule possibilities }
  2031. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  2032. { do not optimize pure assembler procedures }
  2033. not(pi_is_assembler in flags) then
  2034. preregallocschedule(aktproccode);
  2035. {$endif i386}
  2036. end;
  2037. {$endif NoOpt}
  2038. { Perform target-specific processing if necessary }
  2039. postprocess_code;
  2040. { Add end symbol and debug info }
  2041. { this must be done after the pcrelativedata is appended else the distance calculation of
  2042. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  2043. so it should be inserted before the end symbol (FK)
  2044. }
  2045. current_filepos:=exitpos;
  2046. hlcg.gen_proc_symbol_end(templist);
  2047. aktproccode.concatlist(templist);
  2048. { insert line debuginfo }
  2049. if (cs_debuginfo in current_settings.moduleswitches) or
  2050. (cs_use_lineinfo in current_settings.globalswitches) then
  2051. begin
  2052. { We only do this after the code generated because
  2053. otherwise for-loop counters moved to the struct cause
  2054. errors. And doing it before optimisation passes have run
  2055. causes problems when they manually look up symbols
  2056. like result and self (nutils.load_self_node etc). Still
  2057. do it nevertheless to to assist debug info generation
  2058. (hide original symbols, add absolutevarsyms that redirect
  2059. to their new locations in the parentfpstruct) }
  2060. if assigned(current_procinfo.procdef.parentfpstruct) then
  2061. redirect_parentfpstruct_local_syms(current_procinfo.procdef);
  2062. current_debuginfo.insertlineinfo(aktproccode);
  2063. end;
  2064. finish_eh;
  2065. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  2066. { now generate code for any exception filters (they need the tempgen) }
  2067. generate_code_exceptfilters;
  2068. { only now we can remove the temps }
  2069. if (procdef.proctypeoption<>potype_exceptfilter) then
  2070. begin
  2071. tg.resettempgen;
  2072. tg.free;
  2073. tg:=nil;
  2074. end;
  2075. { stop tempgen and ra }
  2076. hlcg.done_register_allocators;
  2077. destroy_hlcodegen;
  2078. end;
  2079. dfabuilder.free;
  2080. { restore symtablestack }
  2081. remove_from_symtablestack;
  2082. { restore }
  2083. templist.free;
  2084. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  2085. current_filepos:=oldfilepos;
  2086. current_structdef:=old_current_structdef;
  2087. current_procinfo:=old_current_procinfo;
  2088. end;
  2089. procedure tcgprocinfo.add_to_symtablestack;
  2090. begin
  2091. { insert symtables for the class, but only if it is no nested function }
  2092. if assigned(procdef.struct) and
  2093. not(assigned(parent) and
  2094. assigned(parent.procdef) and
  2095. assigned(parent.procdef.struct)) then
  2096. push_nested_hierarchy(procdef.struct);
  2097. { insert parasymtable in symtablestack when parsing
  2098. a function }
  2099. if procdef.parast.symtablelevel>=normal_function_level then
  2100. symtablestack.push(procdef.parast);
  2101. { insert localsymtable, except for the main procedure
  2102. (in that case the localst is the unit's static symtable,
  2103. which is already on the stack) }
  2104. if procdef.localst.symtablelevel>=normal_function_level then
  2105. symtablestack.push(procdef.localst);
  2106. end;
  2107. procedure tcgprocinfo.remove_from_symtablestack;
  2108. begin
  2109. { remove localsymtable }
  2110. if procdef.localst.symtablelevel>=normal_function_level then
  2111. symtablestack.pop(procdef.localst);
  2112. { remove parasymtable }
  2113. if procdef.parast.symtablelevel>=normal_function_level then
  2114. symtablestack.pop(procdef.parast);
  2115. { remove symtables for the class, but only if it is no nested function }
  2116. if assigned(procdef.struct) and
  2117. not(assigned(parent) and
  2118. assigned(parent.procdef) and
  2119. assigned(parent.procdef.struct)) then
  2120. pop_nested_hierarchy(procdef.struct);
  2121. end;
  2122. procedure tcgprocinfo.resetprocdef;
  2123. begin
  2124. { remove code tree, if not inline procedure }
  2125. if assigned(code) then
  2126. begin
  2127. { the inline procedure has already got a copy of the tree
  2128. stored in procdef.inlininginfo }
  2129. code.free;
  2130. code:=nil;
  2131. end;
  2132. end;
  2133. procedure tcgprocinfo.parse_body;
  2134. var
  2135. old_current_procinfo : tprocinfo;
  2136. old_block_type : tblock_type;
  2137. st : TSymtable;
  2138. old_current_structdef: tabstractrecorddef;
  2139. old_current_genericdef,
  2140. old_current_specializedef: tstoreddef;
  2141. parentfpinitblock: tnode;
  2142. old_parse_generic: boolean;
  2143. recordtokens : boolean;
  2144. begin
  2145. old_current_procinfo:=current_procinfo;
  2146. old_block_type:=block_type;
  2147. old_current_structdef:=current_structdef;
  2148. old_current_genericdef:=current_genericdef;
  2149. old_current_specializedef:=current_specializedef;
  2150. old_parse_generic:=parse_generic;
  2151. current_procinfo:=self;
  2152. current_structdef:=procdef.struct;
  2153. { check if the definitions of certain types are available which might not be available in older rtls and
  2154. which are assigned "on the fly" in types_dec }
  2155. {$ifndef jvm}
  2156. if not assigned(rec_exceptaddr) then
  2157. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  2158. if not assigned(rec_tguid) then
  2159. Message1(cg_f_internal_type_not_found,'TGUID');
  2160. if not assigned(rec_jmp_buf) then
  2161. Message1(cg_f_internal_type_not_found,'JMP_BUF');
  2162. {$endif}
  2163. { if the procdef is truly a generic (thus takes parameters itself) then
  2164. /that/ is our genericdef, not the - potentially - generic struct }
  2165. if procdef.is_generic then
  2166. begin
  2167. current_genericdef:=procdef;
  2168. parse_generic:=true;
  2169. end
  2170. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  2171. begin
  2172. current_genericdef:=current_structdef;
  2173. parse_generic:=true;
  2174. end;
  2175. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  2176. current_specializedef:=current_structdef;
  2177. { calculate the lexical level }
  2178. if procdef.parast.symtablelevel>maxnesting then
  2179. Message(parser_e_too_much_lexlevel);
  2180. block_type:=bt_body;
  2181. {$ifdef state_tracking}
  2182. { aktstate:=Tstate_storage.create;}
  2183. {$endif state_tracking}
  2184. { allocate the symbol for this procedure }
  2185. alloc_proc_symbol(procdef);
  2186. { add parast/localst to symtablestack }
  2187. add_to_symtablestack;
  2188. { save entry info }
  2189. entrypos:=current_filepos;
  2190. entryswitches:=current_settings.localswitches;
  2191. recordtokens:=procdef.is_generic or
  2192. (
  2193. assigned(procdef.struct) and
  2194. (df_generic in procdef.struct.defoptions) and
  2195. assigned(procdef.owner) and
  2196. (procdef.owner.defowner=procdef.struct)
  2197. );
  2198. if recordtokens then
  2199. begin
  2200. { start token recorder for generic template }
  2201. procdef.initgeneric;
  2202. current_scanner.startrecordtokens(procdef.generictokenbuf);
  2203. end;
  2204. { parse the code ... }
  2205. code:=block(current_module.islibrary);
  2206. if recordtokens then
  2207. begin
  2208. { stop token recorder for generic template }
  2209. current_scanner.stoprecordtokens;
  2210. { Give an error for accesses in the static symtable that aren't visible
  2211. outside the current unit }
  2212. st:=procdef.owner;
  2213. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  2214. st:=st.defowner.owner;
  2215. if (pi_uses_static_symtable in flags) and
  2216. (st.symtabletype<>staticsymtable) then
  2217. Message(parser_e_global_generic_references_static);
  2218. end;
  2219. { save exit info }
  2220. exitswitches:=current_settings.localswitches;
  2221. exitpos:=last_endtoken_filepos;
  2222. { the procedure is now defined }
  2223. procdef.forwarddef:=false;
  2224. procdef.is_implemented:=true;
  2225. if assigned(code) then
  2226. begin
  2227. { get a better entry point }
  2228. entrypos:=code.fileinfo;
  2229. { Finish type checking pass }
  2230. do_typecheckpass(code);
  2231. if assigned(procdef.parentfpinitblock) then
  2232. begin
  2233. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  2234. begin
  2235. parentfpinitblock:=procdef.parentfpinitblock;
  2236. do_typecheckpass(parentfpinitblock);
  2237. procdef.parentfpinitblock:=parentfpinitblock;
  2238. end
  2239. end;
  2240. end;
  2241. { Check for unused labels, forwards, symbols for procedures. Static
  2242. symtable is checked in pmodules.
  2243. The check must be done after the typecheckpass }
  2244. if (Errorcount=0) and
  2245. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  2246. begin
  2247. { check if forwards are resolved }
  2248. tstoredsymtable(procdef.localst).check_forwards;
  2249. { check if all labels are used }
  2250. tstoredsymtable(procdef.localst).checklabels;
  2251. { check for unused symbols, but only if there is no asm block }
  2252. if not(pi_has_assembler_block in flags) then
  2253. begin
  2254. tstoredsymtable(procdef.localst).allsymbolsused;
  2255. tstoredsymtable(procdef.parast).allsymbolsused;
  2256. end;
  2257. end;
  2258. if (po_inline in procdef.procoptions) and
  2259. { Can we inline this procedure? }
  2260. checknodeinlining(procdef) then
  2261. CreateInlineInfo;
  2262. { Print the node to tree.log }
  2263. if paraprintnodetree <> 0 then
  2264. printproc( 'after parsing');
  2265. {$ifdef DEBUG_NODE_XML}
  2266. { Methods of generic classes don't get any code generated, so output
  2267. the node tree here }
  2268. if (df_generic in procdef.defoptions) then
  2269. XMLPrintProc(True);
  2270. {$endif DEBUG_NODE_XML}
  2271. { ... remove symbol tables }
  2272. remove_from_symtablestack;
  2273. {$ifdef state_tracking}
  2274. { aktstate.destroy;}
  2275. {$endif state_tracking}
  2276. current_structdef:=old_current_structdef;
  2277. current_genericdef:=old_current_genericdef;
  2278. current_specializedef:=old_current_specializedef;
  2279. current_procinfo:=old_current_procinfo;
  2280. parse_generic:=old_parse_generic;
  2281. { Restore old state }
  2282. block_type:=old_block_type;
  2283. end;
  2284. {****************************************************************************
  2285. PROCEDURE/FUNCTION PARSING
  2286. ****************************************************************************}
  2287. procedure check_init_paras(p:TObject;arg:pointer);
  2288. begin
  2289. if tsym(p).typ<>paravarsym then
  2290. exit;
  2291. with tparavarsym(p) do
  2292. if (is_managed_type(vardef) and
  2293. (varspez in [vs_value,vs_out])) or
  2294. (is_shortstring(vardef) and
  2295. (varspez=vs_value)) then
  2296. include(current_procinfo.flags,pi_do_call);
  2297. end;
  2298. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  2299. {
  2300. Parses the procedure directives, then parses the procedure body, then
  2301. generates the code for it
  2302. }
  2303. var
  2304. oldfailtokenmode : tmodeswitches;
  2305. isnestedproc : boolean;
  2306. begin
  2307. Message1(parser_d_procedure_start,pd.fullprocname(false));
  2308. oldfailtokenmode:=[];
  2309. { create a new procedure }
  2310. current_procinfo:=cprocinfo.create(old_current_procinfo);
  2311. current_module.procinfo:=current_procinfo;
  2312. current_procinfo.procdef:=pd;
  2313. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  2314. { Insert mangledname }
  2315. pd.aliasnames.insert(pd.mangledname);
  2316. { Handle Export of this procedure }
  2317. if (po_exports in pd.procoptions) and
  2318. (target_info.system in [system_i386_os2,system_i386_emx]) then
  2319. begin
  2320. pd.aliasnames.insert(pd.procsym.realname);
  2321. if cs_link_deffile in current_settings.globalswitches then
  2322. deffile.AddExport(pd.mangledname);
  2323. end;
  2324. { Insert result variables in the localst }
  2325. insert_funcret_local(pd);
  2326. { check if there are para's which require initing -> set }
  2327. { pi_do_call (if not yet set) }
  2328. if not(pi_do_call in current_procinfo.flags) then
  2329. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  2330. { set _FAIL as keyword if constructor }
  2331. if (pd.proctypeoption=potype_constructor) then
  2332. begin
  2333. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  2334. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  2335. end;
  2336. tcgprocinfo(current_procinfo).parse_body;
  2337. { reset _FAIL as _SELF normal }
  2338. if (pd.proctypeoption=potype_constructor) then
  2339. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  2340. { When it's a nested procedure then defer the code generation,
  2341. when back at normal function level then generate the code
  2342. for all defered nested procedures and the current procedure }
  2343. if not isnestedproc then
  2344. begin
  2345. if not(df_generic in current_procinfo.procdef.defoptions) then
  2346. begin
  2347. { also generate the bodies for all previously done
  2348. specializations so that we might inline them }
  2349. generate_specialization_procs;
  2350. tcgprocinfo(current_procinfo).generate_code_tree;
  2351. end;
  2352. end;
  2353. { release procinfo }
  2354. if tprocinfo(current_module.procinfo)<>current_procinfo then
  2355. internalerror(200304274);
  2356. current_module.procinfo:=current_procinfo.parent;
  2357. { For specialization we didn't record the last semicolon. Moving this parsing
  2358. into the parse_body routine is not done because of having better file position
  2359. information available }
  2360. if not current_procinfo.procdef.is_specialization and
  2361. (
  2362. not assigned(current_procinfo.procdef.struct) or
  2363. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  2364. or not (
  2365. assigned(current_procinfo.procdef.owner) and
  2366. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  2367. )
  2368. ) then
  2369. consume(_SEMICOLON);
  2370. if not isnestedproc then
  2371. { current_procinfo is checked for nil later on }
  2372. freeandnil(current_procinfo);
  2373. end;
  2374. procedure read_proc_body(pd:tprocdef);
  2375. var
  2376. old_module_procinfo : tobject;
  2377. old_current_procinfo : tprocinfo;
  2378. begin
  2379. old_current_procinfo:=current_procinfo;
  2380. old_module_procinfo:=current_module.procinfo;
  2381. current_procinfo:=nil;
  2382. current_module.procinfo:=nil;
  2383. read_proc_body(nil,pd);
  2384. current_procinfo:=old_current_procinfo;
  2385. current_module.procinfo:=old_module_procinfo;
  2386. end;
  2387. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  2388. {
  2389. Parses the procedure directives, then parses the procedure body, then
  2390. generates the code for it
  2391. }
  2392. var
  2393. old_current_procinfo : tprocinfo;
  2394. old_current_structdef: tabstractrecorddef;
  2395. old_current_genericdef,
  2396. old_current_specializedef: tstoreddef;
  2397. pdflags : tpdflags;
  2398. pd,firstpd : tprocdef;
  2399. {$ifdef genericdef_for_nested}
  2400. def : tprocdef;
  2401. srsym : tsym;
  2402. i : longint;
  2403. {$endif genericdef_for_nested}
  2404. begin
  2405. { save old state }
  2406. old_current_procinfo:=current_procinfo;
  2407. old_current_structdef:=current_structdef;
  2408. old_current_genericdef:=current_genericdef;
  2409. old_current_specializedef:=current_specializedef;
  2410. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  2411. to another procdef }
  2412. current_procinfo:=nil;
  2413. current_structdef:=nil;
  2414. current_genericdef:=nil;
  2415. current_specializedef:=nil;
  2416. if not assigned(usefwpd) then
  2417. { parse procedure declaration }
  2418. pd:=parse_proc_dec(isclassmethod,old_current_structdef,isgeneric)
  2419. else
  2420. pd:=usefwpd;
  2421. { set the default function options }
  2422. if parse_only then
  2423. begin
  2424. pd.forwarddef:=true;
  2425. { set also the interface flag, for better error message when the
  2426. implementation doesn't match this header }
  2427. pd.interfacedef:=true;
  2428. include(pd.procoptions,po_global);
  2429. pdflags:=[pd_interface];
  2430. end
  2431. else
  2432. begin
  2433. pdflags:=[pd_body];
  2434. if (not current_module.in_interface) then
  2435. include(pdflags,pd_implemen);
  2436. if (not current_module.is_unit) or
  2437. create_smartlink_library then
  2438. include(pd.procoptions,po_global);
  2439. pd.forwarddef:=false;
  2440. end;
  2441. if not assigned(usefwpd) then
  2442. begin
  2443. { parse the directives that may follow }
  2444. parse_proc_directives(pd,pdflags);
  2445. { hint directives, these can be separated by semicolons here,
  2446. that needs to be handled here with a loop (PFV) }
  2447. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  2448. Consume(_SEMICOLON);
  2449. { Set calling convention }
  2450. if parse_only then
  2451. handle_calling_convention(pd,hcc_default_actions_intf)
  2452. else
  2453. handle_calling_convention(pd,hcc_default_actions_impl)
  2454. end;
  2455. { search for forward declarations }
  2456. if not proc_add_definition(pd) then
  2457. begin
  2458. { One may not implement a method of a type declared in a different unit }
  2459. if assigned(pd.struct) and
  2460. (pd.struct.symtable.moduleid<>current_module.moduleid) and
  2461. not pd.is_specialization then
  2462. begin
  2463. MessagePos1(pd.fileinfo,parser_e_method_for_type_in_other_unit,pd.struct.typesymbolprettyname);
  2464. end
  2465. { A method must be forward defined (in the object declaration) }
  2466. else if assigned(pd.struct) and
  2467. (not assigned(old_current_structdef)) then
  2468. begin
  2469. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  2470. tprocsym(pd.procsym).write_parameter_lists(pd);
  2471. end
  2472. else
  2473. begin
  2474. { Give a better error if there is a forward def in the interface and only
  2475. a single implementation }
  2476. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  2477. if (not pd.forwarddef) and
  2478. (not pd.interfacedef) and
  2479. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  2480. firstpd.forwarddef and
  2481. firstpd.interfacedef and
  2482. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  2483. { don't give an error if it may be an overload }
  2484. not(m_fpc in current_settings.modeswitches) and
  2485. (not(po_overload in pd.procoptions) or
  2486. not(po_overload in firstpd.procoptions)) then
  2487. begin
  2488. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  2489. tprocsym(pd.procsym).write_parameter_lists(pd);
  2490. end
  2491. else
  2492. begin
  2493. if pd.is_generic and not assigned(pd.struct) then
  2494. tprocsym(pd.procsym).owner.includeoption(sto_has_generic);
  2495. end;
  2496. end;
  2497. end;
  2498. { Set mangled name }
  2499. proc_set_mangledname(pd);
  2500. { inherit generic flags from parent routine }
  2501. if assigned(old_current_procinfo) and
  2502. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2503. begin
  2504. if df_generic in old_current_procinfo.procdef.defoptions then
  2505. include(pd.defoptions,df_generic);
  2506. if df_specialization in old_current_procinfo.procdef.defoptions then
  2507. begin
  2508. include(pd.defoptions,df_specialization);
  2509. { the procdefs encountered here are nested procdefs of which
  2510. their complete definition also resides inside the current token
  2511. stream, thus access to their genericdef is not required }
  2512. {$ifdef genericdef_for_nested}
  2513. { find the corresponding routine in the generic routine }
  2514. if not assigned(old_current_procinfo.procdef.genericdef) then
  2515. internalerror(2016121701);
  2516. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(pd.procsym.name));
  2517. if not assigned(srsym) or (srsym.typ<>procsym) then
  2518. internalerror(2016121702);
  2519. { in practice the generic procdef should be at the same index
  2520. as the index of the current procdef, but as there *might* be
  2521. differences between the amount of defs generated for the
  2522. specialization and the generic search for the def using
  2523. parameter comparison }
  2524. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2525. begin
  2526. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2527. if (compare_paras(def.paras,pd.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2528. (compare_defs(def.returndef,pd.returndef,nothingn)=te_exact) then
  2529. begin
  2530. pd.genericdef:=def;
  2531. break;
  2532. end;
  2533. end;
  2534. if not assigned(pd.genericdef) then
  2535. internalerror(2016121703);
  2536. {$endif}
  2537. end;
  2538. end;
  2539. { compile procedure when a body is needed }
  2540. if (pd_body in pdflags) then
  2541. begin
  2542. read_proc_body(old_current_procinfo,pd);
  2543. end
  2544. else
  2545. begin
  2546. { Handle imports }
  2547. if (po_external in pd.procoptions) then
  2548. begin
  2549. import_external_proc(pd);
  2550. {$ifdef cpuhighleveltarget}
  2551. { it's hard to factor this out in a virtual method, because the
  2552. generic version (the one inside this ifdef) doesn't fit in
  2553. hlcgobj but in symcreat or here, while the other version
  2554. doesn't fit in symcreat (since it uses the code generator).
  2555. Maybe we need another class for this kind of code that could
  2556. either be symcreat- or hlcgobj-based
  2557. }
  2558. if (not pd.forwarddef) and
  2559. (pd.hasforward) and
  2560. (proc_get_importname(pd)<>'') then
  2561. begin
  2562. { we cannot handle the callee-side of variadic functions (and
  2563. even if we could, e.g. LLVM cannot call through to something
  2564. else in that case) }
  2565. if is_c_variadic(pd) then
  2566. Message1(parser_e_callthrough_varargs,pd.fullprocname(false));
  2567. call_through_new_name(pd,proc_get_importname(pd));
  2568. include(pd.implprocoptions,pio_thunk);
  2569. end
  2570. else
  2571. {$endif cpuhighleveltarget}
  2572. begin
  2573. create_hlcodegen;
  2574. hlcg.handle_external_proc(
  2575. current_asmdata.asmlists[al_procedures],
  2576. pd,
  2577. proc_get_importname(pd));
  2578. destroy_hlcodegen;
  2579. end
  2580. end;
  2581. end;
  2582. { always register public functions that are only declared in the
  2583. implementation section as they might be called using an external
  2584. declaration from another unit }
  2585. if (po_global in pd.procoptions) and
  2586. not pd.interfacedef and
  2587. ([df_generic,df_specialization]*pd.defoptions=[]) then
  2588. begin
  2589. pd.register_def;
  2590. pd.procsym.register_sym;
  2591. end;
  2592. { make sure that references to forward-declared functions are not }
  2593. { treated as references to external symbols, needed for darwin. }
  2594. { make sure we don't change the binding of real external symbols }
  2595. if (([po_external,po_weakexternal]*pd.procoptions)=[]) and (pocall_internproc<>pd.proccalloption) then
  2596. current_asmdata.DefineProcAsmSymbol(pd,pd.mangledname,pd.needsglobalasmsym);
  2597. current_structdef:=old_current_structdef;
  2598. current_genericdef:=old_current_genericdef;
  2599. current_specializedef:=old_current_specializedef;
  2600. current_procinfo:=old_current_procinfo;
  2601. end;
  2602. procedure import_external_proc(pd:tprocdef);
  2603. var
  2604. name : string;
  2605. begin
  2606. if not (po_external in pd.procoptions) then
  2607. internalerror(2015121101);
  2608. { Import DLL specified? }
  2609. if assigned(pd.import_dll) then
  2610. begin
  2611. if assigned (pd.import_name) then
  2612. current_module.AddExternalImport(pd.import_dll^,
  2613. pd.import_name^,proc_get_importname(pd),
  2614. pd.import_nr,false,false)
  2615. else
  2616. current_module.AddExternalImport(pd.import_dll^,
  2617. proc_get_importname(pd),proc_get_importname(pd),
  2618. pd.import_nr,false,true);
  2619. end
  2620. else
  2621. begin
  2622. name:=proc_get_importname(pd);
  2623. { add import name to external list for DLL scanning }
  2624. if tf_has_dllscanner in target_info.flags then
  2625. current_module.dllscannerinputlist.Add(name,pd);
  2626. { needed for units that use functions in packages this way }
  2627. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2628. end;
  2629. end;
  2630. {****************************************************************************
  2631. DECLARATION PARSING
  2632. ****************************************************************************}
  2633. { search in symtablestack for not complete classes }
  2634. procedure check_forward_class(p:TObject;arg:pointer);
  2635. begin
  2636. if (tsym(p).typ=typesym) and
  2637. (ttypesym(p).typedef.typ=objectdef) and
  2638. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2639. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2640. end;
  2641. {$ifdef DEBUG_NODE_XML}
  2642. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  2643. var
  2644. T: Text;
  2645. begin
  2646. Assign(T, current_module.ppxfilename);
  2647. {$push} {$I-}
  2648. Rewrite(T);
  2649. if IOResult<>0 then
  2650. begin
  2651. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2652. current_module.ppxfilefail := True;
  2653. Exit;
  2654. end;
  2655. {$pop}
  2656. { Mark the node dump file as available for writing }
  2657. current_module.ppxfilefail := False;
  2658. WriteLn(T, '<?xml version="1.0" encoding="utf-8"?>');
  2659. WriteLn(T, '<', RootName, ' name="', ModuleName, '">');
  2660. Close(T);
  2661. printnodeindention := printnodespacing;
  2662. end;
  2663. procedure XMLFinalizeNodeFile(RootName: shortstring);
  2664. var
  2665. T: Text;
  2666. begin
  2667. if current_module.ppxfilefail then
  2668. Exit;
  2669. current_module.ppxfilefail := True; { File is now considered closed no matter what happens }
  2670. Assign(T, current_module.ppxfilename);
  2671. {$push} {$I-}
  2672. Append(T);
  2673. if IOResult<>0 then
  2674. begin
  2675. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2676. Exit;
  2677. end;
  2678. {$pop}
  2679. WriteLn(T, '</', RootName, '>');
  2680. Close(T);
  2681. end;
  2682. {$endif DEBUG_NODE_XML}
  2683. procedure read_declarations(islibrary : boolean);
  2684. var
  2685. hadgeneric : boolean;
  2686. procedure handle_unexpected_had_generic;
  2687. begin
  2688. if hadgeneric then
  2689. begin
  2690. Message(parser_e_procedure_or_function_expected);
  2691. hadgeneric:=false;
  2692. end;
  2693. end;
  2694. var
  2695. is_classdef:boolean;
  2696. begin
  2697. is_classdef:=false;
  2698. hadgeneric:=false;
  2699. repeat
  2700. if not assigned(current_procinfo) then
  2701. internalerror(200304251);
  2702. case token of
  2703. _LABEL:
  2704. begin
  2705. handle_unexpected_had_generic;
  2706. label_dec;
  2707. end;
  2708. _CONST:
  2709. begin
  2710. handle_unexpected_had_generic;
  2711. const_dec(hadgeneric);
  2712. end;
  2713. _TYPE:
  2714. begin
  2715. handle_unexpected_had_generic;
  2716. type_dec(hadgeneric);
  2717. end;
  2718. _VAR:
  2719. begin
  2720. handle_unexpected_had_generic;
  2721. var_dec(hadgeneric);
  2722. end;
  2723. _THREADVAR:
  2724. begin
  2725. handle_unexpected_had_generic;
  2726. threadvar_dec(hadgeneric);
  2727. end;
  2728. _CLASS:
  2729. begin
  2730. is_classdef:=false;
  2731. if try_to_consume(_CLASS) then
  2732. begin
  2733. { class modifier is only allowed for procedures, functions, }
  2734. { constructors, destructors }
  2735. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2736. not((token=_ID) and (idtoken=_OPERATOR)) then
  2737. Message(parser_e_procedure_or_function_expected);
  2738. if is_interface(current_structdef) then
  2739. Message(parser_e_no_static_method_in_interfaces)
  2740. else
  2741. { class methods are also allowed for Objective-C protocols }
  2742. is_classdef:=true;
  2743. end;
  2744. end;
  2745. _CONSTRUCTOR,
  2746. _DESTRUCTOR,
  2747. _FUNCTION,
  2748. _PROCEDURE,
  2749. _OPERATOR:
  2750. begin
  2751. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2752. begin
  2753. Message(parser_e_procedure_or_function_expected);
  2754. hadgeneric:=false;
  2755. end;
  2756. read_proc(is_classdef,nil,hadgeneric);
  2757. is_classdef:=false;
  2758. hadgeneric:=false;
  2759. end;
  2760. _EXPORTS:
  2761. begin
  2762. handle_unexpected_had_generic;
  2763. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2764. begin
  2765. Message(parser_e_syntax_error);
  2766. consume_all_until(_SEMICOLON);
  2767. end
  2768. else if islibrary or
  2769. (target_info.system in systems_unit_program_exports) then
  2770. read_exports
  2771. else
  2772. begin
  2773. Message(parser_w_unsupported_feature);
  2774. consume(_BEGIN);
  2775. end;
  2776. end;
  2777. _PROPERTY:
  2778. begin
  2779. handle_unexpected_had_generic;
  2780. if (m_fpc in current_settings.modeswitches) then
  2781. property_dec
  2782. else
  2783. break;
  2784. end;
  2785. else
  2786. begin
  2787. case idtoken of
  2788. _RESOURCESTRING:
  2789. begin
  2790. handle_unexpected_had_generic;
  2791. { m_class is needed, because the resourcestring
  2792. loading is in the ObjPas unit }
  2793. { if (m_class in current_settings.modeswitches) then}
  2794. resourcestring_dec(hadgeneric)
  2795. { else
  2796. break;}
  2797. end;
  2798. _OPERATOR:
  2799. begin
  2800. handle_unexpected_had_generic;
  2801. if is_classdef then
  2802. begin
  2803. read_proc(is_classdef,nil,false);
  2804. is_classdef:=false;
  2805. end
  2806. else
  2807. break;
  2808. end;
  2809. _GENERIC:
  2810. begin
  2811. handle_unexpected_had_generic;
  2812. if not (m_delphi in current_settings.modeswitches) then
  2813. begin
  2814. consume(_ID);
  2815. hadgeneric:=true;
  2816. end
  2817. else
  2818. break;
  2819. end
  2820. else
  2821. break;
  2822. end;
  2823. end;
  2824. end;
  2825. until false;
  2826. { add implementations for synthetic method declarations added by
  2827. the compiler (not for unit/program init functions, their localst
  2828. is the staticst -> would duplicate the work done in pmodules) }
  2829. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  2830. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2831. { check for incomplete class definitions, this is only required
  2832. for fpc modes }
  2833. if (m_fpc in current_settings.modeswitches) then
  2834. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2835. end;
  2836. procedure read_interface_declarations;
  2837. var
  2838. hadgeneric : boolean;
  2839. procedure handle_unexpected_had_generic;
  2840. begin
  2841. if hadgeneric then
  2842. begin
  2843. Message(parser_e_procedure_or_function_expected);
  2844. hadgeneric:=false;
  2845. end;
  2846. end;
  2847. begin
  2848. hadgeneric:=false;
  2849. repeat
  2850. case token of
  2851. _CONST :
  2852. begin
  2853. handle_unexpected_had_generic;
  2854. const_dec(hadgeneric);
  2855. end;
  2856. _TYPE :
  2857. begin
  2858. handle_unexpected_had_generic;
  2859. type_dec(hadgeneric);
  2860. end;
  2861. _VAR :
  2862. begin
  2863. handle_unexpected_had_generic;
  2864. var_dec(hadgeneric);
  2865. end;
  2866. _THREADVAR :
  2867. begin
  2868. handle_unexpected_had_generic;
  2869. threadvar_dec(hadgeneric);
  2870. end;
  2871. _FUNCTION,
  2872. _PROCEDURE,
  2873. _OPERATOR :
  2874. begin
  2875. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2876. begin
  2877. message(parser_e_procedure_or_function_expected);
  2878. hadgeneric:=false;
  2879. end;
  2880. read_proc(false,nil,hadgeneric);
  2881. hadgeneric:=false;
  2882. end;
  2883. else
  2884. begin
  2885. case idtoken of
  2886. _RESOURCESTRING :
  2887. begin
  2888. handle_unexpected_had_generic;
  2889. resourcestring_dec(hadgeneric);
  2890. end;
  2891. _PROPERTY:
  2892. begin
  2893. handle_unexpected_had_generic;
  2894. if (m_fpc in current_settings.modeswitches) then
  2895. property_dec
  2896. else
  2897. break;
  2898. end;
  2899. _GENERIC:
  2900. begin
  2901. handle_unexpected_had_generic;
  2902. if not (m_delphi in current_settings.modeswitches) then
  2903. begin
  2904. hadgeneric:=true;
  2905. consume(_ID);
  2906. end
  2907. else
  2908. break;
  2909. end
  2910. else
  2911. break;
  2912. end;
  2913. end;
  2914. end;
  2915. until false;
  2916. { check for incomplete class definitions, this is only required
  2917. for fpc modes }
  2918. if (m_fpc in current_settings.modeswitches) then
  2919. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2920. end;
  2921. end.