psub.pas 129 KB

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