psub.pas 94 KB

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