psub.pas 128 KB

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