psub.pas 127 KB

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