psub.pas 109 KB

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