psub.pas 129 KB

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