psub.pas 108 KB

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