psub.pas 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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. cclasses,globals,
  22. node,nbas,
  23. symdef,procinfo;
  24. type
  25. tcgprocinfo = class(tprocinfo)
  26. private
  27. procedure add_entry_exit_code;
  28. public
  29. { code for the subroutine as tree }
  30. code : tnode;
  31. { positions in the tree for init/final }
  32. entry_asmnode,
  33. loadpara_asmnode,
  34. exitlabel_asmnode,
  35. stackcheck_asmnode,
  36. init_asmnode,
  37. final_asmnode : tasmnode;
  38. { list to store the procinfo's of the nested procedures }
  39. nestedprocs : tlinkedlist;
  40. constructor create(aparent:tprocinfo);override;
  41. destructor destroy;override;
  42. procedure printproc;
  43. procedure generate_code;
  44. procedure resetprocdef;
  45. procedure add_to_symtablestack;
  46. procedure remove_from_symtablestack;
  47. procedure parse_body;
  48. function stack_tainting_parameter : boolean;
  49. function has_assembler_child : boolean;
  50. end;
  51. procedure printnode_reset;
  52. { reads the declaration blocks }
  53. procedure read_declarations(islibrary : boolean);
  54. { reads declarations in the interface part of a unit }
  55. procedure read_interface_declarations;
  56. procedure generate_specialization_procs;
  57. implementation
  58. uses
  59. sysutils,
  60. { common }
  61. cutils,
  62. { global }
  63. globtype,tokens,verbose,comphook,
  64. systems,
  65. { aasm }
  66. cpubase,aasmbase,aasmtai,aasmdata,
  67. { symtable }
  68. symconst,symbase,symsym,symtype,symtable,defutil,
  69. paramgr,
  70. ppu,fmodule,
  71. { pass 1 }
  72. nutils,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  73. pass_1,
  74. {$ifdef state_tracking}
  75. nstate,
  76. {$endif state_tracking}
  77. { pass 2 }
  78. {$ifndef NOPASS2}
  79. pass_2,
  80. {$endif}
  81. { parser }
  82. scanner,import,gendef,
  83. pbase,pstatmnt,pdecl,pdecsub,pexports,
  84. { codegen }
  85. tgobj,cgbase,cgobj,dbgbase,
  86. ncgutil,regvars,
  87. opttail
  88. {$if defined(arm) or defined(powerpc) or defined(powerpc64)}
  89. ,aasmcpu
  90. {$endif arm}
  91. {$ifndef NOOPT}
  92. {$ifdef i386}
  93. ,aopt386
  94. {$else i386}
  95. ,aopt
  96. {$endif i386}
  97. {$endif}
  98. ;
  99. {****************************************************************************
  100. PROCEDURE/FUNCTION BODY PARSING
  101. ****************************************************************************}
  102. procedure initializevars(p:TObject;arg:pointer);
  103. var
  104. b : tblocknode;
  105. begin
  106. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  107. exit;
  108. with tabstractnormalvarsym(p) do
  109. begin
  110. if assigned(defaultconstsym) then
  111. begin
  112. b:=tblocknode(arg);
  113. b.left:=cstatementnode.create(
  114. cassignmentnode.create(
  115. cloadnode.create(tsym(p),tsym(p).owner),
  116. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  117. b.left);
  118. end;
  119. end;
  120. end;
  121. procedure check_finalize_paras(p:TObject;arg:pointer);
  122. begin
  123. if (tsym(p).typ=paravarsym) and
  124. (tparavarsym(p).varspez=vs_value) and
  125. not is_class(tparavarsym(p).vardef) and
  126. tparavarsym(p).vardef.needs_inittable then
  127. include(current_procinfo.flags,pi_needs_implicit_finally);
  128. end;
  129. procedure check_finalize_locals(p:TObject;arg:pointer);
  130. begin
  131. if (tsym(p).typ=localvarsym) and
  132. (tlocalvarsym(p).refs>0) and
  133. not(vo_is_funcret in tlocalvarsym(p).varoptions) and
  134. not(is_class(tlocalvarsym(p).vardef)) and
  135. tlocalvarsym(p).vardef.needs_inittable then
  136. include(current_procinfo.flags,pi_needs_implicit_finally);
  137. end;
  138. function block(islibrary : boolean) : tnode;
  139. begin
  140. { parse const,types and vars }
  141. read_declarations(islibrary);
  142. { do we have an assembler block without the po_assembler?
  143. we should allow this for Delphi compatibility (PFV) }
  144. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  145. include(current_procinfo.procdef.procoptions,po_assembler);
  146. { Handle assembler block different }
  147. if (po_assembler in current_procinfo.procdef.procoptions) then
  148. begin
  149. block:=assembler_block;
  150. exit;
  151. end;
  152. {Unit initialization?.}
  153. if (
  154. assigned(current_procinfo.procdef.localst) and
  155. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  156. (current_module.is_unit)
  157. ) or
  158. islibrary then
  159. begin
  160. if (token=_END) then
  161. begin
  162. consume(_END);
  163. { We need at least a node, else the entry/exit code is not
  164. generated and thus no PASCALMAIN symbol which we need (PFV) }
  165. if islibrary then
  166. block:=cnothingnode.create
  167. else
  168. block:=nil;
  169. end
  170. else
  171. begin
  172. if token=_INITIALIZATION then
  173. begin
  174. { The library init code is already called and does not
  175. need to be in the initfinal table (PFV) }
  176. if not islibrary then
  177. current_module.flags:=current_module.flags or uf_init;
  178. block:=statement_block(_INITIALIZATION);
  179. end
  180. else if (token=_FINALIZATION) then
  181. begin
  182. if (current_module.flags and uf_finalize)<>0 then
  183. block:=statement_block(_FINALIZATION)
  184. else
  185. begin
  186. { can we allow no INITIALIZATION for DLL ??
  187. I think it should work PM }
  188. block:=nil;
  189. exit;
  190. end;
  191. end
  192. else
  193. begin
  194. { The library init code is already called and does not
  195. need to be in the initfinal table (PFV) }
  196. if not islibrary then
  197. current_module.flags:=current_module.flags or uf_init;
  198. block:=statement_block(_BEGIN);
  199. end;
  200. end;
  201. end
  202. else
  203. begin
  204. block:=statement_block(_BEGIN);
  205. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  206. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  207. end;
  208. end;
  209. {****************************************************************************
  210. PROCEDURE/FUNCTION COMPILING
  211. ****************************************************************************}
  212. procedure printnode_reset;
  213. begin
  214. assign(printnodefile,treelogfilename);
  215. {$I-}
  216. rewrite(printnodefile);
  217. {$I+}
  218. if ioresult<>0 then
  219. begin
  220. Comment(V_Error,'Error creating '+treelogfilename);
  221. exit;
  222. end;
  223. close(printnodefile);
  224. end;
  225. function generate_bodyentry_block:tnode;
  226. var
  227. srsym : tsym;
  228. para : tcallparanode;
  229. newstatement : tstatementnode;
  230. hdef : tdef;
  231. begin
  232. result:=internalstatements(newstatement);
  233. if assigned(current_procinfo.procdef._class) then
  234. begin
  235. { a constructor needs a help procedure }
  236. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  237. begin
  238. if is_class(current_procinfo.procdef._class) then
  239. begin
  240. include(current_procinfo.flags,pi_needs_implicit_finally);
  241. srsym:=search_class_member(current_procinfo.procdef._class,'NEWINSTANCE');
  242. if assigned(srsym) and
  243. (srsym.typ=procsym) then
  244. begin
  245. { if vmt>1 then newinstance }
  246. addstatement(newstatement,cifnode.create(
  247. caddnode.create(gtn,
  248. ctypeconvnode.create_internal(
  249. load_vmt_pointer_node,
  250. voidpointertype),
  251. cpointerconstnode.create(1,voidpointertype)),
  252. cassignmentnode.create(
  253. ctypeconvnode.create_internal(
  254. load_self_pointer_node,
  255. voidpointertype),
  256. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_vmt_pointer_node,[])),
  257. nil));
  258. end
  259. else
  260. internalerror(200305108);
  261. end
  262. else
  263. if is_object(current_procinfo.procdef._class) then
  264. begin
  265. hdef:=current_procinfo.procdef._class;
  266. hdef:=tpointerdef.create(hdef);
  267. { parameter 3 : vmt_offset }
  268. { parameter 2 : address of pointer to vmt,
  269. this is required to allow setting the vmt to -1 to indicate
  270. that memory was allocated }
  271. { parameter 1 : self pointer }
  272. para:=ccallparanode.create(
  273. cordconstnode.create(current_procinfo.procdef._class.vmt_offset,s32inttype,false),
  274. ccallparanode.create(
  275. ctypeconvnode.create_internal(
  276. load_vmt_pointer_node,
  277. voidpointertype),
  278. ccallparanode.create(
  279. ctypeconvnode.create_internal(
  280. load_self_pointer_node,
  281. voidpointertype),
  282. nil)));
  283. addstatement(newstatement,cassignmentnode.create(
  284. ctypeconvnode.create_internal(
  285. load_self_pointer_node,
  286. voidpointertype),
  287. ccallnode.createintern('fpc_help_constructor',para)));
  288. end
  289. else
  290. internalerror(200305103);
  291. { if self=nil then exit
  292. calling fail instead of exit is useless because
  293. there is nothing to dispose (PFV) }
  294. addstatement(newstatement,cifnode.create(
  295. caddnode.create(equaln,
  296. load_self_pointer_node,
  297. cnilnode.create),
  298. cexitnode.create(nil),
  299. nil));
  300. end;
  301. { maybe call BeforeDestruction for classes }
  302. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  303. is_class(current_procinfo.procdef._class) then
  304. begin
  305. srsym:=search_class_member(current_procinfo.procdef._class,'BEFOREDESTRUCTION');
  306. if assigned(srsym) and
  307. (srsym.typ=procsym) then
  308. begin
  309. { if vmt<>0 then beforedestruction }
  310. addstatement(newstatement,cifnode.create(
  311. caddnode.create(unequaln,
  312. load_vmt_pointer_node,
  313. cnilnode.create),
  314. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  315. nil));
  316. end
  317. else
  318. internalerror(200305104);
  319. end;
  320. end;
  321. end;
  322. function generate_bodyexit_block:tnode;
  323. var
  324. srsym : tsym;
  325. para : tcallparanode;
  326. newstatement : tstatementnode;
  327. oldlocalswitches: tlocalswitches;
  328. begin
  329. result:=internalstatements(newstatement);
  330. if assigned(current_procinfo.procdef._class) then
  331. begin
  332. { Don't test self and the vmt here. The reason is that }
  333. { a constructor already checks whether these are valid }
  334. { before. Further, in case of TThread the thread may }
  335. { free the class instance right after AfterConstruction }
  336. { has been called, so it may no longer be valid (JM) }
  337. oldlocalswitches:=current_settings.localswitches;
  338. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  339. { maybe call AfterConstruction for classes }
  340. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  341. is_class(current_procinfo.procdef._class) then
  342. begin
  343. srsym:=search_class_member(current_procinfo.procdef._class,'AFTERCONSTRUCTION');
  344. if assigned(srsym) and
  345. (srsym.typ=procsym) then
  346. begin
  347. { Self can be nil when fail is called }
  348. { if self<>nil and vmt<>nil then afterconstruction }
  349. addstatement(newstatement,cifnode.create(
  350. caddnode.create(andn,
  351. caddnode.create(unequaln,
  352. load_self_pointer_node,
  353. cnilnode.create),
  354. caddnode.create(unequaln,
  355. load_vmt_pointer_node,
  356. cnilnode.create)),
  357. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  358. nil));
  359. end
  360. else
  361. internalerror(200305106);
  362. end;
  363. { a destructor needs a help procedure }
  364. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  365. begin
  366. if is_class(current_procinfo.procdef._class) then
  367. begin
  368. srsym:=search_class_member(current_procinfo.procdef._class,'FREEINSTANCE');
  369. if assigned(srsym) and
  370. (srsym.typ=procsym) then
  371. begin
  372. { if self<>0 and vmt=1 then freeinstance }
  373. addstatement(newstatement,cifnode.create(
  374. caddnode.create(andn,
  375. caddnode.create(unequaln,
  376. load_self_pointer_node,
  377. cnilnode.create),
  378. caddnode.create(equaln,
  379. ctypeconvnode.create(
  380. load_vmt_pointer_node,
  381. voidpointertype),
  382. cpointerconstnode.create(1,voidpointertype))),
  383. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  384. nil));
  385. end
  386. else
  387. internalerror(200305108);
  388. end
  389. else
  390. if is_object(current_procinfo.procdef._class) then
  391. begin
  392. { finalize object data }
  393. if current_procinfo.procdef._class.needs_inittable then
  394. addstatement(newstatement,finalize_data_node(load_self_node));
  395. { parameter 3 : vmt_offset }
  396. { parameter 2 : pointer to vmt }
  397. { parameter 1 : self pointer }
  398. para:=ccallparanode.create(
  399. cordconstnode.create(current_procinfo.procdef._class.vmt_offset,s32inttype,false),
  400. ccallparanode.create(
  401. ctypeconvnode.create_internal(
  402. load_vmt_pointer_node,
  403. voidpointertype),
  404. ccallparanode.create(
  405. ctypeconvnode.create_internal(
  406. load_self_pointer_node,
  407. voidpointertype),
  408. nil)));
  409. addstatement(newstatement,
  410. ccallnode.createintern('fpc_help_destructor',para));
  411. end
  412. else
  413. internalerror(200305105);
  414. end;
  415. current_settings.localswitches:=oldlocalswitches;
  416. end;
  417. end;
  418. function generate_except_block:tnode;
  419. var
  420. pd : tprocdef;
  421. newstatement : tstatementnode;
  422. oldlocalswitches: tlocalswitches;
  423. begin
  424. generate_except_block:=internalstatements(newstatement);
  425. { a constructor needs call destructor (if available) when it
  426. is not inherited }
  427. if assigned(current_procinfo.procdef._class) and
  428. (current_procinfo.procdef.proctypeoption=potype_constructor) then
  429. begin
  430. { Don't test self and the vmt here. See generate_bodyexit_block }
  431. { why (JM) }
  432. oldlocalswitches:=current_settings.localswitches;
  433. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  434. pd:=current_procinfo.procdef._class.Finddestructor;
  435. if assigned(pd) then
  436. begin
  437. { if vmt<>0 then call destructor }
  438. addstatement(newstatement,cifnode.create(
  439. caddnode.create(unequaln,
  440. load_vmt_pointer_node,
  441. cnilnode.create),
  442. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[]),
  443. nil));
  444. end;
  445. current_settings.localswitches:=oldlocalswitches;
  446. end
  447. else
  448. begin
  449. { no constructor }
  450. { must be the return value finalized before reraising the exception? }
  451. if (not is_void(current_procinfo.procdef.returndef)) and
  452. (current_procinfo.procdef.returndef.needs_inittable) and
  453. (not is_class(current_procinfo.procdef.returndef)) then
  454. addstatement(newstatement,finalize_data_node(load_result_node));
  455. end;
  456. end;
  457. {****************************************************************************
  458. TCGProcInfo
  459. ****************************************************************************}
  460. constructor tcgprocinfo.create(aparent:tprocinfo);
  461. begin
  462. inherited Create(aparent);
  463. nestedprocs:=tlinkedlist.create;
  464. end;
  465. destructor tcgprocinfo.destroy;
  466. begin
  467. nestedprocs.free;
  468. if assigned(code) then
  469. code.free;
  470. inherited destroy;
  471. end;
  472. procedure tcgprocinfo.printproc;
  473. begin
  474. assign(printnodefile,treelogfilename);
  475. {$I-}
  476. append(printnodefile);
  477. if ioresult<>0 then
  478. rewrite(printnodefile);
  479. {$I+}
  480. if ioresult<>0 then
  481. begin
  482. Comment(V_Error,'Error creating '+treelogfilename);
  483. exit;
  484. end;
  485. writeln(printnodefile);
  486. writeln(printnodefile,'*******************************************************************************');
  487. writeln(printnodefile,procdef.fullprocname(false));
  488. writeln(printnodefile,'*******************************************************************************');
  489. printnode(printnodefile,code);
  490. close(printnodefile);
  491. end;
  492. procedure tcgprocinfo.add_entry_exit_code;
  493. var
  494. finalcode,
  495. bodyentrycode,
  496. bodyexitcode,
  497. exceptcode : tnode;
  498. newblock : tblocknode;
  499. codestatement,
  500. newstatement : tstatementnode;
  501. oldfilepos : tfileposinfo;
  502. begin
  503. oldfilepos:=current_filepos;
  504. { Generate code/locations used at start of proc }
  505. current_filepos:=entrypos;
  506. entry_asmnode:=casmnode.create_get_position;
  507. loadpara_asmnode:=casmnode.create_get_position;
  508. stackcheck_asmnode:=casmnode.create_get_position;
  509. init_asmnode:=casmnode.create_get_position;
  510. bodyentrycode:=generate_bodyentry_block;
  511. { Generate code/locations used at end of proc }
  512. current_filepos:=exitpos;
  513. exitlabel_asmnode:=casmnode.create_get_position;
  514. final_asmnode:=casmnode.create_get_position;
  515. bodyexitcode:=generate_bodyexit_block;
  516. { Generate procedure by combining init+body+final,
  517. depending on the implicit finally we need to add
  518. an try...finally...end wrapper }
  519. newblock:=internalstatements(newstatement);
  520. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  521. (pi_needs_implicit_finally in flags) and
  522. { but it's useless in init/final code of units }
  523. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) then
  524. begin
  525. { Generate special exception block only needed when
  526. implicit finaly is used }
  527. current_filepos:=exitpos;
  528. exceptcode:=generate_except_block;
  529. { Generate code that will be in the try...finally }
  530. finalcode:=internalstatements(codestatement);
  531. addstatement(codestatement,bodyexitcode);
  532. addstatement(codestatement,final_asmnode);
  533. { Initialize before try...finally...end frame }
  534. addstatement(newstatement,loadpara_asmnode);
  535. addstatement(newstatement,stackcheck_asmnode);
  536. addstatement(newstatement,entry_asmnode);
  537. addstatement(newstatement,init_asmnode);
  538. addstatement(newstatement,bodyentrycode);
  539. current_filepos:=entrypos;
  540. addstatement(newstatement,ctryfinallynode.create_implicit(
  541. code,
  542. finalcode,
  543. exceptcode));
  544. addstatement(newstatement,exitlabel_asmnode);
  545. { set flag the implicit finally has been generated }
  546. include(flags,pi_has_implicit_finally);
  547. end
  548. else
  549. begin
  550. addstatement(newstatement,loadpara_asmnode);
  551. addstatement(newstatement,stackcheck_asmnode);
  552. addstatement(newstatement,entry_asmnode);
  553. addstatement(newstatement,init_asmnode);
  554. addstatement(newstatement,bodyentrycode);
  555. addstatement(newstatement,code);
  556. addstatement(newstatement,exitlabel_asmnode);
  557. addstatement(newstatement,bodyexitcode);
  558. addstatement(newstatement,final_asmnode);
  559. end;
  560. do_firstpass(newblock);
  561. code:=newblock;
  562. current_filepos:=oldfilepos;
  563. end;
  564. procedure clearrefs(p:TObject;arg:pointer);
  565. begin
  566. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  567. if tabstractvarsym(p).refs>1 then
  568. tabstractvarsym(p).refs:=1;
  569. end;
  570. procedure translate_registers(p:TObject;list:pointer);
  571. begin
  572. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  573. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  574. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  575. begin
  576. if not(cs_no_regalloc in current_settings.globalswitches) then
  577. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  578. if cs_asm_source in current_settings.globalswitches then
  579. TAsmList(list).concat(Tai_comment.Create(strpnew('Var '+tabstractnormalvarsym(p).realname+' located in register '+
  580. std_regname(tabstractnormalvarsym(p).localloc.register))))
  581. end;
  582. end;
  583. procedure check_for_stack(p:TObject;arg:pointer);
  584. begin
  585. if tsym(p).typ=paravarsym then
  586. begin
  587. { check if there no parameter of the current procedure is stack dependend }
  588. if is_open_array(tparavarsym(p).vardef) or
  589. is_array_of_const(tparavarsym(p).vardef) then
  590. pboolean(arg)^:=true;
  591. if assigned(p) and
  592. assigned(tparavarsym(p).paraloc[calleeside].location) and
  593. (tparavarsym(p).paraloc[calleeside].location^.loc=LOC_REFERENCE) then
  594. pboolean(arg)^:=true;
  595. end;
  596. end;
  597. function tcgprocinfo.stack_tainting_parameter : boolean;
  598. begin
  599. result:=false;
  600. procdef.parast.SymList.ForEachCall(@check_for_stack,@result);
  601. end;
  602. function tcgprocinfo.has_assembler_child : boolean;
  603. var
  604. hp : tcgprocinfo;
  605. begin
  606. result:=false;
  607. hp:=tcgprocinfo(nestedprocs.first);
  608. while assigned(hp) do
  609. begin
  610. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  611. begin
  612. result:=true;
  613. exit;
  614. end;
  615. hp:=tcgprocinfo(hp.next);
  616. end;
  617. end;
  618. procedure tcgprocinfo.generate_code;
  619. var
  620. oldprocinfo : tprocinfo;
  621. oldmaxfpuregisters : longint;
  622. oldfilepos : tfileposinfo;
  623. templist : TAsmList;
  624. headertai : tai;
  625. begin
  626. { the initialization procedure can be empty, then we
  627. don't need to generate anything. When it was an empty
  628. procedure there would be at least a blocknode }
  629. if not assigned(code) then
  630. exit;
  631. { We need valid code }
  632. if Errorcount<>0 then
  633. exit;
  634. { No code can be generated for generic template }
  635. if (df_generic in procdef.defoptions) then
  636. internalerror(200511152);
  637. { The RA and Tempgen shall not be available yet }
  638. if assigned(tg) then
  639. internalerror(200309201);
  640. oldprocinfo:=current_procinfo;
  641. oldfilepos:=current_filepos;
  642. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  643. current_procinfo:=self;
  644. current_filepos:=entrypos;
  645. templist:=TAsmList.create;
  646. { add parast/localst to symtablestack }
  647. add_to_symtablestack;
  648. { when size optimization only count occurrence }
  649. if cs_opt_size in current_settings.optimizerswitches then
  650. cg.t_times:=1
  651. else
  652. { reference for repetition is 100 }
  653. cg.t_times:=100;
  654. { clear register count }
  655. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  656. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  657. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  658. if (procdef.localst.symtablelevel=main_program_level) and
  659. (not current_module.is_unit) then
  660. include(flags,pi_do_call);
  661. { set implicit_finally flag when there are locals/paras to be finalized }
  662. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  663. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  664. { firstpass everything }
  665. flowcontrol:=[];
  666. do_firstpass(code);
  667. if code.registersfpu>0 then
  668. include(flags,pi_uses_fpu);
  669. { do this before adding the entry code else the tail recursion recognition won't work,
  670. if this causes troubles, it must be if'ed
  671. }
  672. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  673. (pi_is_recursive in flags) then
  674. do_opttail(code,procdef);
  675. { add implicit entry and exit code }
  676. add_entry_exit_code;
  677. { only do secondpass if there are no errors }
  678. if (ErrorCount=0) then
  679. begin
  680. { set the start offset to the start of the temp area in the stack }
  681. tg:=ttgobj.create;
  682. {$if defined(x86) or defined(arm)}
  683. { try to strip the stack frame }
  684. { set the framepointer to esp if:
  685. - no assembler directive, those are handled elsewhere
  686. (for cases not caught by the Delphi exception below)
  687. - no exceptions are used
  688. - no debug info
  689. - no pushes are used/esp modifications, could be:
  690. * outgoing parameters on the stack
  691. * incoming parameters on the stack
  692. * open arrays
  693. - no inline assembler
  694. or
  695. - Delphi mode
  696. - assembler directive
  697. - no pushes are used/esp modifications, could be:
  698. * outgoing parameters on the stack
  699. * incoming parameters on the stack
  700. * open arrays
  701. - no local variables
  702. }
  703. if ((po_assembler in procdef.procoptions) and
  704. (m_delphi in current_settings.modeswitches) and
  705. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  706. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  707. not(po_assembler in procdef.procoptions) and
  708. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  709. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  710. pi_needs_stackframe])=[])
  711. {$ifdef arm}
  712. and ((cs_fp_emulation in current_settings.moduleswitches) or not (pi_uses_fpu in flags))
  713. {$endif arm}
  714. )
  715. then
  716. begin
  717. { we need the parameter info here to determine if the procedure gets
  718. parameters on the stack
  719. calling generate_parameter_info doesn't hurt but it costs time
  720. }
  721. generate_parameter_info;
  722. if not(stack_tainting_parameter) and
  723. not(has_assembler_child) and (para_stack_size=0) then
  724. begin
  725. { Only need to set the framepointer }
  726. framepointer:=NR_STACK_POINTER_REG;
  727. tg.direction:=1;
  728. end;
  729. end;
  730. {$endif}
  731. { Create register allocator }
  732. cg.init_register_allocators;
  733. set_first_temp_offset;
  734. generate_parameter_info;
  735. { Allocate space in temp/registers for parast and localst }
  736. current_filepos:=entrypos;
  737. gen_alloc_symtable(aktproccode,procdef.parast);
  738. gen_alloc_symtable(aktproccode,procdef.localst);
  739. { Store temp offset for information about 'real' temps }
  740. tempstart:=tg.lasttemp;
  741. { Generate code to load register parameters in temps and insert local
  742. copies for values parameters. This must be done before the code for the
  743. body is generated because the localloc is updated.
  744. Note: The generated code will be inserted after the code generation of
  745. the body is finished, because only then the position is known }
  746. {$ifdef oldregvars}
  747. assign_regvars(code);
  748. {$endif oldreg}
  749. current_filepos:=entrypos;
  750. { record which registers are allocated here, since all code }
  751. { allocating registers comes after it }
  752. cg.set_regalloc_extend_backwards(true);
  753. gen_load_para_value(templist);
  754. cg.set_regalloc_extend_backwards(false);
  755. { caller paraloc info is also necessary in the stackframe_entry
  756. code of the ppc (and possibly other processors) }
  757. if not procdef.has_paraloc_info then
  758. begin
  759. procdef.requiredargarea:=paramanager.create_paraloc_info(procdef,callerside);
  760. procdef.has_paraloc_info:=true;
  761. end;
  762. { generate code for the node tree }
  763. do_secondpass(code);
  764. aktproccode.concatlist(current_asmdata.CurrAsmList);
  765. {$ifdef i386}
  766. procdef.fpu_used:=code.registersfpu;
  767. {$endif i386}
  768. { The position of the loadpara_asmnode is now known }
  769. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  770. { first generate entry and initialize code with the correct
  771. position and switches }
  772. current_filepos:=entrypos;
  773. current_settings.localswitches:=entryswitches;
  774. cg.set_regalloc_extend_backwards(true);
  775. gen_entry_code(templist);
  776. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  777. gen_initialize_code(templist);
  778. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  779. { now generate finalize and exit code with the correct position
  780. and switches }
  781. current_filepos:=exitpos;
  782. current_settings.localswitches:=exitswitches;
  783. cg.set_regalloc_extend_backwards(false);
  784. gen_finalize_code(templist);
  785. { the finalcode must be concated if there was no position available,
  786. using insertlistafter will result in an insert at the start
  787. when currentai=nil }
  788. if assigned(final_asmnode.currenttai) then
  789. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  790. else
  791. aktproccode.concatlist(templist);
  792. { insert exit label at the correct position }
  793. cg.a_label(templist,CurrExitLabel);
  794. if assigned(exitlabel_asmnode.currenttai) then
  795. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  796. else
  797. aktproccode.concatlist(templist);
  798. { exit code }
  799. gen_exit_code(templist);
  800. aktproccode.concatlist(templist);
  801. {$ifdef OLDREGVARS}
  802. { note: this must be done only after as much code as possible has }
  803. { been generated. The result is that when you ungetregister() a }
  804. { regvar, it will actually free the regvar (and alse free the }
  805. { the regvars at the same time). Doing this too early will }
  806. { confuse the register allocator, as the regvars will still be }
  807. { used. It should be done before loading the result regs (so }
  808. { they don't conflict with the regvars) and before }
  809. { gen_entry_code (that one has to be able to allocate the }
  810. { regvars again) (JM) }
  811. free_regvars(aktproccode);
  812. {$endif OLDREGVARS}
  813. { generate symbol and save end of header position }
  814. current_filepos:=entrypos;
  815. gen_proc_symbol(templist);
  816. headertai:=tai(templist.last);
  817. { insert symbol }
  818. aktproccode.insertlist(templist);
  819. { Free space in temp/registers for parast and localst, must be
  820. done after gen_entry_code }
  821. current_filepos:=exitpos;
  822. gen_free_symtable(aktproccode,procdef.localst);
  823. gen_free_symtable(aktproccode,procdef.parast);
  824. { add code that will load the return value, this is not done
  825. for assembler routines when they didn't reference the result
  826. variable }
  827. gen_load_return_value(templist);
  828. aktproccode.concatlist(templist);
  829. { Already reserve all registers for stack checking code and
  830. generate the call to the helper function }
  831. if (cs_check_stack in entryswitches) and
  832. not(po_assembler in procdef.procoptions) and
  833. (procdef.proctypeoption<>potype_proginit) then
  834. begin
  835. current_filepos:=entrypos;
  836. gen_stack_check_call(templist);
  837. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  838. end;
  839. { load got if necessary }
  840. cg.set_regalloc_extend_backwards(true);
  841. current_filepos:=entrypos;
  842. gen_got_load(templist);
  843. aktproccode.insertlistafter(headertai,templist);
  844. cg.set_regalloc_extend_backwards(false);
  845. { The procedure body is finished, we can now
  846. allocate the registers }
  847. cg.do_register_allocation(aktproccode,headertai);
  848. { translate imag. register to their real counter parts
  849. this is necessary for debuginfo and verbose assembler output
  850. when SSA will be implented, this will be more complicated because we've to
  851. maintain location lists }
  852. current_procinfo.procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  853. current_procinfo.procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  854. { Add save and restore of used registers }
  855. current_filepos:=entrypos;
  856. gen_save_used_regs(templist);
  857. aktproccode.insertlistafter(headertai,templist);
  858. current_filepos:=exitpos;
  859. gen_restore_used_regs(aktproccode);
  860. { We know the size of the stack, now we can generate the
  861. parameter that is passed to the stack checking code }
  862. if (cs_check_stack in entryswitches) and
  863. not(po_assembler in procdef.procoptions) and
  864. (procdef.proctypeoption<>potype_proginit) then
  865. begin
  866. current_filepos:=entrypos;
  867. gen_stack_check_size_para(templist);
  868. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  869. end;
  870. { Add entry code (stack allocation) after header }
  871. current_filepos:=entrypos;
  872. gen_proc_entry_code(templist);
  873. aktproccode.insertlistafter(headertai,templist);
  874. { Add exit code at the end }
  875. current_filepos:=exitpos;
  876. gen_proc_exit_code(templist);
  877. aktproccode.concatlist(templist);
  878. { check if the implicit finally has been generated. The flag
  879. should already be set in pass1 }
  880. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  881. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  882. (pi_needs_implicit_finally in flags) and
  883. not(pi_has_implicit_finally in flags) then
  884. internalerror(200405231);
  885. {$ifndef NoOpt}
  886. if not(cs_no_regalloc in current_settings.globalswitches) then
  887. begin
  888. if (cs_opt_level1 in current_settings.optimizerswitches) and
  889. { do not optimize pure assembler procedures }
  890. not(pi_is_assembler in flags) then
  891. optimize(aktproccode);
  892. end;
  893. {$endif NoOpt}
  894. {$ifdef ARM}
  895. { because of the limited constant size of the arm, all data access is done pc relative }
  896. insertpcrelativedata(aktproccode,aktlocaldata);
  897. {$endif ARM}
  898. { Add end symbol and debug info }
  899. { this must be done after the pcrelativedata is appended else the distance calculation of
  900. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  901. so it should be inserted before the end symbol (FK)
  902. }
  903. current_filepos:=exitpos;
  904. gen_proc_symbol_end(templist);
  905. aktproccode.concatlist(templist);
  906. {$ifdef POWERPC}
  907. fixup_jmps(aktproccode);
  908. {$endif POWERPC}
  909. {$ifdef POWERPC64}
  910. fixup_jmps(aktproccode);
  911. {$endif POWERPC64}
  912. { insert line debuginfo }
  913. if (cs_debuginfo in current_settings.moduleswitches) or
  914. (cs_use_lineinfo in current_settings.globalswitches) then
  915. debuginfo.insertlineinfo(aktproccode);
  916. { add the procedure to the al_procedures }
  917. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  918. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  919. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  920. { save local data (casetable) also in the same file }
  921. if assigned(aktlocaldata) and
  922. (not aktlocaldata.empty) then
  923. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  924. { only now we can remove the temps }
  925. tg.resettempgen;
  926. { stop tempgen and ra }
  927. tg.free;
  928. cg.done_register_allocators;
  929. tg:=nil;
  930. end;
  931. { restore symtablestack }
  932. remove_from_symtablestack;
  933. { restore }
  934. templist.free;
  935. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  936. current_filepos:=oldfilepos;
  937. current_procinfo:=oldprocinfo;
  938. end;
  939. procedure tcgprocinfo.add_to_symtablestack;
  940. var
  941. _class,hp : tobjectdef;
  942. begin
  943. { insert symtables for the class, but only if it is no nested function }
  944. if assigned(procdef._class) and
  945. not(assigned(parent) and
  946. assigned(parent.procdef) and
  947. assigned(parent.procdef._class)) then
  948. begin
  949. { insert them in the reverse order }
  950. hp:=nil;
  951. repeat
  952. _class:=procdef._class;
  953. while _class.childof<>hp do
  954. _class:=_class.childof;
  955. hp:=_class;
  956. symtablestack.push(_class.symtable);
  957. until hp=procdef._class;
  958. end;
  959. { insert parasymtable in symtablestack when parsing
  960. a function }
  961. if procdef.parast.symtablelevel>=normal_function_level then
  962. symtablestack.push(procdef.parast);
  963. { insert localsymtable }
  964. symtablestack.push(procdef.localst);
  965. end;
  966. procedure tcgprocinfo.remove_from_symtablestack;
  967. var
  968. _class : tobjectdef;
  969. begin
  970. { remove localsymtable }
  971. symtablestack.pop(procdef.localst);
  972. { remove parasymtable }
  973. if procdef.parast.symtablelevel>=normal_function_level then
  974. symtablestack.pop(procdef.parast);
  975. { remove symtables for the class, but only if it is no nested function }
  976. if assigned(procdef._class) and
  977. not(assigned(parent) and
  978. assigned(parent.procdef) and
  979. assigned(parent.procdef._class)) then
  980. begin
  981. _class:=procdef._class;
  982. while assigned(_class) do
  983. begin
  984. symtablestack.pop(_class.symtable);
  985. _class:=_class.childof;
  986. end;
  987. end;
  988. end;
  989. procedure tcgprocinfo.resetprocdef;
  990. begin
  991. { remove code tree, if not inline procedure }
  992. if assigned(code) then
  993. begin
  994. { the inline procedure has already got a copy of the tree
  995. stored in procdef.inlininginfo }
  996. code.free;
  997. code:=nil;
  998. end;
  999. end;
  1000. function checknodeinlining(procdef: tprocdef): boolean;
  1001. var
  1002. i : integer;
  1003. currpara : tparavarsym;
  1004. begin
  1005. result := false;
  1006. if (pi_has_assembler_block in current_procinfo.flags) then
  1007. exit;
  1008. for i:=0 to procdef.paras.count-1 do
  1009. begin
  1010. currpara:=tparavarsym(procdef.paras[i]);
  1011. { we can't handle formaldefs and special arrays (the latter may need a }
  1012. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  1013. { you have to add 1 to all index operations if you directly inline it }
  1014. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  1015. (currpara.vardef.typ=formaldef)) or
  1016. is_special_array(currpara.vardef) then
  1017. exit;
  1018. end;
  1019. result:=true;
  1020. end;
  1021. procedure tcgprocinfo.parse_body;
  1022. var
  1023. oldprocinfo : tprocinfo;
  1024. oldblock_type : tblock_type;
  1025. st : TSymtable;
  1026. begin
  1027. oldprocinfo:=current_procinfo;
  1028. oldblock_type:=block_type;
  1029. { reset break and continue labels }
  1030. block_type:=bt_body;
  1031. current_procinfo:=self;
  1032. { calculate the lexical level }
  1033. if procdef.parast.symtablelevel>maxnesting then
  1034. Message(parser_e_too_much_lexlevel);
  1035. { static is also important for local procedures !! }
  1036. if (po_staticmethod in procdef.procoptions) then
  1037. allow_only_static:=true
  1038. else if (procdef.parast.symtablelevel=normal_function_level) then
  1039. allow_only_static:=false;
  1040. {$ifdef state_tracking}
  1041. { aktstate:=Tstate_storage.create;}
  1042. {$endif state_tracking}
  1043. { allocate the symbol for this procedure }
  1044. alloc_proc_symbol(procdef);
  1045. { add parast/localst to symtablestack }
  1046. add_to_symtablestack;
  1047. { save entry info }
  1048. entrypos:=current_filepos;
  1049. entryswitches:=current_settings.localswitches;
  1050. if (df_generic in procdef.defoptions) then
  1051. begin
  1052. { start token recorder for generic template }
  1053. procdef.initgeneric;
  1054. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1055. end;
  1056. { parse the code ... }
  1057. code:=block(current_module.islibrary);
  1058. if (df_generic in procdef.defoptions) then
  1059. begin
  1060. { stop token recorder for generic template }
  1061. current_scanner.stoprecordtokens;
  1062. { Give a warning for accesses in the static symtable that aren't visible
  1063. outside the current unit }
  1064. st:=procdef.owner;
  1065. while (st.symtabletype=ObjectSymtable) do
  1066. st:=st.defowner.owner;
  1067. if (pi_uses_static_symtable in flags) and
  1068. (st.symtabletype<>staticsymtable) then
  1069. Comment(V_Warning,'Global Generic template references static symtable');
  1070. end;
  1071. { save exit info }
  1072. exitswitches:=current_settings.localswitches;
  1073. exitpos:=last_endtoken_filepos;
  1074. { the procedure is now defined }
  1075. procdef.forwarddef:=false;
  1076. if assigned(code) then
  1077. begin
  1078. { get a better entry point }
  1079. entrypos:=code.fileinfo;
  1080. { Finish type checking pass }
  1081. do_typecheckpass(code);
  1082. end;
  1083. { Check for unused labels, forwards, symbols for procedures. Static
  1084. symtable is checked in pmodules.
  1085. The check must be done after the typecheckpass }
  1086. if (Errorcount=0) and
  1087. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1088. begin
  1089. { check if forwards are resolved }
  1090. tstoredsymtable(procdef.localst).check_forwards;
  1091. { check if all labels are used }
  1092. tstoredsymtable(procdef.localst).checklabels;
  1093. { remove cross unit overloads }
  1094. tstoredsymtable(procdef.localst).unchain_overloaded;
  1095. { check for unused symbols, but only if there is no asm block }
  1096. if not(pi_has_assembler_block in flags) then
  1097. begin
  1098. tstoredsymtable(procdef.localst).allsymbolsused;
  1099. tstoredsymtable(procdef.parast).allsymbolsused;
  1100. end;
  1101. end;
  1102. if (po_inline in procdef.procoptions) then
  1103. begin
  1104. { Can we inline this procedure? }
  1105. if checknodeinlining(procdef) then
  1106. begin
  1107. new(procdef.inlininginfo);
  1108. include(procdef.procoptions,po_has_inlininginfo);
  1109. procdef.inlininginfo^.code:=code.getcopy;
  1110. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1111. { The blocknode needs to set an exit label }
  1112. if procdef.inlininginfo^.code.nodetype=blockn then
  1113. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1114. end;
  1115. end;
  1116. { Print the node to tree.log }
  1117. if paraprintnodetree=1 then
  1118. printproc;
  1119. { ... remove symbol tables }
  1120. remove_from_symtablestack;
  1121. {$ifdef state_tracking}
  1122. { aktstate.destroy;}
  1123. {$endif state_tracking}
  1124. { reset to normal non static function }
  1125. if (procdef.parast.symtablelevel=normal_function_level) then
  1126. allow_only_static:=false;
  1127. current_procinfo:=oldprocinfo;
  1128. { Restore old state }
  1129. block_type:=oldblock_type;
  1130. end;
  1131. {****************************************************************************
  1132. PROCEDURE/FUNCTION PARSING
  1133. ****************************************************************************}
  1134. procedure check_init_paras(p:TObject;arg:pointer);
  1135. begin
  1136. if tsym(p).typ<>paravarsym then
  1137. exit;
  1138. with tparavarsym(p) do
  1139. if (not is_class(vardef) and
  1140. vardef.needs_inittable and
  1141. (varspez in [vs_value,vs_out])) then
  1142. include(current_procinfo.flags,pi_do_call);
  1143. end;
  1144. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1145. {
  1146. Parses the procedure directives, then parses the procedure body, then
  1147. generates the code for it
  1148. }
  1149. procedure do_generate_code(pi:tcgprocinfo);
  1150. var
  1151. hpi : tcgprocinfo;
  1152. begin
  1153. { generate code for this procedure }
  1154. pi.generate_code;
  1155. { process nested procs }
  1156. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1157. while assigned(hpi) do
  1158. begin
  1159. do_generate_code(hpi);
  1160. hpi:=tcgprocinfo(hpi.next);
  1161. end;
  1162. pi.resetprocdef;
  1163. end;
  1164. var
  1165. oldfailtokenmode : tmodeswitch;
  1166. isnestedproc : boolean;
  1167. begin
  1168. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1169. { create a new procedure }
  1170. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1171. current_module.procinfo:=current_procinfo;
  1172. current_procinfo.procdef:=pd;
  1173. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1174. { Insert mangledname }
  1175. pd.aliasnames.insert(pd.mangledname);
  1176. { Handle Export of this procedure }
  1177. if (po_exports in pd.procoptions) and
  1178. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1179. begin
  1180. pd.aliasnames.insert(pd.procsym.realname);
  1181. if cs_link_deffile in current_settings.globalswitches then
  1182. deffile.AddExport(pd.mangledname);
  1183. end;
  1184. { Insert result variables in the localst }
  1185. insert_funcret_local(pd);
  1186. { check if there are para's which require initing -> set }
  1187. { pi_do_call (if not yet set) }
  1188. if not(pi_do_call in current_procinfo.flags) then
  1189. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1190. { set _FAIL as keyword if constructor }
  1191. if (pd.proctypeoption=potype_constructor) then
  1192. begin
  1193. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1194. tokeninfo^[_FAIL].keyword:=m_all;
  1195. end;
  1196. tcgprocinfo(current_procinfo).parse_body;
  1197. { When it's a nested procedure then defer the code generation,
  1198. when back at normal function level then generate the code
  1199. for all defered nested procedures and the current procedure }
  1200. if isnestedproc then
  1201. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1202. else
  1203. begin
  1204. { We can't support inlining for procedures that have nested
  1205. procedures because the nested procedures use a fixed offset
  1206. for accessing locals in the parent procedure (PFV) }
  1207. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1208. begin
  1209. if (df_generic in current_procinfo.procdef.defoptions) then
  1210. {$warning TODO Add error message for nested procs in generics}
  1211. internalerror(200511151)
  1212. else if (po_inline in current_procinfo.procdef.procoptions) then
  1213. begin
  1214. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1215. Message(parser_w_inlining_disabled);
  1216. current_procinfo.procdef.proccalloption:=pocall_default;
  1217. end;
  1218. end;
  1219. if not(df_generic in current_procinfo.procdef.defoptions) then
  1220. do_generate_code(tcgprocinfo(current_procinfo));
  1221. end;
  1222. { reset _FAIL as _SELF normal }
  1223. if (pd.proctypeoption=potype_constructor) then
  1224. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1225. { release procinfo }
  1226. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1227. internalerror(200304274);
  1228. current_module.procinfo:=current_procinfo.parent;
  1229. { For specialization we didn't record the last semicolon. Moving this parsing
  1230. into the parse_body routine is not done because of having better file position
  1231. information available }
  1232. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1233. consume(_SEMICOLON);
  1234. if not isnestedproc then
  1235. { current_procinfo is checked for nil later on }
  1236. freeandnil(current_procinfo);
  1237. end;
  1238. procedure read_proc;
  1239. {
  1240. Parses the procedure directives, then parses the procedure body, then
  1241. generates the code for it
  1242. }
  1243. procedure do_generate_code(pi:tcgprocinfo);
  1244. var
  1245. hpi : tcgprocinfo;
  1246. begin
  1247. { generate code for this procedure }
  1248. pi.generate_code;
  1249. { process nested procs }
  1250. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1251. while assigned(hpi) do
  1252. begin
  1253. do_generate_code(hpi);
  1254. hpi:=tcgprocinfo(hpi.next);
  1255. end;
  1256. pi.resetprocdef;
  1257. end;
  1258. var
  1259. old_current_procinfo : tprocinfo;
  1260. pdflags : tpdflags;
  1261. pd,firstpd : tprocdef;
  1262. s : string;
  1263. begin
  1264. { save old state }
  1265. old_current_procinfo:=current_procinfo;
  1266. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1267. to an other procdef }
  1268. current_procinfo:=nil;
  1269. { parse procedure declaration }
  1270. if assigned(old_current_procinfo) and
  1271. assigned(old_current_procinfo.procdef) then
  1272. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1273. else
  1274. pd:=parse_proc_dec(nil);
  1275. { set the default function options }
  1276. if parse_only then
  1277. begin
  1278. pd.forwarddef:=true;
  1279. { set also the interface flag, for better error message when the
  1280. implementation doesn't much this header }
  1281. pd.interfacedef:=true;
  1282. include(pd.procoptions,po_global);
  1283. pdflags:=[pd_interface];
  1284. end
  1285. else
  1286. begin
  1287. pdflags:=[pd_body];
  1288. if (not current_module.in_interface) then
  1289. include(pdflags,pd_implemen);
  1290. if (not current_module.is_unit) or
  1291. maybe_smartlink_symbol or
  1292. {
  1293. taking addresses of static procedures goes wrong
  1294. if they aren't global when pic is used (FK)
  1295. }
  1296. (cs_create_pic in current_settings.moduleswitches) then
  1297. include(pd.procoptions,po_global);
  1298. pd.forwarddef:=false;
  1299. end;
  1300. { parse the directives that may follow }
  1301. parse_proc_directives(pd,pdflags);
  1302. { hint directives, these can be separated by semicolons here,
  1303. that needs to be handled here with a loop (PFV) }
  1304. while try_consume_hintdirective(pd.symoptions) do
  1305. Consume(_SEMICOLON);
  1306. { Set calling convention }
  1307. handle_calling_convention(pd);
  1308. { search for forward declarations }
  1309. if not proc_add_definition(pd) then
  1310. begin
  1311. { A method must be forward defined (in the object declaration) }
  1312. if assigned(pd._class) and
  1313. (not assigned(old_current_procinfo.procdef._class)) then
  1314. begin
  1315. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1316. tprocsym(pd.procsym).write_parameter_lists(pd);
  1317. end
  1318. else
  1319. begin
  1320. { Give a better error if there is a forward def in the interface and only
  1321. a single implementation }
  1322. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1323. if (not pd.forwarddef) and
  1324. (not pd.interfacedef) and
  1325. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1326. firstpd.forwarddef and
  1327. firstpd.interfacedef and
  1328. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1329. { don't give an error if it may be an overload }
  1330. not(m_fpc in current_settings.modeswitches) and
  1331. (not(po_overload in pd.procoptions) or
  1332. not(po_overload in firstpd.procoptions)) then
  1333. begin
  1334. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1335. tprocsym(pd.procsym).write_parameter_lists(pd);
  1336. end;
  1337. end;
  1338. end;
  1339. { Set mangled name }
  1340. proc_set_mangledname(pd);
  1341. { compile procedure when a body is needed }
  1342. if (pd_body in pdflags) then
  1343. begin
  1344. read_proc_body(old_current_procinfo,pd);
  1345. end
  1346. else
  1347. begin
  1348. { Handle imports }
  1349. if (po_external in pd.procoptions) then
  1350. begin
  1351. { External declared in implementation, and there was already a
  1352. forward (or interface) declaration then we need to generate
  1353. a stub that calls the external routine }
  1354. if (not pd.forwarddef) and
  1355. (pd.hasforward) and
  1356. not(
  1357. assigned(pd.import_dll) and
  1358. (target_info.system in [system_i386_wdosx,system_i386_emx,system_i386_os2,
  1359. system_arm_wince,system_i386_wince])
  1360. ) then
  1361. begin
  1362. s:=proc_get_importname(pd);
  1363. if s<>'' then
  1364. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1365. end;
  1366. { Import DLL specified? }
  1367. if assigned(pd.import_dll) then
  1368. current_module.AddExternalImport(pd.import_dll^,proc_get_importname(pd),pd.import_nr,false)
  1369. else
  1370. begin
  1371. { add import name to external list for DLL scanning }
  1372. if tf_has_dllscanner in target_info.flags then
  1373. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1374. end;
  1375. end;
  1376. end;
  1377. { make sure that references to forward-declared functions are not }
  1378. { treated as references to external symbols, needed for darwin. }
  1379. { make sure we don't change the binding of real external symbols }
  1380. if not(po_external in pd.procoptions) then
  1381. begin
  1382. if (po_global in pd.procoptions) or
  1383. (cs_profile in current_settings.moduleswitches) then
  1384. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1385. else
  1386. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1387. end;
  1388. current_procinfo:=old_current_procinfo;
  1389. end;
  1390. {****************************************************************************
  1391. DECLARATION PARSING
  1392. ****************************************************************************}
  1393. { search in symtablestack for not complete classes }
  1394. procedure check_forward_class(p:TObject;arg:pointer);
  1395. begin
  1396. if (tsym(p).typ=typesym) and
  1397. (ttypesym(p).typedef.typ=objectdef) and
  1398. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1399. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1400. end;
  1401. procedure read_declarations(islibrary : boolean);
  1402. begin
  1403. repeat
  1404. if not assigned(current_procinfo) then
  1405. internalerror(200304251);
  1406. case token of
  1407. _LABEL:
  1408. label_dec;
  1409. _CONST:
  1410. const_dec;
  1411. _TYPE:
  1412. type_dec;
  1413. _VAR:
  1414. var_dec;
  1415. _THREADVAR:
  1416. threadvar_dec;
  1417. _CONSTRUCTOR,
  1418. _DESTRUCTOR,
  1419. _FUNCTION,
  1420. _PROCEDURE,
  1421. _OPERATOR,
  1422. _CLASS:
  1423. read_proc;
  1424. _EXPORTS:
  1425. begin
  1426. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1427. begin
  1428. Message(parser_e_syntax_error);
  1429. consume_all_until(_SEMICOLON);
  1430. end
  1431. else if islibrary or
  1432. (target_info.system in system_unit_program_exports) then
  1433. read_exports
  1434. else
  1435. begin
  1436. Message(parser_w_unsupported_feature);
  1437. consume(_BEGIN);
  1438. end;
  1439. end
  1440. else
  1441. begin
  1442. case idtoken of
  1443. _RESOURCESTRING :
  1444. begin
  1445. { m_class is needed, because the resourcestring
  1446. loading is in the ObjPas unit }
  1447. { if (m_class in current_settings.modeswitches) then}
  1448. resourcestring_dec
  1449. { else
  1450. break;}
  1451. end;
  1452. _PROPERTY:
  1453. begin
  1454. if (m_fpc in current_settings.modeswitches) then
  1455. property_dec
  1456. else
  1457. break;
  1458. end;
  1459. else
  1460. break;
  1461. end;
  1462. end;
  1463. end;
  1464. until false;
  1465. { check for incomplete class definitions, this is only required
  1466. for fpc modes }
  1467. if (m_fpc in current_settings.modeswitches) then
  1468. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1469. end;
  1470. procedure read_interface_declarations;
  1471. begin
  1472. repeat
  1473. case token of
  1474. _CONST :
  1475. const_dec;
  1476. _TYPE :
  1477. type_dec;
  1478. _VAR :
  1479. var_dec;
  1480. _THREADVAR :
  1481. threadvar_dec;
  1482. _FUNCTION,
  1483. _PROCEDURE,
  1484. _OPERATOR :
  1485. read_proc;
  1486. else
  1487. begin
  1488. case idtoken of
  1489. _RESOURCESTRING :
  1490. resourcestring_dec;
  1491. _PROPERTY:
  1492. begin
  1493. if (m_fpc in current_settings.modeswitches) then
  1494. property_dec
  1495. else
  1496. break;
  1497. end;
  1498. else
  1499. break;
  1500. end;
  1501. end;
  1502. end;
  1503. until false;
  1504. { check for incomplete class definitions, this is only required
  1505. for fpc modes }
  1506. if (m_fpc in current_settings.modeswitches) then
  1507. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1508. end;
  1509. {****************************************************************************
  1510. SPECIALIZATION BODY GENERATION
  1511. ****************************************************************************}
  1512. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1513. var
  1514. i : longint;
  1515. hp : tdef;
  1516. oldcurrent_filepos : tfileposinfo;
  1517. begin
  1518. if not((tsym(p).typ=typesym) and
  1519. (ttypesym(p).typedef.typ=objectdef) and
  1520. (df_specialization in ttypesym(p).typedef.defoptions)
  1521. ) then
  1522. exit;
  1523. { definitions }
  1524. for i:=0 to tobjectdef(ttypesym(p).typedef).symtable.DefList.Count-1 do
  1525. begin
  1526. hp:=tdef(tobjectdef(ttypesym(p).typedef).symtable.DefList[i]);
  1527. if hp.typ=procdef then
  1528. begin
  1529. if assigned(tprocdef(hp).genericdef) and
  1530. (tprocdef(hp).genericdef.typ=procdef) and
  1531. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1532. begin
  1533. oldcurrent_filepos:=current_filepos;
  1534. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1535. current_tokenpos:=current_filepos;
  1536. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1537. read_proc_body(nil,tprocdef(hp));
  1538. current_filepos:=oldcurrent_filepos;
  1539. end
  1540. else
  1541. MessagePos1(tprocdef(tprocdef(hp).genericdef).fileinfo,sym_e_forward_not_resolved,tprocdef(tprocdef(hp).genericdef).fullprocname(false));
  1542. end;
  1543. end;
  1544. end;
  1545. procedure generate_specialization_procs;
  1546. begin
  1547. if assigned(current_module.globalsymtable) then
  1548. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1549. if assigned(current_module.localsymtable) then
  1550. begin
  1551. symtablestack.push(current_module.localsymtable);
  1552. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1553. symtablestack.pop(current_module.localsymtable);
  1554. end;
  1555. end;
  1556. end.