2
0

psub.pas 93 KB

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