psub.pas 129 KB

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