psub.pas 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255
  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 tstoredsym(p).typ=labelsym then
  412. begin
  413. addstatement(tstatementnode(arg^),
  414. cifnode.create(caddnode.create(equaln,
  415. ccallnode.createintern('fpc_setjmp',
  416. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  417. cordconstnode.create(1,search_system_proc('fpc_setjmp').returndef,true))
  418. ,cgotonode.create(tlabelsym(p)),nil)
  419. );
  420. end;
  421. end;
  422. function generate_bodyentry_block:tnode;
  423. var
  424. srsym : tsym;
  425. para : tcallparanode;
  426. call : tcallnode;
  427. newstatement : tstatementnode;
  428. def : tabstractrecorddef;
  429. begin
  430. result:=internalstatements(newstatement);
  431. if assigned(current_structdef) then
  432. begin
  433. { a constructor needs a help procedure }
  434. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  435. begin
  436. if is_class(current_structdef) or
  437. (
  438. is_objectpascal_helper(current_structdef) and
  439. is_class(tobjectdef(current_structdef).extendeddef)
  440. ) then
  441. begin
  442. if is_objectpascal_helper(current_structdef) then
  443. def:=tabstractrecorddef(tobjectdef(current_structdef).extendeddef)
  444. else
  445. def:=current_structdef;
  446. srsym:=search_struct_member(def,'NEWINSTANCE');
  447. if assigned(srsym) and
  448. (srsym.typ=procsym) then
  449. begin
  450. { if vmt=1 then newinstance }
  451. addstatement(newstatement,cifnode.create(
  452. caddnode.create_internal(equaln,
  453. ctypeconvnode.create_internal(
  454. load_vmt_pointer_node,
  455. voidpointertype),
  456. cpointerconstnode.create(1,voidpointertype)),
  457. cassignmentnode.create(
  458. ctypeconvnode.create_internal(
  459. load_self_pointer_node,
  460. voidpointertype),
  461. ccallnode.create(nil,tprocsym(srsym),srsym.owner,
  462. ctypeconvnode.create_internal(load_self_pointer_node,cclassrefdef.create(current_structdef)),
  463. [],nil)),
  464. nil));
  465. end
  466. else
  467. internalerror(200305108);
  468. end
  469. else
  470. if is_object(current_structdef) then
  471. begin
  472. { parameter 3 : vmt_offset }
  473. { parameter 2 : address of pointer to vmt,
  474. this is required to allow setting the vmt to -1 to indicate
  475. that memory was allocated }
  476. { parameter 1 : self pointer }
  477. para:=ccallparanode.create(
  478. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  479. ccallparanode.create(
  480. ctypeconvnode.create_internal(
  481. load_vmt_pointer_node,
  482. voidpointertype),
  483. ccallparanode.create(
  484. ctypeconvnode.create_internal(
  485. load_self_pointer_node,
  486. voidpointertype),
  487. nil)));
  488. addstatement(newstatement,cassignmentnode.create(
  489. ctypeconvnode.create_internal(
  490. load_self_pointer_node,
  491. voidpointertype),
  492. ccallnode.createintern('fpc_help_constructor',para)));
  493. end
  494. else
  495. if is_javaclass(current_structdef) or
  496. ((target_info.system in systems_jvm) and
  497. is_record(current_structdef)) then
  498. begin
  499. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  500. not current_procinfo.ConstructorCallingConstructor then
  501. begin
  502. { call inherited constructor }
  503. if is_javaclass(current_structdef) then
  504. srsym:=search_struct_member_no_helper(tobjectdef(current_structdef).childof,'CREATE')
  505. else
  506. srsym:=search_struct_member_no_helper(java_fpcbaserecordtype,'CREATE');
  507. if assigned(srsym) and
  508. (srsym.typ=procsym) then
  509. begin
  510. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited],nil);
  511. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  512. addstatement(newstatement,call);
  513. end
  514. else
  515. internalerror(2011010312);
  516. end;
  517. end
  518. else
  519. if not is_record(current_structdef) and
  520. not (
  521. is_objectpascal_helper(current_structdef) and
  522. (tobjectdef(current_structdef).extendeddef.typ<>objectdef)
  523. ) then
  524. internalerror(200305103);
  525. { if self=nil then exit
  526. calling fail instead of exit is useless because
  527. there is nothing to dispose (PFV) }
  528. if is_class_or_object(current_structdef) then
  529. addstatement(newstatement,cifnode.create(
  530. caddnode.create(equaln,
  531. load_self_pointer_node,
  532. cnilnode.create),
  533. cexitnode.create(nil),
  534. nil));
  535. end;
  536. { maybe call BeforeDestruction for classes }
  537. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  538. is_class(current_structdef) then
  539. begin
  540. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  541. if assigned(srsym) and
  542. (srsym.typ=procsym) then
  543. begin
  544. { if vmt>0 then beforedestruction }
  545. addstatement(newstatement,cifnode.create(
  546. caddnode.create(gtn,
  547. ctypeconvnode.create_internal(
  548. load_vmt_pointer_node,ptrsinttype),
  549. ctypeconvnode.create_internal(
  550. cnilnode.create,ptrsinttype)),
  551. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  552. nil));
  553. end
  554. else
  555. internalerror(200305104);
  556. end;
  557. end;
  558. if m_non_local_goto in current_settings.modeswitches then
  559. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  560. end;
  561. function generate_bodyexit_block:tnode;
  562. var
  563. srsym : tsym;
  564. para : tcallparanode;
  565. newstatement : tstatementnode;
  566. oldlocalswitches: tlocalswitches;
  567. begin
  568. result:=internalstatements(newstatement);
  569. if assigned(current_structdef) then
  570. begin
  571. { Don't test self and the vmt here. The reason is that }
  572. { a constructor already checks whether these are valid }
  573. { before. Further, in case of TThread the thread may }
  574. { free the class instance right after AfterConstruction }
  575. { has been called, so it may no longer be valid (JM) }
  576. oldlocalswitches:=current_settings.localswitches;
  577. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  578. { a destructor needs a help procedure }
  579. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  580. begin
  581. if is_class(current_structdef) then
  582. begin
  583. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  584. if assigned(srsym) and
  585. (srsym.typ=procsym) then
  586. begin
  587. { if self<>0 and vmt<>0 then freeinstance }
  588. addstatement(newstatement,cifnode.create(
  589. caddnode.create(andn,
  590. caddnode.create(unequaln,
  591. load_self_pointer_node,
  592. cnilnode.create),
  593. caddnode.create(unequaln,
  594. ctypeconvnode.create(
  595. load_vmt_pointer_node,
  596. voidpointertype),
  597. cpointerconstnode.create(0,voidpointertype))),
  598. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  599. nil));
  600. end
  601. else
  602. internalerror(2003051001);
  603. end
  604. else
  605. if is_object(current_structdef) then
  606. begin
  607. { finalize object data, but only if not in inherited call }
  608. if is_managed_type(current_structdef) then
  609. begin
  610. addstatement(newstatement,cifnode.create(
  611. caddnode.create(unequaln,
  612. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  613. cnilnode.create),
  614. cnodeutils.finalize_data_node(load_self_node),
  615. nil));
  616. end;
  617. { parameter 3 : vmt_offset }
  618. { parameter 2 : pointer to vmt }
  619. { parameter 1 : self pointer }
  620. para:=ccallparanode.create(
  621. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  622. ccallparanode.create(
  623. ctypeconvnode.create_internal(
  624. load_vmt_pointer_node,
  625. voidpointertype),
  626. ccallparanode.create(
  627. ctypeconvnode.create_internal(
  628. load_self_pointer_node,
  629. voidpointertype),
  630. nil)));
  631. addstatement(newstatement,
  632. ccallnode.createintern('fpc_help_destructor',para));
  633. end
  634. else if is_javaclass(current_structdef) then
  635. begin
  636. { nothing to do }
  637. end
  638. else
  639. internalerror(200305105);
  640. end;
  641. current_settings.localswitches:=oldlocalswitches;
  642. end;
  643. end;
  644. {****************************************************************************
  645. TCGProcInfo
  646. ****************************************************************************}
  647. destructor tcgprocinfo.destroy;
  648. var
  649. i : longint;
  650. begin
  651. if assigned(tempinfo_flags_map) then
  652. begin
  653. for i:=0 to tempinfo_flags_map.count-1 do
  654. dispose(ptempinfo_flags_entry(tempinfo_flags_map[i]));
  655. tempinfo_flags_map.free;
  656. end;
  657. code.free;
  658. inherited destroy;
  659. end;
  660. function tcgprocinfo.calc_stackframe_size:longint;
  661. begin
  662. result:=Align(tg.direction*tg.lasttemp,current_settings.alignment.localalignmin);
  663. end;
  664. procedure tcgprocinfo.printproc(pass:string);
  665. begin
  666. assign(printnodefile,treelogfilename);
  667. {$push}{$I-}
  668. append(printnodefile);
  669. if ioresult<>0 then
  670. rewrite(printnodefile);
  671. {$pop}
  672. if ioresult<>0 then
  673. begin
  674. Comment(V_Error,'Error creating '+treelogfilename);
  675. exit;
  676. end;
  677. writeln(printnodefile);
  678. writeln(printnodefile,'*******************************************************************************');
  679. writeln(printnodefile, pass);
  680. writeln(printnodefile,procdef.fullprocname(false));
  681. writeln(printnodefile,'*******************************************************************************');
  682. printnode(printnodefile,code);
  683. close(printnodefile);
  684. end;
  685. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  686. var
  687. oldlocalswitches: tlocalswitches;
  688. srsym: tsym;
  689. constructionblock,
  690. exceptblock,
  691. newblock: tblocknode;
  692. newstatement: tstatementnode;
  693. pd: tprocdef;
  694. constructionsuccessful: tlocalvarsym;
  695. begin
  696. if assigned(procdef.struct) and
  697. (procdef.proctypeoption=potype_constructor) then
  698. begin
  699. withexceptblock:=
  700. withexceptblock and
  701. not(target_info.system in systems_garbage_collected_managed_types);
  702. { Don't test self and the vmt here. See generate_bodyexit_block }
  703. { why (JM) }
  704. oldlocalswitches:=current_settings.localswitches;
  705. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  706. { call AfterConstruction for classes }
  707. constructionsuccessful:=nil;
  708. if is_class(procdef.struct) then
  709. begin
  710. constructionsuccessful:=clocalvarsym.create(internaltypeprefixName[itp_vmt_afterconstruction_local],vs_value,ptrsinttype,[]);
  711. procdef.localst.insert(constructionsuccessful,false);
  712. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  713. if not assigned(srsym) or
  714. (srsym.typ<>procsym) then
  715. internalerror(200305106);
  716. current_filepos:=entrypos;
  717. constructionblock:=internalstatements(newstatement);
  718. { initialise constructionsuccessful with -1, indicating that
  719. the construction was not successful and hence
  720. beforedestruction should not be called if a destructor is
  721. called from the constructor }
  722. addstatement(newstatement,cassignmentnode.create(
  723. cloadnode.create(constructionsuccessful,procdef.localst),
  724. genintconstnode(-1))
  725. );
  726. { first execute all constructor code. If no exception
  727. occurred then we will execute afterconstruction,
  728. otherwise we won't (the exception will jump over us) }
  729. addstatement(newstatement,tocode);
  730. current_filepos:=exitpos;
  731. { if implicit finally node wasn't created, then exit label and
  732. finalization code must be handled here and placed before
  733. afterconstruction }
  734. if not ((pi_needs_implicit_finally in flags) and
  735. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  736. begin
  737. include(tocode.flags,nf_block_with_exit);
  738. if procdef.proctypeoption<>potype_exceptfilter then
  739. addstatement(newstatement,cfinalizetempsnode.create);
  740. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  741. temps_finalized:=true;
  742. end;
  743. { construction successful -> beforedestruction should be called
  744. if an exception happens now }
  745. addstatement(newstatement,cassignmentnode.create(
  746. cloadnode.create(constructionsuccessful,procdef.localst),
  747. genintconstnode(1))
  748. );
  749. { Self can be nil when fail is called }
  750. { if self<>nil and vmt<>nil then afterconstruction }
  751. addstatement(newstatement,cifnode.create(
  752. caddnode.create(andn,
  753. caddnode.create(unequaln,
  754. load_self_node,
  755. cnilnode.create),
  756. caddnode.create(unequaln,
  757. load_vmt_pointer_node,
  758. cnilnode.create)),
  759. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  760. nil));
  761. tocode:=constructionblock;
  762. end;
  763. if withexceptblock and (procdef.struct.typ=objectdef) then
  764. begin
  765. { Generate the implicit "fail" code for a constructor (destroy
  766. in case an exception happened) }
  767. pd:=tobjectdef(procdef.struct).find_destructor;
  768. { this will always be the case for classes, since tobject has
  769. a destructor }
  770. if assigned(pd) or is_object(procdef.struct) then
  771. begin
  772. current_filepos:=exitpos;
  773. exceptblock:=internalstatements(newstatement);
  774. { first free the instance if non-nil }
  775. if assigned(pd) then
  776. { if vmt<>0 then call destructor }
  777. addstatement(newstatement,
  778. cifnode.create(
  779. caddnode.create(unequaln,
  780. load_vmt_pointer_node,
  781. cnilnode.create),
  782. { cnf_create_failed -> don't call BeforeDestruction }
  783. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed],nil),
  784. nil))
  785. else
  786. { object without destructor, call 'fail' helper }
  787. addstatement(newstatement,
  788. ccallnode.createintern('fpc_help_fail',
  789. ccallparanode.create(
  790. cordconstnode.create(tobjectdef(procdef.struct).vmt_offset,s32inttype,false),
  791. ccallparanode.create(
  792. ctypeconvnode.create_internal(
  793. load_vmt_pointer_node,
  794. voidpointertype),
  795. ccallparanode.create(
  796. ctypeconvnode.create_internal(
  797. load_self_pointer_node,
  798. voidpointertype),
  799. nil))))
  800. );
  801. { then re-raise the exception }
  802. addstatement(newstatement,craisenode.create(nil,nil,nil));
  803. current_filepos:=entrypos;
  804. newblock:=internalstatements(newstatement);
  805. { try
  806. tocode
  807. except
  808. exceptblock
  809. end
  810. }
  811. addstatement(newstatement,ctryexceptnode.create(
  812. tocode,
  813. nil,
  814. exceptblock));
  815. tocode:=newblock;
  816. end;
  817. end;
  818. current_settings.localswitches:=oldlocalswitches;
  819. end;
  820. end;
  821. procedure tcgprocinfo.add_entry_exit_code;
  822. var
  823. finalcode,
  824. bodyentrycode,
  825. bodyexitcode,
  826. wrappedbody,
  827. newblock : tnode;
  828. codestatement,
  829. newstatement : tstatementnode;
  830. oldfilepos : tfileposinfo;
  831. is_constructor: boolean;
  832. begin
  833. is_constructor:=assigned(procdef.struct) and
  834. (procdef.proctypeoption=potype_constructor);
  835. oldfilepos:=current_filepos;
  836. { Generate code/locations used at start of proc }
  837. current_filepos:=entrypos;
  838. entry_asmnode:=casmnode.create_get_position;
  839. loadpara_asmnode:=casmnode.create_get_position;
  840. stackcheck_asmnode:=casmnode.create_get_position;
  841. init_asmnode:=casmnode.create_get_position;
  842. bodyentrycode:=generate_bodyentry_block;
  843. { Generate code/locations used at end of proc }
  844. current_filepos:=exitpos;
  845. exitlabel_asmnode:=casmnode.create_get_position;
  846. temps_finalized:=false;
  847. bodyexitcode:=generate_bodyexit_block;
  848. { Check if bodyexitcode is not empty }
  849. with tstatementnode(tblocknode(bodyexitcode).statements) do
  850. if (statement.nodetype<>nothingn) or assigned(next) then
  851. { Indicate that the extra code is executed after the exit statement }
  852. include(flowcontrol,fc_no_direct_exit);
  853. { Generate procedure by combining init+body+final,
  854. depending on the implicit finally we need to add
  855. an try...finally...end wrapper }
  856. current_filepos:=entrypos;
  857. newblock:=internalstatements(newstatement);
  858. { initialization is common for all cases }
  859. addstatement(newstatement,loadpara_asmnode);
  860. addstatement(newstatement,stackcheck_asmnode);
  861. addstatement(newstatement,entry_asmnode);
  862. cnodeutils.procdef_block_add_implicit_initialize_nodes(procdef,newstatement);
  863. addstatement(newstatement,init_asmnode);
  864. if assigned(procdef.parentfpinitblock) then
  865. begin
  866. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  867. begin
  868. { could be an asmn in case of a pure assembler procedure,
  869. but those shouldn't access nested variables }
  870. addstatement(newstatement,procdef.parentfpinitblock);
  871. end
  872. else
  873. procdef.parentfpinitblock.free;
  874. procdef.parentfpinitblock:=nil;
  875. end;
  876. addstatement(newstatement,bodyentrycode);
  877. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  878. (pi_needs_implicit_finally in flags) and
  879. { but it's useless in init/final code of units }
  880. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  881. not(target_info.system in systems_garbage_collected_managed_types) and
  882. (f_exceptions in features) then
  883. begin
  884. { Any result of managed type must be returned in parameter }
  885. if is_managed_type(procdef.returndef) and
  886. (not paramanager.ret_in_param(procdef.returndef,procdef)) and
  887. (not is_class(procdef.returndef)) then
  888. InternalError(2013121301);
  889. { Generate special exception block only needed when
  890. implicit finally is used }
  891. current_filepos:=exitpos;
  892. { Generate code that will be in the try...finally }
  893. finalcode:=internalstatements(codestatement);
  894. if procdef.proctypeoption<>potype_exceptfilter then
  895. addstatement(codestatement,cfinalizetempsnode.create);
  896. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,codestatement);
  897. temps_finalized:=true;
  898. current_filepos:=entrypos;
  899. wrappedbody:=ctryfinallynode.create_implicit(code,finalcode);
  900. { afterconstruction must be called after finalizetemps, because it
  901. has to execute after the temps have been finalised in case of a
  902. refcounted class (afterconstruction decreases the refcount
  903. without freeing the instance if the count becomes nil, while
  904. the finalising of the temps can free the instance) }
  905. maybe_add_constructor_wrapper(wrappedbody,true);
  906. addstatement(newstatement,wrappedbody);
  907. addstatement(newstatement,exitlabel_asmnode);
  908. addstatement(newstatement,bodyexitcode);
  909. { set flag the implicit finally has been generated }
  910. include(flags,pi_has_implicit_finally);
  911. end
  912. else
  913. begin
  914. { constructors need destroy-on-exception code even if they don't
  915. have managed variables/temps }
  916. maybe_add_constructor_wrapper(code,
  917. (cs_implicit_exceptions in current_settings.moduleswitches) and (f_exceptions in features));
  918. current_filepos:=entrypos;
  919. addstatement(newstatement,code);
  920. current_filepos:=exitpos;
  921. if assigned(nestedexitlabel) then
  922. addstatement(newstatement,clabelnode.create(cnothingnode.create,nestedexitlabel));
  923. addstatement(newstatement,exitlabel_asmnode);
  924. addstatement(newstatement,bodyexitcode);
  925. if not is_constructor then
  926. begin
  927. if procdef.proctypeoption<>potype_exceptfilter then
  928. addstatement(newstatement,cfinalizetempsnode.create);
  929. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  930. temps_finalized:=true;
  931. end;
  932. end;
  933. if not temps_finalized then
  934. begin
  935. current_filepos:=exitpos;
  936. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  937. end;
  938. do_firstpass(newblock);
  939. code:=newblock;
  940. current_filepos:=oldfilepos;
  941. end;
  942. procedure clearrefs(p:TObject;arg:pointer);
  943. begin
  944. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  945. if tabstractvarsym(p).refs>1 then
  946. tabstractvarsym(p).refs:=1;
  947. end;
  948. procedure translate_registers(p:TObject;list:pointer);
  949. begin
  950. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  951. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  952. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  953. begin
  954. if not(cs_no_regalloc in current_settings.globalswitches) then
  955. begin
  956. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  957. if (tabstractnormalvarsym(p).localloc.registerhi<>NR_NO) then
  958. cg.translate_register(tabstractnormalvarsym(p).localloc.registerhi);
  959. end;
  960. end;
  961. end;
  962. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(riscv32) or defined(riscv64) or defined(m68k)}
  963. const
  964. exception_flags: array[boolean] of tprocinfoflags = (
  965. [],
  966. [pi_uses_exceptions,pi_needs_implicit_finally,pi_has_implicit_finally]
  967. );
  968. {$endif}
  969. procedure tcgprocinfo.setup_tempgen;
  970. begin
  971. tg:=tgobjclass.create;
  972. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(m68k)}
  973. {$if defined(arm)}
  974. { frame and stack pointer must be always the same on arm thumb so it makes no
  975. sense to fiddle with a frame pointer }
  976. if GenerateThumbCode then
  977. begin
  978. framepointer:=NR_STACK_POINTER_REG;
  979. tg.direction:=1;
  980. end
  981. else
  982. {$endif defined(arm)}
  983. begin
  984. { try to strip the stack frame }
  985. { set the framepointer to esp if:
  986. - no assembler directive, those are handled in assembler_block
  987. in pstatment.pas (for cases not caught by the Delphi
  988. exception below)
  989. - no exceptions are used
  990. - no pushes are used/esp modifications, could be:
  991. * outgoing parameters on the stack on non-fixed stack target
  992. * incoming parameters on the stack
  993. * open arrays
  994. - no inline assembler
  995. or
  996. - Delphi mode
  997. - assembler directive
  998. - no pushes are used/esp modifications, could be:
  999. * outgoing parameters on the stack
  1000. * incoming parameters on the stack
  1001. * open arrays
  1002. - no local variables
  1003. - stack frame cannot be optimized if using Win64 SEH
  1004. (at least with the current state of our codegenerator).
  1005. }
  1006. if ((po_assembler in procdef.procoptions) and
  1007. (m_delphi in current_settings.modeswitches) and
  1008. { localst at main_program_level is a staticsymtable }
  1009. (procdef.localst.symtablelevel<>main_program_level) and
  1010. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  1011. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  1012. not(cs_generate_stackframes in current_settings.localswitches) and
  1013. not(cs_profile in current_settings.moduleswitches) and
  1014. not(po_assembler in procdef.procoptions) and
  1015. not ((pi_has_stackparameter in flags)
  1016. {$ifndef arm} { Outgoing parameter(s) on stack do not need stackframe on x86 targets
  1017. with fixed stack. On ARM it fails, see bug #25050 }
  1018. and (not paramanager.use_fixed_stack)
  1019. {$endif arm}
  1020. ) and
  1021. ((flags*([pi_has_assembler_block,pi_is_assembler,
  1022. pi_needs_stackframe]+
  1023. exception_flags[((target_info.cpu=cpu_i386) and (not paramanager.use_fixed_stack))
  1024. {$ifndef DISABLE_WIN64_SEH}
  1025. or (target_info.system=system_x86_64_win64)
  1026. {$endif DISABLE_WIN64_SEH}
  1027. ]))=[])
  1028. )
  1029. then
  1030. begin
  1031. { we need the parameter info here to determine if the procedure gets
  1032. parameters on the stack
  1033. calling generate_parameter_info doesn't hurt but it costs time
  1034. (necessary to init para_stack_size)
  1035. }
  1036. generate_parameter_info;
  1037. if not(procdef.stack_tainting_parameter(calleeside)) and
  1038. not(has_assembler_child)
  1039. { parasize must be really zero, this means also that no result may be returned
  1040. in a parameter }
  1041. and not((current_procinfo.procdef.proccalloption in clearstack_pocalls) and
  1042. not(current_procinfo.procdef.generate_safecall_wrapper) and
  1043. paramanager.ret_in_param(current_procinfo.procdef.returndef,current_procinfo.procdef)) then
  1044. begin
  1045. { Only need to set the framepointer }
  1046. framepointer:=NR_STACK_POINTER_REG;
  1047. tg.direction:=1;
  1048. end
  1049. {$if defined(arm)}
  1050. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1051. in case parameters are passed on the stack.
  1052. However, the draw back is, if the estimation fails, compilation will break later on
  1053. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1054. multipass compilation of subroutines must be supported
  1055. }
  1056. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1057. not(has_assembler_child) then
  1058. begin
  1059. { Only need to set the framepointer }
  1060. framepointer:=NR_STACK_POINTER_REG;
  1061. tg.direction:=1;
  1062. include(flags,pi_estimatestacksize);
  1063. set_first_temp_offset;
  1064. procdef.has_paraloc_info:=callnoside;
  1065. generate_parameter_info;
  1066. exit;
  1067. end;
  1068. {$endif defined(arm)}
  1069. end;
  1070. end;
  1071. {$endif defined(x86) or defined(arm) or defined(m68k)}
  1072. {$if defined(xtensa)}
  1073. { On xtensa, the stack frame size can be estimated to avoid using an extra frame pointer,
  1074. in case parameters are passed on the stack.
  1075. However, the draw back is, if the estimation fails, compilation will break later on
  1076. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1077. multipass compilation of subroutines must be supported
  1078. }
  1079. if procdef.stack_tainting_parameter(calleeside) then
  1080. begin
  1081. include(flags,pi_estimatestacksize);
  1082. set_first_temp_offset;
  1083. procdef.has_paraloc_info:=callnoside;
  1084. generate_parameter_info;
  1085. exit;
  1086. end;
  1087. {$endif defined(xtensa)}
  1088. { set the start offset to the start of the temp area in the stack }
  1089. set_first_temp_offset;
  1090. end;
  1091. procedure tcgprocinfo.OptimizeNodeTree;
  1092. var
  1093. i : integer;
  1094. RedoDFA: Boolean;
  1095. {RedoDFA : boolean;}
  1096. begin
  1097. { do this before adding the entry code else the tail recursion recognition won't work,
  1098. if this causes troubles, it must be if'ed
  1099. }
  1100. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1101. (pi_is_recursive in flags) then
  1102. do_opttail(code,procdef);
  1103. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1104. do_optconstpropagate(code);
  1105. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1106. { creating dfa is not always possible }
  1107. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1108. begin
  1109. dfabuilder:=TDFABuilder.Create;
  1110. dfabuilder.createdfainfo(code);
  1111. include(flags,pi_dfaavailable);
  1112. RedoDFA:=false;
  1113. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1114. { our induction variable strength reduction doesn't like
  1115. for loops with more than one entry }
  1116. and not(pi_has_label in flags) then
  1117. begin
  1118. RedoDFA:=OptimizeInductionVariables(code);
  1119. end;
  1120. if RedoDFA then
  1121. begin
  1122. dfabuilder.resetdfainfo(code);
  1123. dfabuilder.createdfainfo(code);
  1124. include(flags,pi_dfaavailable);
  1125. end;
  1126. RedoDFA:=OptimizeForLoop(code);
  1127. RedoDFA:=ConvertForLoops(code) or RedoDFA;
  1128. if RedoDFA then
  1129. begin
  1130. dfabuilder.resetdfainfo(code);
  1131. dfabuilder.createdfainfo(code);
  1132. include(flags,pi_dfaavailable);
  1133. end;
  1134. { when life info is available, we can give more sophisticated warning about uninitialized
  1135. variables ...
  1136. ... but not for the finalization section of a unit, we would need global dfa to handle
  1137. it properly }
  1138. if potype_unitfinalize<>procdef.proctypeoption then
  1139. { iterate through life info of the first node }
  1140. for i:=0 to dfabuilder.nodemap.count-1 do
  1141. begin
  1142. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1143. begin
  1144. { do not warn for certain parameters: }
  1145. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1146. { do not warn about parameters passed by var }
  1147. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1148. { function result is passed by var but it must be initialized }
  1149. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1150. { do not warn about initialized hidden parameters }
  1151. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1152. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1153. end
  1154. else
  1155. begin
  1156. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1157. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1158. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1159. end;
  1160. end;
  1161. end
  1162. else
  1163. begin
  1164. ConvertForLoops(code);
  1165. end;
  1166. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1167. do_optdeadstoreelim(code);
  1168. if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
  1169. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1170. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1171. procdef.isempty:=true;
  1172. if cs_opt_nodecse in current_settings.optimizerswitches then
  1173. do_optcse(code);
  1174. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1175. do_optloadmodifystore(code);
  1176. if cs_opt_consts in current_settings.optimizerswitches then
  1177. do_consttovar(code);
  1178. end;
  1179. function tcgprocinfo.has_assembler_child : boolean;
  1180. var
  1181. hp : tprocinfo;
  1182. begin
  1183. result:=false;
  1184. hp:=get_first_nestedproc;
  1185. while assigned(hp) do
  1186. begin
  1187. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  1188. begin
  1189. result:=true;
  1190. exit;
  1191. end;
  1192. hp:=tprocinfo(hp.next);
  1193. end;
  1194. end;
  1195. procedure tcgprocinfo.set_eh_info;
  1196. begin
  1197. inherited;
  1198. if (tf_use_psabieh in target_info.flags) and
  1199. ((pi_uses_exceptions in flags) or
  1200. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1201. (pi_needs_implicit_finally in flags))) or
  1202. (pi_has_except_table_data in flags) then
  1203. procdef.personality:=search_system_proc('_FPC_PSABIEH_PERSONALITY_V0');
  1204. end;
  1205. function tcgprocinfo.store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  1206. var
  1207. nodeset : THashSet absolute arg;
  1208. entry : ptempinfo_flags_entry;
  1209. i : longint;
  1210. {hashsetitem: PHashSetItem;}
  1211. begin
  1212. result:=fen_true;
  1213. case n.nodetype of
  1214. tempcreaten:
  1215. begin
  1216. {$ifdef EXTDEBUG}
  1217. comment(V_Debug,'keeping track of new temp node: '+hexstr(ttempbasenode(n).tempinfo));
  1218. {$endif EXTDEBUG}
  1219. nodeset.FindOrAdd(ttempbasenode(n).tempinfo,sizeof(pointer));
  1220. end;
  1221. tempdeleten:
  1222. begin
  1223. {$ifdef EXTDEBUG}
  1224. comment(V_Debug,'got temp delete node: '+hexstr(ttempbasenode(n).tempinfo));
  1225. {$endif EXTDEBUG}
  1226. { don't remove temp nodes so that outside code can know if some temp
  1227. was only created in here }
  1228. (*hashsetitem:=nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer));
  1229. if assigned(hashsetitem) then
  1230. begin
  1231. {$ifdef EXTDEBUG}
  1232. comment(V_Debug,'no longer keeping track of temp node');
  1233. {$endif EXTDEBUG}
  1234. writeln('no longer keeping track of temp node');
  1235. nodeset.Remove(hashsetitem);
  1236. end;*)
  1237. end;
  1238. temprefn:
  1239. begin
  1240. {$ifdef EXTDEBUG}
  1241. comment(V_Debug,'found temp ref node: '+hexstr(ttempbasenode(n).tempinfo));
  1242. {$endif EXTDEBUG}
  1243. if not assigned(nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer))) then
  1244. begin
  1245. for i:=0 to tempinfo_flags_map.count-1 do
  1246. begin
  1247. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1248. {$ifdef EXTDEBUG}
  1249. comment(V_Debug,'comparing with tempinfo: '+hexstr(entry^.tempinfo));
  1250. {$endif EXTDEBUG}
  1251. if entry^.tempinfo=ttempbasenode(n).tempinfo then
  1252. begin
  1253. {$ifdef EXTDEBUG}
  1254. comment(V_Debug,'temp node exists');
  1255. {$endif EXTDEBUG}
  1256. exit;
  1257. end;
  1258. end;
  1259. {$ifdef EXTDEBUG}
  1260. comment(V_Debug,'storing node');
  1261. {$endif EXTDEBUG}
  1262. new(entry);
  1263. entry^.tempinfo:=ttempbasenode(n).tempinfo;
  1264. entry^.flags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1265. tempinfo_flags_map.add(entry);
  1266. end
  1267. else
  1268. begin
  1269. {$ifdef EXTDEBUG}
  1270. comment(V_Debug,'ignoring node');
  1271. {$endif EXTDEBUG}
  1272. end;
  1273. end;
  1274. else
  1275. ;
  1276. end;
  1277. end;
  1278. procedure tcgprocinfo.store_tempflags;
  1279. var
  1280. nodeset : THashSet;
  1281. begin
  1282. if assigned(tempinfo_flags_map) then
  1283. internalerror(2020040601);
  1284. {$ifdef EXTDEBUG}
  1285. comment(V_Debug,'storing temp nodes of '+procdef.mangledname);
  1286. {$endif EXTDEBUG}
  1287. tempinfo_flags_map:=tfplist.create;
  1288. nodeset:=THashSet.Create(32,false,false);
  1289. foreachnode(code,@store_node_tempflags,nodeset);
  1290. nodeset.free;
  1291. end;
  1292. procedure tcgprocinfo.swap_tempflags;
  1293. var
  1294. entry : ptempinfo_flags_entry;
  1295. i : longint;
  1296. tempflags : ttempinfoflags;
  1297. begin
  1298. if not assigned(tempinfo_flags_map) then
  1299. exit;
  1300. for i:=0 to tempinfo_flags_map.count-1 do
  1301. begin
  1302. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1303. tempflags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1304. ttempinfoaccessor.settempinfoflags(entry^.tempinfo,entry^.flags);
  1305. entry^.flags:=tempflags;
  1306. end;
  1307. end;
  1308. procedure tcgprocinfo.apply_tempflags;
  1309. begin
  1310. if tempflags_swapped then
  1311. internalerror(2020040602);
  1312. swap_tempflags;
  1313. tempflags_swapped:=true;
  1314. end;
  1315. procedure tcgprocinfo.reset_tempflags;
  1316. begin
  1317. if not tempflags_swapped then
  1318. internalerror(2020040603);
  1319. swap_tempflags;
  1320. tempflags_swapped:=false;
  1321. end;
  1322. {$ifdef DEBUG_NODE_XML}
  1323. procedure tcgprocinfo.XMLPrintProc(FirstHalf: Boolean);
  1324. var
  1325. T: Text;
  1326. W: Word;
  1327. syssym: tsyssym;
  1328. separate : boolean;
  1329. procedure PrintType(Flag: string);
  1330. begin
  1331. if df_generic in procdef.defoptions then
  1332. Write(T, ' type="generic ', Flag, '"')
  1333. else
  1334. Write(T, ' type="', Flag, '"');
  1335. end;
  1336. procedure PrintOption(Flag: string);
  1337. begin
  1338. WriteLn(T, PrintNodeIndention, '<option>', Flag, '</option>');
  1339. end;
  1340. begin
  1341. if current_module.ppxfilefail then
  1342. Exit;
  1343. Assign(T, current_module.ppxfilename);
  1344. {$push} {$I-}
  1345. Append(T);
  1346. if IOResult <> 0 then
  1347. begin
  1348. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  1349. current_module.ppxfilefail := True;
  1350. Exit;
  1351. end;
  1352. {$pop}
  1353. separate := (df_generic in procdef.defoptions);
  1354. { First half prints the header and the nodes as a "code" tag }
  1355. if FirstHalf or separate then
  1356. begin
  1357. Write(T, PrintNodeIndention, '<subroutine');
  1358. { Check to see if the procedure is a class or object method }
  1359. if Assigned(procdef.struct) then
  1360. begin
  1361. if Assigned(procdef.struct.objrealname) then
  1362. Write(T, ' struct="', SanitiseXMLString(procdef.struct.objrealname^), '"')
  1363. else
  1364. Write(T, ' struct="&lt;NULL&gt;"');
  1365. end;
  1366. case procdef.proctypeoption of
  1367. potype_none:
  1368. { Do nothing - should this be an internal error though? };
  1369. potype_procedure,
  1370. potype_function:
  1371. if po_classmethod in procdef.procoptions then
  1372. begin
  1373. if po_staticmethod in procdef.procoptions then
  1374. PrintType('static class method')
  1375. else
  1376. PrintType('class method');
  1377. end
  1378. else if df_generic in procdef.defoptions then
  1379. Write(T, ' type="generic"');
  1380. potype_proginit,
  1381. potype_unitinit:
  1382. PrintType('initialization');
  1383. potype_unitfinalize:
  1384. PrintType('finalization');
  1385. potype_constructor:
  1386. PrintType('constructor');
  1387. potype_destructor:
  1388. PrintType('destructor');
  1389. potype_operator:
  1390. PrintType('operator');
  1391. potype_class_constructor:
  1392. PrintType('class constructor');
  1393. potype_class_destructor:
  1394. PrintType('class destructor');
  1395. potype_propgetter:
  1396. PrintType('dispinterface getter');
  1397. potype_propsetter:
  1398. PrintType('dispinterface setter');
  1399. potype_exceptfilter:
  1400. PrintType('except filter');
  1401. potype_mainstub:
  1402. PrintType('main stub');
  1403. potype_libmainstub:
  1404. PrintType('library main stub');
  1405. potype_pkgstub:
  1406. PrintType('package stub');
  1407. end;
  1408. Write(T, ' name="', SanitiseXMLString(procdef.customprocname([pno_showhidden, pno_noclassmarker])), '"');
  1409. if po_hascallingconvention in procdef.procoptions then
  1410. Write(T, ' convention="', proccalloptionStr[procdef.proccalloption], '"');
  1411. WriteLn(T, '>');
  1412. PrintNodeIndent;
  1413. if Assigned(procdef.returndef) and not is_void(procdef.returndef) then
  1414. WriteLn(T, PrintNodeIndention, '<returndef>', SanitiseXMLString(procdef.returndef.typesymbolprettyname), '</returndef>');
  1415. if po_reintroduce in procdef.procoptions then
  1416. PrintOption('reintroduce');
  1417. if po_virtualmethod in procdef.procoptions then
  1418. PrintOption('virtual');
  1419. if po_finalmethod in procdef.procoptions then
  1420. PrintOption('final');
  1421. if po_overridingmethod in procdef.procoptions then
  1422. PrintOption('override');
  1423. if po_overload in procdef.procoptions then
  1424. PrintOption('overload');
  1425. if po_compilerproc in procdef.procoptions then
  1426. PrintOption('compilerproc');
  1427. if po_assembler in procdef.procoptions then
  1428. PrintOption('assembler');
  1429. if po_nostackframe in procdef.procoptions then
  1430. PrintOption('nostackframe');
  1431. if po_inline in procdef.procoptions then
  1432. PrintOption('inline');
  1433. if po_noreturn in procdef.procoptions then
  1434. PrintOption('noreturn');
  1435. if po_noinline in procdef.procoptions then
  1436. PrintOption('noinline');
  1437. end;
  1438. if Assigned(Code) then
  1439. begin
  1440. if FirstHalf then
  1441. WriteLn(T, PrintNodeIndention, '<code>')
  1442. else
  1443. begin
  1444. WriteLn(T); { Line for spacing }
  1445. WriteLn(T, PrintNodeIndention, '<firstpass>');
  1446. end;
  1447. PrintNodeIndent;
  1448. XMLPrintNode(T, Code);
  1449. PrintNodeUnindent;
  1450. if FirstHalf then
  1451. WriteLn(T, PrintNodeIndention, '</code>')
  1452. else
  1453. WriteLn(T, PrintNodeIndention, '</firstpass>');
  1454. end
  1455. else { Code=Nil }
  1456. begin
  1457. { Don't print anything for second half - if there's no code, there's no firstpass }
  1458. if FirstHalf then
  1459. WriteLn(T, PrintNodeIndention, '<code />');
  1460. end;
  1461. { Print footer only for second half }
  1462. if (not FirstHalf) or separate then
  1463. begin
  1464. PrintNodeUnindent;
  1465. WriteLn(T, PrintNodeIndention, '</subroutine>');
  1466. WriteLn(T); { Line for spacing }
  1467. end;
  1468. Close(T);
  1469. end;
  1470. {$endif DEBUG_NODE_XML}
  1471. procedure tcgprocinfo.generate_code_tree;
  1472. var
  1473. hpi : tcgprocinfo;
  1474. begin
  1475. { generate code for this procedure }
  1476. generate_code;
  1477. { process nested procedures }
  1478. hpi:=tcgprocinfo(get_first_nestedproc);
  1479. while assigned(hpi) do
  1480. begin
  1481. hpi.generate_code_tree;
  1482. hpi:=tcgprocinfo(hpi.next);
  1483. end;
  1484. resetprocdef;
  1485. end;
  1486. procedure tcgprocinfo.generate_code_exceptfilters;
  1487. var
  1488. hpi : tcgprocinfo;
  1489. begin
  1490. hpi:=tcgprocinfo(get_first_nestedproc);
  1491. while assigned(hpi) do
  1492. begin
  1493. if hpi.procdef.proctypeoption=potype_exceptfilter then
  1494. begin
  1495. hpi.apply_tempflags;
  1496. generate_exceptfilter(hpi);
  1497. hpi.reset_tempflags;
  1498. end;
  1499. hpi:=tcgprocinfo(hpi.next);
  1500. end;
  1501. end;
  1502. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  1503. which can be called by OS during stack unwind. This resembles nested procedures,
  1504. but finalizer procedures do not have their own local variables and work directly
  1505. with the stack frame of parent. In particular, the tempgen must be shared, so
  1506. 1) finalizer procedure is able to finalize temps of the parent,
  1507. 2) if the finalizer procedure is complex enough to need its own temps, they are
  1508. allocated in stack frame of parent, so second-level finalizer procedures are
  1509. not needed.
  1510. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  1511. procedure (after the parent) and have to do it inline.
  1512. This is called by platform-specific tryfinallynodes during pass2.
  1513. Here we put away the codegen (which carries the register allocator state), process
  1514. the 'nested' procedure, then restore previous cg and continue processing the parent
  1515. procedure. generate_code() will create another cg, but not another tempgen because
  1516. setup_tempgen() is not called for potype_exceptfilter procedures. }
  1517. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  1518. var
  1519. saved_cg: tcg;
  1520. saved_hlcg: thlcgobj;
  1521. {$ifdef cpu64bitalu}
  1522. saved_cg128 : tcg128;
  1523. {$else cpu64bitalu}
  1524. saved_cg64 : tcg64;
  1525. {$endif cpu64bitalu}
  1526. begin
  1527. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  1528. InternalError(201201141);
  1529. { flush code generated this far }
  1530. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1531. { save the codegen }
  1532. saved_cg:=cg;
  1533. saved_hlcg:=hlcg;
  1534. cg:=nil;
  1535. hlcg:=nil;
  1536. {$ifdef cpu64bitalu}
  1537. saved_cg128:=cg128;
  1538. cg128:=nil;
  1539. {$else cpu64bitalu}
  1540. saved_cg64:=cg64;
  1541. cg64:=nil;
  1542. {$endif cpu64bitalu}
  1543. nestedpi.generate_code;
  1544. { prevents generating code the second time when processing nested procedures }
  1545. nestedpi.resetprocdef;
  1546. cg:=saved_cg;
  1547. hlcg:=saved_hlcg;
  1548. {$ifdef cpu64bitalu}
  1549. cg128:=saved_cg128;
  1550. {$else cpu64bitalu}
  1551. cg64:=saved_cg64;
  1552. {$endif cpu64bitalu}
  1553. add_reg_instruction_hook:[email protected]_reg_instruction;
  1554. end;
  1555. procedure TCGProcinfo.CreateInlineInfo;
  1556. begin
  1557. new(procdef.inlininginfo);
  1558. procdef.inlininginfo^.code:=code.getcopy;
  1559. procdef.inlininginfo^.flags:=flags;
  1560. { The blocknode needs to set an exit label }
  1561. if procdef.inlininginfo^.code.nodetype=blockn then
  1562. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1563. procdef.has_inlininginfo:=true;
  1564. export_local_ref_syms;
  1565. export_local_ref_defs;
  1566. end;
  1567. procedure searchthreadvar(p: TObject; arg: pointer);
  1568. var
  1569. i : longint;
  1570. pd : tprocdef;
  1571. begin
  1572. case tsym(p).typ of
  1573. staticvarsym :
  1574. begin
  1575. { local (procedure or unit) variables only need finalization
  1576. if they are used
  1577. }
  1578. if (vo_is_thread_var in tstaticvarsym(p).varoptions) and
  1579. ((tstaticvarsym(p).refs>0) or
  1580. { global (unit) variables always need finalization, since
  1581. they may also be used in another unit
  1582. }
  1583. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  1584. (
  1585. (tstaticvarsym(p).varspez<>vs_const) or
  1586. (vo_force_finalize in tstaticvarsym(p).varoptions)
  1587. ) and
  1588. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  1589. not(vo_is_external in tstaticvarsym(p).varoptions) and
  1590. is_managed_type(tstaticvarsym(p).vardef) then
  1591. include(current_procinfo.flags,pi_uses_threadvar);
  1592. end;
  1593. procsym :
  1594. begin
  1595. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  1596. begin
  1597. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  1598. if assigned(pd.localst) and
  1599. (pd.procsym=tprocsym(p)) and
  1600. (pd.localst.symtabletype<>staticsymtable) then
  1601. pd.localst.SymList.ForEachCall(@searchthreadvar,arg);
  1602. end;
  1603. end;
  1604. else
  1605. ;
  1606. end;
  1607. end;
  1608. function searchusercode(var n: tnode; arg: pointer): foreachnoderesult;
  1609. begin
  1610. if nf_usercode_entry in n.flags then
  1611. begin
  1612. pnode(arg)^:=n;
  1613. result:=fen_norecurse_true
  1614. end
  1615. else
  1616. result:=fen_false;
  1617. end;
  1618. function TCGProcinfo.GetUserCode : tnode;
  1619. var
  1620. n : tnode;
  1621. begin
  1622. n:=nil;
  1623. foreachnodestatic(code,@searchusercode,@n);
  1624. if not(assigned(n)) then
  1625. internalerror(2013111004);
  1626. result:=n;
  1627. end;
  1628. procedure tcgprocinfo.generate_code;
  1629. procedure check_for_threadvars_in_initfinal;
  1630. begin
  1631. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  1632. begin
  1633. { this is also used for initialization of variables in a
  1634. program which does not have a globalsymtable }
  1635. if assigned(current_module.globalsymtable) then
  1636. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1637. TSymtable(current_module.localsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1638. end;
  1639. end;
  1640. var
  1641. old_current_procinfo : tprocinfo;
  1642. oldmaxfpuregisters : longint;
  1643. oldfilepos : tfileposinfo;
  1644. old_current_structdef : tabstractrecorddef;
  1645. oldswitches : tlocalswitches;
  1646. templist : TAsmList;
  1647. headertai : tai;
  1648. procedure delete_marker(anode: tasmnode);
  1649. var
  1650. ai: tai;
  1651. begin
  1652. if assigned(anode) then
  1653. begin
  1654. ai:=anode.currenttai;
  1655. if assigned(ai) then
  1656. begin
  1657. aktproccode.remove(ai);
  1658. ai.free;
  1659. anode.currenttai:=nil;
  1660. end;
  1661. end;
  1662. end;
  1663. begin
  1664. { the initialization procedure can be empty, then we
  1665. don't need to generate anything. When it was an empty
  1666. procedure there would be at least a blocknode }
  1667. if not assigned(code) then
  1668. begin
  1669. {$ifdef DEBUG_NODE_XML}
  1670. { Print out nodes as they appear after the first pass }
  1671. XMLPrintProc(True);
  1672. XMLPrintProc(False);
  1673. {$endif DEBUG_NODE_XML}
  1674. exit;
  1675. end;
  1676. { We need valid code }
  1677. if Errorcount<>0 then
  1678. exit;
  1679. { No code can be generated for generic template }
  1680. if (df_generic in procdef.defoptions) then
  1681. internalerror(200511152);
  1682. { For regular procedures the RA and Tempgen shall not be available yet,
  1683. but exception filters reuse Tempgen of parent }
  1684. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1685. internalerror(200309201);
  1686. old_current_procinfo:=current_procinfo;
  1687. oldfilepos:=current_filepos;
  1688. old_current_structdef:=current_structdef;
  1689. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1690. current_procinfo:=self;
  1691. current_filepos:=entrypos;
  1692. current_structdef:=procdef.struct;
  1693. { store start of user code, it must be a block node, it will be used later one to
  1694. check variable lifeness }
  1695. include(code.flags,nf_usercode_entry);
  1696. { add wrapping code if necessary (initialization of typed constants on
  1697. some platforms, initing of local variables and out parameters with
  1698. trashing values, ...) }
  1699. { init/final code must be wrapped later (after code for main proc body
  1700. has been generated) }
  1701. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1702. code:=cnodeutils.wrap_proc_body(procdef,code);
  1703. { automatic inlining? }
  1704. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1705. not(po_noinline in procdef.procoptions) and
  1706. { no inlining yet? }
  1707. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1708. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1709. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1710. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1711. (not(procdef.proccalloption in [pocall_safecall])) and
  1712. { rough approximation if we should auto inline:
  1713. - if the tree is simple enough
  1714. - if the tree is not too big
  1715. A bigger tree which is simpler might be autoinlined otoh
  1716. a smaller and complexer tree as well: so we use the sum of
  1717. both measures here }
  1718. (node_count(code)+node_complexity(code)<=25) then
  1719. begin
  1720. { Can we inline this procedure? }
  1721. if checknodeinlining(procdef) then
  1722. begin
  1723. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1724. include(procdef.procoptions,po_inline);
  1725. CreateInlineInfo;
  1726. end;
  1727. end;
  1728. templist:=TAsmList.create;
  1729. { add parast/localst to symtablestack }
  1730. add_to_symtablestack;
  1731. { clear register count }
  1732. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1733. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1734. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1735. if (procdef.localst.symtablelevel=main_program_level) and
  1736. (not current_module.is_unit) then
  1737. begin
  1738. include(flags,pi_do_call);
  1739. { the main program never returns due to the do_exit call }
  1740. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1741. include(procdef.procoptions,po_noreturn);
  1742. end;
  1743. { set implicit_finally flag when there are locals/paras to be finalized }
  1744. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1745. begin
  1746. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1747. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1748. end;
  1749. {$ifdef SUPPORT_SAFECALL}
  1750. { set implicit_finally flag for if procedure is safecall }
  1751. if (tf_safecall_exceptions in target_info.flags) and
  1752. (procdef.proccalloption=pocall_safecall) then
  1753. include(flags, pi_needs_implicit_finally);
  1754. {$endif}
  1755. {$ifdef DEBUG_NODE_XML}
  1756. { Print out nodes as they appear after the first pass }
  1757. XMLPrintProc(True);
  1758. {$endif DEBUG_NODE_XML}
  1759. { firstpass everything }
  1760. flowcontrol:=[];
  1761. do_firstpass(code);
  1762. {$if defined(i386) or defined(i8086)}
  1763. if node_resources_fpu(code)>0 then
  1764. include(flags,pi_uses_fpu);
  1765. {$endif i386 or i8086}
  1766. { Print the node to tree.log }
  1767. if paraprintnodetree <> 0 then
  1768. printproc( 'after the firstpass');
  1769. OptimizeNodeTree;
  1770. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1771. require a tls register, so check for such variables }
  1772. check_for_threadvars_in_initfinal;
  1773. { add implicit entry and exit code }
  1774. add_entry_exit_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. {$if not defined(jvm) and not defined(wasm)}
  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.