psub.pas 70 KB

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