psub.pas 130 KB

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