psub.pas 91 KB

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