psub.pas 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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,constexp,
  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. optbase,
  88. opttail,
  89. optcse,
  90. optdfa,
  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. { firstpass everything }
  674. flowcontrol:=[];
  675. do_firstpass(code);
  676. if code.registersfpu>0 then
  677. include(flags,pi_uses_fpu);
  678. { do this before adding the entry code else the tail recursion recognition won't work,
  679. if this causes troubles, it must be if'ed
  680. }
  681. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  682. (pi_is_recursive in flags) then
  683. do_opttail(code,procdef);
  684. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  685. { creating dfa is not always possible }
  686. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  687. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  688. pi_needs_stackframe])=[]) then
  689. begin
  690. createdfainfo(code);
  691. { when life info is available, we can give more sophisticated warning about unintialized
  692. variables }
  693. { iterate through life info of the first node }
  694. for i:=0 to nodemap.count-1 do
  695. begin
  696. if DFASetIn(code.optinfo^.life,i) then
  697. case tnode(nodemap[i]).nodetype of
  698. loadn:
  699. begin
  700. varsym:=tabstractnormalvarsym(tloadnode(nodemap[i]).symtableentry);
  701. { Give warning/note for living locals }
  702. if assigned(varsym.owner) and
  703. not(vo_is_external in varsym.varoptions) then
  704. begin
  705. if (vo_is_funcret in varsym.varoptions) then
  706. CGMessage(sym_w_function_result_uninitialized)
  707. else
  708. begin
  709. if varsym.owner=procdef.localst then
  710. CGMessage1(sym_w_uninitialized_local_variable,varsym.realname);
  711. end;
  712. end;
  713. end;
  714. end;
  715. end;
  716. end;
  717. if cs_opt_nodecse in current_settings.optimizerswitches then
  718. do_optcse(code);
  719. { add implicit entry and exit code }
  720. add_entry_exit_code;
  721. { only do secondpass if there are no errors }
  722. if (ErrorCount=0) then
  723. begin
  724. { set the start offset to the start of the temp area in the stack }
  725. tg:=ttgobj.create;
  726. {$if defined(x86) or defined(arm)}
  727. { try to strip the stack frame }
  728. { set the framepointer to esp if:
  729. - no assembler directive, those are handled in assembler_block
  730. in pstatment.pas (for cases not caught by the Delphi
  731. exception below)
  732. - no exceptions are used
  733. - no debug info
  734. - no pushes are used/esp modifications, could be:
  735. * outgoing parameters on the stack
  736. * incoming parameters on the stack
  737. * open arrays
  738. - no inline assembler
  739. or
  740. - Delphi mode
  741. - assembler directive
  742. - no pushes are used/esp modifications, could be:
  743. * outgoing parameters on the stack
  744. * incoming parameters on the stack
  745. * open arrays
  746. - no local variables
  747. }
  748. if ((po_assembler in procdef.procoptions) and
  749. (m_delphi in current_settings.modeswitches) and
  750. { localst at main_program_level is a staticsymtable }
  751. (procdef.localst.symtablelevel<>main_program_level) and
  752. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  753. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  754. not(cs_generate_stackframes in current_settings.localswitches) and
  755. not(po_assembler in procdef.procoptions) and
  756. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  757. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter,
  758. pi_needs_stackframe])=[])
  759. {$ifdef arm}
  760. and ((cs_fp_emulation in current_settings.moduleswitches) or not (pi_uses_fpu in flags))
  761. {$endif arm}
  762. )
  763. then
  764. begin
  765. { we need the parameter info here to determine if the procedure gets
  766. parameters on the stack
  767. calling generate_parameter_info doesn't hurt but it costs time
  768. }
  769. generate_parameter_info;
  770. if not(stack_tainting_parameter) and
  771. not(has_assembler_child) and (para_stack_size=0) then
  772. begin
  773. { Only need to set the framepointer }
  774. framepointer:=NR_STACK_POINTER_REG;
  775. tg.direction:=1;
  776. end;
  777. end;
  778. {$endif}
  779. { Create register allocator }
  780. cg.init_register_allocators;
  781. set_first_temp_offset;
  782. generate_parameter_info;
  783. { Allocate space in temp/registers for parast and localst }
  784. current_filepos:=entrypos;
  785. gen_alloc_symtable(aktproccode,procdef.parast);
  786. gen_alloc_symtable(aktproccode,procdef.localst);
  787. { Store temp offset for information about 'real' temps }
  788. tempstart:=tg.lasttemp;
  789. { Generate code to load register parameters in temps and insert local
  790. copies for values parameters. This must be done before the code for the
  791. body is generated because the localloc is updated.
  792. Note: The generated code will be inserted after the code generation of
  793. the body is finished, because only then the position is known }
  794. {$ifdef oldregvars}
  795. assign_regvars(code);
  796. {$endif oldreg}
  797. current_filepos:=entrypos;
  798. { record which registers are allocated here, since all code }
  799. { allocating registers comes after it }
  800. cg.set_regalloc_extend_backwards(true);
  801. gen_load_para_value(templist);
  802. cg.set_regalloc_extend_backwards(false);
  803. { caller paraloc info is also necessary in the stackframe_entry
  804. code of the ppc (and possibly other processors) }
  805. if not procdef.has_paraloc_info then
  806. begin
  807. procdef.requiredargarea:=paramanager.create_paraloc_info(procdef,callerside);
  808. procdef.has_paraloc_info:=true;
  809. end;
  810. { generate code for the node tree }
  811. do_secondpass(code);
  812. aktproccode.concatlist(current_asmdata.CurrAsmList);
  813. {$ifdef i386}
  814. procdef.fpu_used:=code.registersfpu;
  815. {$endif i386}
  816. { The position of the loadpara_asmnode is now known }
  817. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  818. { first generate entry and initialize code with the correct
  819. position and switches }
  820. current_filepos:=entrypos;
  821. current_settings.localswitches:=entryswitches;
  822. cg.set_regalloc_extend_backwards(true);
  823. gen_entry_code(templist);
  824. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  825. gen_initialize_code(templist);
  826. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  827. { now generate finalize and exit code with the correct position
  828. and switches }
  829. current_filepos:=exitpos;
  830. current_settings.localswitches:=exitswitches;
  831. cg.set_regalloc_extend_backwards(false);
  832. gen_finalize_code(templist);
  833. { the finalcode must be concated if there was no position available,
  834. using insertlistafter will result in an insert at the start
  835. when currentai=nil }
  836. if assigned(final_asmnode.currenttai) then
  837. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  838. else
  839. aktproccode.concatlist(templist);
  840. { insert exit label at the correct position }
  841. cg.a_label(templist,CurrExitLabel);
  842. if assigned(exitlabel_asmnode.currenttai) then
  843. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  844. else
  845. aktproccode.concatlist(templist);
  846. { exit code }
  847. gen_exit_code(templist);
  848. aktproccode.concatlist(templist);
  849. {$ifdef OLDREGVARS}
  850. { note: this must be done only after as much code as possible has }
  851. { been generated. The result is that when you ungetregister() a }
  852. { regvar, it will actually free the regvar (and alse free the }
  853. { the regvars at the same time). Doing this too early will }
  854. { confuse the register allocator, as the regvars will still be }
  855. { used. It should be done before loading the result regs (so }
  856. { they don't conflict with the regvars) and before }
  857. { gen_entry_code (that one has to be able to allocate the }
  858. { regvars again) (JM) }
  859. free_regvars(aktproccode);
  860. {$endif OLDREGVARS}
  861. { generate symbol and save end of header position }
  862. current_filepos:=entrypos;
  863. gen_proc_symbol(templist);
  864. headertai:=tai(templist.last);
  865. { insert symbol }
  866. aktproccode.insertlist(templist);
  867. { Free space in temp/registers for parast and localst, must be
  868. done after gen_entry_code }
  869. current_filepos:=exitpos;
  870. gen_free_symtable(aktproccode,procdef.localst);
  871. gen_free_symtable(aktproccode,procdef.parast);
  872. { add code that will load the return value, this is not done
  873. for assembler routines when they didn't reference the result
  874. variable }
  875. gen_load_return_value(templist);
  876. aktproccode.concatlist(templist);
  877. { Already reserve all registers for stack checking code and
  878. generate the call to the helper function }
  879. if (cs_check_stack in entryswitches) and
  880. not(po_assembler in procdef.procoptions) and
  881. (procdef.proctypeoption<>potype_proginit) then
  882. begin
  883. current_filepos:=entrypos;
  884. gen_stack_check_call(templist);
  885. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  886. end;
  887. { load got if necessary }
  888. cg.set_regalloc_extend_backwards(true);
  889. current_filepos:=entrypos;
  890. gen_got_load(templist);
  891. aktproccode.insertlistafter(headertai,templist);
  892. cg.set_regalloc_extend_backwards(false);
  893. { The procedure body is finished, we can now
  894. allocate the registers }
  895. cg.do_register_allocation(aktproccode,headertai);
  896. { translate imag. register to their real counter parts
  897. this is necessary for debuginfo and verbose assembler output
  898. when SSA will be implented, this will be more complicated because we've to
  899. maintain location lists }
  900. current_procinfo.procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  901. current_procinfo.procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  902. { Add save and restore of used registers }
  903. current_filepos:=entrypos;
  904. gen_save_used_regs(templist);
  905. aktproccode.insertlistafter(headertai,templist);
  906. current_filepos:=exitpos;
  907. gen_restore_used_regs(aktproccode);
  908. { We know the size of the stack, now we can generate the
  909. parameter that is passed to the stack checking code }
  910. if (cs_check_stack in entryswitches) and
  911. not(po_assembler in procdef.procoptions) and
  912. (procdef.proctypeoption<>potype_proginit) then
  913. begin
  914. current_filepos:=entrypos;
  915. gen_stack_check_size_para(templist);
  916. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  917. end;
  918. { Add entry code (stack allocation) after header }
  919. current_filepos:=entrypos;
  920. gen_proc_entry_code(templist);
  921. aktproccode.insertlistafter(headertai,templist);
  922. { Add exit code at the end }
  923. current_filepos:=exitpos;
  924. gen_proc_exit_code(templist);
  925. aktproccode.concatlist(templist);
  926. { check if the implicit finally has been generated. The flag
  927. should already be set in pass1 }
  928. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  929. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  930. (pi_needs_implicit_finally in flags) and
  931. not(pi_has_implicit_finally in flags) then
  932. internalerror(200405231);
  933. {$ifndef NoOpt}
  934. if not(cs_no_regalloc in current_settings.globalswitches) then
  935. begin
  936. if (cs_opt_level1 in current_settings.optimizerswitches) and
  937. { do not optimize pure assembler procedures }
  938. not(pi_is_assembler in flags) then
  939. optimize(aktproccode);
  940. end;
  941. {$endif NoOpt}
  942. {$ifdef ARM}
  943. { because of the limited constant size of the arm, all data access is done pc relative }
  944. insertpcrelativedata(aktproccode,aktlocaldata);
  945. {$endif ARM}
  946. { Add end symbol and debug info }
  947. { this must be done after the pcrelativedata is appended else the distance calculation of
  948. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  949. so it should be inserted before the end symbol (FK)
  950. }
  951. current_filepos:=exitpos;
  952. gen_proc_symbol_end(templist);
  953. aktproccode.concatlist(templist);
  954. {$if defined(POWERPC) or defined(POWERPC64)}
  955. fixup_jmps(aktproccode);
  956. {$endif}
  957. { insert line debuginfo }
  958. if (cs_debuginfo in current_settings.moduleswitches) or
  959. (cs_use_lineinfo in current_settings.globalswitches) then
  960. debuginfo.insertlineinfo(aktproccode);
  961. { add the procedure to the al_procedures }
  962. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  963. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  964. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  965. { save local data (casetable) also in the same file }
  966. if assigned(aktlocaldata) and
  967. (not aktlocaldata.empty) then
  968. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  969. { only now we can remove the temps }
  970. tg.resettempgen;
  971. { stop tempgen and ra }
  972. tg.free;
  973. cg.done_register_allocators;
  974. tg:=nil;
  975. end;
  976. { restore symtablestack }
  977. remove_from_symtablestack;
  978. { restore }
  979. templist.free;
  980. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  981. current_filepos:=oldfilepos;
  982. current_procinfo:=oldprocinfo;
  983. end;
  984. procedure tcgprocinfo.add_to_symtablestack;
  985. var
  986. _class,hp : tobjectdef;
  987. begin
  988. { insert symtables for the class, but only if it is no nested function }
  989. if assigned(procdef._class) and
  990. not(assigned(parent) and
  991. assigned(parent.procdef) and
  992. assigned(parent.procdef._class)) then
  993. begin
  994. { insert them in the reverse order }
  995. hp:=nil;
  996. repeat
  997. _class:=procdef._class;
  998. while _class.childof<>hp do
  999. _class:=_class.childof;
  1000. hp:=_class;
  1001. symtablestack.push(_class.symtable);
  1002. until hp=procdef._class;
  1003. end;
  1004. { insert parasymtable in symtablestack when parsing
  1005. a function }
  1006. if procdef.parast.symtablelevel>=normal_function_level then
  1007. symtablestack.push(procdef.parast);
  1008. { insert localsymtable }
  1009. symtablestack.push(procdef.localst);
  1010. end;
  1011. procedure tcgprocinfo.remove_from_symtablestack;
  1012. var
  1013. _class : tobjectdef;
  1014. begin
  1015. { remove localsymtable }
  1016. symtablestack.pop(procdef.localst);
  1017. { remove parasymtable }
  1018. if procdef.parast.symtablelevel>=normal_function_level then
  1019. symtablestack.pop(procdef.parast);
  1020. { remove symtables for the class, but only if it is no nested function }
  1021. if assigned(procdef._class) and
  1022. not(assigned(parent) and
  1023. assigned(parent.procdef) and
  1024. assigned(parent.procdef._class)) then
  1025. begin
  1026. _class:=procdef._class;
  1027. while assigned(_class) do
  1028. begin
  1029. symtablestack.pop(_class.symtable);
  1030. _class:=_class.childof;
  1031. end;
  1032. end;
  1033. end;
  1034. procedure tcgprocinfo.resetprocdef;
  1035. begin
  1036. { remove code tree, if not inline procedure }
  1037. if assigned(code) then
  1038. begin
  1039. { the inline procedure has already got a copy of the tree
  1040. stored in procdef.inlininginfo }
  1041. code.free;
  1042. code:=nil;
  1043. end;
  1044. end;
  1045. function checknodeinlining(procdef: tprocdef): boolean;
  1046. var
  1047. i : integer;
  1048. currpara : tparavarsym;
  1049. begin
  1050. result := false;
  1051. if (pi_has_assembler_block in current_procinfo.flags) then
  1052. exit;
  1053. for i:=0 to procdef.paras.count-1 do
  1054. begin
  1055. currpara:=tparavarsym(procdef.paras[i]);
  1056. { we can't handle formaldefs and special arrays (the latter may need a }
  1057. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  1058. { you have to add 1 to all index operations if you directly inline it }
  1059. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  1060. (currpara.vardef.typ=formaldef)) or
  1061. is_special_array(currpara.vardef) then
  1062. exit;
  1063. end;
  1064. result:=true;
  1065. end;
  1066. procedure tcgprocinfo.parse_body;
  1067. var
  1068. oldprocinfo : tprocinfo;
  1069. oldblock_type : tblock_type;
  1070. st : TSymtable;
  1071. begin
  1072. oldprocinfo:=current_procinfo;
  1073. oldblock_type:=block_type;
  1074. { reset break and continue labels }
  1075. block_type:=bt_body;
  1076. current_procinfo:=self;
  1077. { calculate the lexical level }
  1078. if procdef.parast.symtablelevel>maxnesting then
  1079. Message(parser_e_too_much_lexlevel);
  1080. {$ifdef state_tracking}
  1081. { aktstate:=Tstate_storage.create;}
  1082. {$endif state_tracking}
  1083. { allocate the symbol for this procedure }
  1084. alloc_proc_symbol(procdef);
  1085. { add parast/localst to symtablestack }
  1086. add_to_symtablestack;
  1087. { save entry info }
  1088. entrypos:=current_filepos;
  1089. entryswitches:=current_settings.localswitches;
  1090. if (df_generic in procdef.defoptions) then
  1091. begin
  1092. { start token recorder for generic template }
  1093. procdef.initgeneric;
  1094. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1095. end;
  1096. { parse the code ... }
  1097. code:=block(current_module.islibrary);
  1098. if (df_generic in procdef.defoptions) then
  1099. begin
  1100. { stop token recorder for generic template }
  1101. current_scanner.stoprecordtokens;
  1102. { Give a warning for accesses in the static symtable that aren't visible
  1103. outside the current unit }
  1104. st:=procdef.owner;
  1105. while (st.symtabletype=ObjectSymtable) do
  1106. st:=st.defowner.owner;
  1107. if (pi_uses_static_symtable in flags) and
  1108. (st.symtabletype<>staticsymtable) then
  1109. Comment(V_Warning,'Global Generic template references static symtable');
  1110. end;
  1111. { save exit info }
  1112. exitswitches:=current_settings.localswitches;
  1113. exitpos:=last_endtoken_filepos;
  1114. { the procedure is now defined }
  1115. procdef.forwarddef:=false;
  1116. if assigned(code) then
  1117. begin
  1118. { get a better entry point }
  1119. entrypos:=code.fileinfo;
  1120. { Finish type checking pass }
  1121. do_typecheckpass(code);
  1122. end;
  1123. { Check for unused labels, forwards, symbols for procedures. Static
  1124. symtable is checked in pmodules.
  1125. The check must be done after the typecheckpass }
  1126. if (Errorcount=0) and
  1127. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1128. begin
  1129. { check if forwards are resolved }
  1130. tstoredsymtable(procdef.localst).check_forwards;
  1131. { check if all labels are used }
  1132. tstoredsymtable(procdef.localst).checklabels;
  1133. { remove cross unit overloads }
  1134. tstoredsymtable(procdef.localst).unchain_overloaded;
  1135. { check for unused symbols, but only if there is no asm block }
  1136. if not(pi_has_assembler_block in flags) then
  1137. begin
  1138. tstoredsymtable(procdef.localst).allsymbolsused;
  1139. tstoredsymtable(procdef.parast).allsymbolsused;
  1140. end;
  1141. end;
  1142. if (po_inline in procdef.procoptions) then
  1143. begin
  1144. { Can we inline this procedure? }
  1145. if checknodeinlining(procdef) then
  1146. begin
  1147. new(procdef.inlininginfo);
  1148. include(procdef.procoptions,po_has_inlininginfo);
  1149. procdef.inlininginfo^.code:=code.getcopy;
  1150. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1151. { The blocknode needs to set an exit label }
  1152. if procdef.inlininginfo^.code.nodetype=blockn then
  1153. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1154. end;
  1155. end;
  1156. { Print the node to tree.log }
  1157. if paraprintnodetree=1 then
  1158. printproc;
  1159. { ... remove symbol tables }
  1160. remove_from_symtablestack;
  1161. {$ifdef state_tracking}
  1162. { aktstate.destroy;}
  1163. {$endif state_tracking}
  1164. current_procinfo:=oldprocinfo;
  1165. { Restore old state }
  1166. block_type:=oldblock_type;
  1167. end;
  1168. {****************************************************************************
  1169. PROCEDURE/FUNCTION PARSING
  1170. ****************************************************************************}
  1171. procedure check_init_paras(p:TObject;arg:pointer);
  1172. begin
  1173. if tsym(p).typ<>paravarsym then
  1174. exit;
  1175. with tparavarsym(p) do
  1176. if (not is_class(vardef) and
  1177. vardef.needs_inittable and
  1178. (varspez in [vs_value,vs_out])) then
  1179. include(current_procinfo.flags,pi_do_call);
  1180. end;
  1181. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1182. {
  1183. Parses the procedure directives, then parses the procedure body, then
  1184. generates the code for it
  1185. }
  1186. procedure do_generate_code(pi:tcgprocinfo);
  1187. var
  1188. hpi : tcgprocinfo;
  1189. begin
  1190. { generate code for this procedure }
  1191. pi.generate_code;
  1192. { process nested procs }
  1193. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1194. while assigned(hpi) do
  1195. begin
  1196. do_generate_code(hpi);
  1197. hpi:=tcgprocinfo(hpi.next);
  1198. end;
  1199. pi.resetprocdef;
  1200. end;
  1201. var
  1202. oldfailtokenmode : tmodeswitch;
  1203. isnestedproc : boolean;
  1204. begin
  1205. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1206. { create a new procedure }
  1207. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1208. current_module.procinfo:=current_procinfo;
  1209. current_procinfo.procdef:=pd;
  1210. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1211. { Insert mangledname }
  1212. pd.aliasnames.insert(pd.mangledname);
  1213. { Handle Export of this procedure }
  1214. if (po_exports in pd.procoptions) and
  1215. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1216. begin
  1217. pd.aliasnames.insert(pd.procsym.realname);
  1218. if cs_link_deffile in current_settings.globalswitches then
  1219. deffile.AddExport(pd.mangledname);
  1220. end;
  1221. { Insert result variables in the localst }
  1222. insert_funcret_local(pd);
  1223. { check if there are para's which require initing -> set }
  1224. { pi_do_call (if not yet set) }
  1225. if not(pi_do_call in current_procinfo.flags) then
  1226. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1227. { set _FAIL as keyword if constructor }
  1228. if (pd.proctypeoption=potype_constructor) then
  1229. begin
  1230. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1231. tokeninfo^[_FAIL].keyword:=m_all;
  1232. end;
  1233. tcgprocinfo(current_procinfo).parse_body;
  1234. { When it's a nested procedure then defer the code generation,
  1235. when back at normal function level then generate the code
  1236. for all defered nested procedures and the current procedure }
  1237. if isnestedproc then
  1238. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1239. else
  1240. begin
  1241. { We can't support inlining for procedures that have nested
  1242. procedures because the nested procedures use a fixed offset
  1243. for accessing locals in the parent procedure (PFV) }
  1244. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1245. begin
  1246. if (df_generic in current_procinfo.procdef.defoptions) then
  1247. Comment(V_Error,'Generic methods cannot have nested procedures')
  1248. else
  1249. if (po_inline in current_procinfo.procdef.procoptions) then
  1250. begin
  1251. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1252. Message(parser_w_inlining_disabled);
  1253. current_procinfo.procdef.proccalloption:=pocall_default;
  1254. end;
  1255. end;
  1256. if not(df_generic in current_procinfo.procdef.defoptions) then
  1257. do_generate_code(tcgprocinfo(current_procinfo));
  1258. end;
  1259. { reset _FAIL as _SELF normal }
  1260. if (pd.proctypeoption=potype_constructor) then
  1261. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1262. { release procinfo }
  1263. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1264. internalerror(200304274);
  1265. current_module.procinfo:=current_procinfo.parent;
  1266. { For specialization we didn't record the last semicolon. Moving this parsing
  1267. into the parse_body routine is not done because of having better file position
  1268. information available }
  1269. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1270. consume(_SEMICOLON);
  1271. if not isnestedproc then
  1272. { current_procinfo is checked for nil later on }
  1273. freeandnil(current_procinfo);
  1274. end;
  1275. procedure read_proc;
  1276. {
  1277. Parses the procedure directives, then parses the procedure body, then
  1278. generates the code for it
  1279. }
  1280. procedure do_generate_code(pi:tcgprocinfo);
  1281. var
  1282. hpi : tcgprocinfo;
  1283. begin
  1284. { generate code for this procedure }
  1285. pi.generate_code;
  1286. { process nested procs }
  1287. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1288. while assigned(hpi) do
  1289. begin
  1290. do_generate_code(hpi);
  1291. hpi:=tcgprocinfo(hpi.next);
  1292. end;
  1293. pi.resetprocdef;
  1294. end;
  1295. var
  1296. old_current_procinfo : tprocinfo;
  1297. pdflags : tpdflags;
  1298. pd,firstpd : tprocdef;
  1299. s : string;
  1300. begin
  1301. { save old state }
  1302. old_current_procinfo:=current_procinfo;
  1303. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1304. to an other procdef }
  1305. current_procinfo:=nil;
  1306. { parse procedure declaration }
  1307. if assigned(old_current_procinfo) and
  1308. assigned(old_current_procinfo.procdef) then
  1309. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1310. else
  1311. pd:=parse_proc_dec(nil);
  1312. { set the default function options }
  1313. if parse_only then
  1314. begin
  1315. pd.forwarddef:=true;
  1316. { set also the interface flag, for better error message when the
  1317. implementation doesn't much this header }
  1318. pd.interfacedef:=true;
  1319. include(pd.procoptions,po_global);
  1320. pdflags:=[pd_interface];
  1321. end
  1322. else
  1323. begin
  1324. pdflags:=[pd_body];
  1325. if (not current_module.in_interface) then
  1326. include(pdflags,pd_implemen);
  1327. if (not current_module.is_unit) or
  1328. maybe_smartlink_symbol or
  1329. {
  1330. taking addresses of static procedures goes wrong
  1331. if they aren't global when pic is used (FK)
  1332. }
  1333. (cs_create_pic in current_settings.moduleswitches) then
  1334. include(pd.procoptions,po_global);
  1335. pd.forwarddef:=false;
  1336. end;
  1337. { parse the directives that may follow }
  1338. parse_proc_directives(pd,pdflags);
  1339. { hint directives, these can be separated by semicolons here,
  1340. that needs to be handled here with a loop (PFV) }
  1341. while try_consume_hintdirective(pd.symoptions) do
  1342. Consume(_SEMICOLON);
  1343. { Set calling convention }
  1344. handle_calling_convention(pd);
  1345. { search for forward declarations }
  1346. if not proc_add_definition(pd) then
  1347. begin
  1348. { A method must be forward defined (in the object declaration) }
  1349. if assigned(pd._class) and
  1350. (not assigned(old_current_procinfo.procdef._class)) then
  1351. begin
  1352. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1353. tprocsym(pd.procsym).write_parameter_lists(pd);
  1354. end
  1355. else
  1356. begin
  1357. { Give a better error if there is a forward def in the interface and only
  1358. a single implementation }
  1359. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1360. if (not pd.forwarddef) and
  1361. (not pd.interfacedef) and
  1362. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1363. firstpd.forwarddef and
  1364. firstpd.interfacedef and
  1365. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1366. { don't give an error if it may be an overload }
  1367. not(m_fpc in current_settings.modeswitches) and
  1368. (not(po_overload in pd.procoptions) or
  1369. not(po_overload in firstpd.procoptions)) then
  1370. begin
  1371. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1372. tprocsym(pd.procsym).write_parameter_lists(pd);
  1373. end;
  1374. end;
  1375. end;
  1376. { Set mangled name }
  1377. proc_set_mangledname(pd);
  1378. { compile procedure when a body is needed }
  1379. if (pd_body in pdflags) then
  1380. begin
  1381. read_proc_body(old_current_procinfo,pd);
  1382. end
  1383. else
  1384. begin
  1385. { Handle imports }
  1386. if (po_external in pd.procoptions) then
  1387. begin
  1388. { External declared in implementation, and there was already a
  1389. forward (or interface) declaration then we need to generate
  1390. a stub that calls the external routine }
  1391. if (not pd.forwarddef) and
  1392. (pd.hasforward) and
  1393. not(
  1394. assigned(pd.import_dll) and
  1395. (target_info.system in [system_i386_wdosx,
  1396. system_arm_wince,system_i386_wince])
  1397. ) then
  1398. begin
  1399. s:=proc_get_importname(pd);
  1400. if s<>'' then
  1401. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1402. end;
  1403. { Import DLL specified? }
  1404. if assigned(pd.import_dll) then
  1405. current_module.AddExternalImport(pd.import_dll^,proc_get_importname(pd),pd.import_nr,false)
  1406. else
  1407. begin
  1408. { add import name to external list for DLL scanning }
  1409. if tf_has_dllscanner in target_info.flags then
  1410. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1411. end;
  1412. end;
  1413. end;
  1414. { make sure that references to forward-declared functions are not }
  1415. { treated as references to external symbols, needed for darwin. }
  1416. { make sure we don't change the binding of real external symbols }
  1417. if not(po_external in pd.procoptions) then
  1418. begin
  1419. if (po_global in pd.procoptions) or
  1420. (cs_profile in current_settings.moduleswitches) then
  1421. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1422. else
  1423. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1424. end;
  1425. current_procinfo:=old_current_procinfo;
  1426. end;
  1427. {****************************************************************************
  1428. DECLARATION PARSING
  1429. ****************************************************************************}
  1430. { search in symtablestack for not complete classes }
  1431. procedure check_forward_class(p:TObject;arg:pointer);
  1432. begin
  1433. if (tsym(p).typ=typesym) and
  1434. (ttypesym(p).typedef.typ=objectdef) and
  1435. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1436. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1437. end;
  1438. procedure read_declarations(islibrary : boolean);
  1439. begin
  1440. repeat
  1441. if not assigned(current_procinfo) then
  1442. internalerror(200304251);
  1443. case token of
  1444. _LABEL:
  1445. label_dec;
  1446. _CONST:
  1447. const_dec;
  1448. _TYPE:
  1449. type_dec;
  1450. _VAR:
  1451. var_dec;
  1452. _THREADVAR:
  1453. threadvar_dec;
  1454. _CONSTRUCTOR,
  1455. _DESTRUCTOR,
  1456. _FUNCTION,
  1457. _PROCEDURE,
  1458. _OPERATOR,
  1459. _CLASS:
  1460. read_proc;
  1461. _EXPORTS:
  1462. begin
  1463. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1464. begin
  1465. Message(parser_e_syntax_error);
  1466. consume_all_until(_SEMICOLON);
  1467. end
  1468. else if islibrary or
  1469. (target_info.system in system_unit_program_exports) then
  1470. read_exports
  1471. else
  1472. begin
  1473. Message(parser_w_unsupported_feature);
  1474. consume(_BEGIN);
  1475. end;
  1476. end
  1477. else
  1478. begin
  1479. case idtoken of
  1480. _RESOURCESTRING :
  1481. begin
  1482. { m_class is needed, because the resourcestring
  1483. loading is in the ObjPas unit }
  1484. { if (m_class in current_settings.modeswitches) then}
  1485. resourcestring_dec
  1486. { else
  1487. break;}
  1488. end;
  1489. _PROPERTY:
  1490. begin
  1491. if (m_fpc in current_settings.modeswitches) then
  1492. property_dec
  1493. else
  1494. break;
  1495. end;
  1496. else
  1497. break;
  1498. end;
  1499. end;
  1500. end;
  1501. until false;
  1502. { check for incomplete class definitions, this is only required
  1503. for fpc modes }
  1504. if (m_fpc in current_settings.modeswitches) then
  1505. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1506. end;
  1507. procedure read_interface_declarations;
  1508. begin
  1509. repeat
  1510. case token of
  1511. _CONST :
  1512. const_dec;
  1513. _TYPE :
  1514. type_dec;
  1515. _VAR :
  1516. var_dec;
  1517. _THREADVAR :
  1518. threadvar_dec;
  1519. _FUNCTION,
  1520. _PROCEDURE,
  1521. _OPERATOR :
  1522. read_proc;
  1523. else
  1524. begin
  1525. case idtoken of
  1526. _RESOURCESTRING :
  1527. resourcestring_dec;
  1528. _PROPERTY:
  1529. begin
  1530. if (m_fpc in current_settings.modeswitches) then
  1531. property_dec
  1532. else
  1533. break;
  1534. end;
  1535. else
  1536. break;
  1537. end;
  1538. end;
  1539. end;
  1540. until false;
  1541. { check for incomplete class definitions, this is only required
  1542. for fpc modes }
  1543. if (m_fpc in current_settings.modeswitches) then
  1544. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1545. end;
  1546. {****************************************************************************
  1547. SPECIALIZATION BODY GENERATION
  1548. ****************************************************************************}
  1549. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1550. function find_module_from_symtable(st:tsymtable):tmodule;
  1551. var
  1552. hp : tmodule;
  1553. begin
  1554. result:=nil;
  1555. hp:=tmodule(loaded_units.first);
  1556. while assigned(hp) do
  1557. begin
  1558. if (hp.globalsymtable=st) or
  1559. (hp.localsymtable=st) then
  1560. begin
  1561. result:=hp;
  1562. exit;
  1563. end;
  1564. hp:=tmodule(hp.next);
  1565. end;
  1566. end;
  1567. var
  1568. i : longint;
  1569. hp : tdef;
  1570. oldcurrent_filepos : tfileposinfo;
  1571. oldsymtablestack : tsymtablestack;
  1572. pu : tused_unit;
  1573. hmodule : tmodule;
  1574. begin
  1575. if not((tsym(p).typ=typesym) and
  1576. (ttypesym(p).typedef.typ=objectdef) and
  1577. (df_specialization in ttypesym(p).typedef.defoptions)
  1578. ) then
  1579. exit;
  1580. { Setup symtablestack a definition time }
  1581. oldsymtablestack:=symtablestack;
  1582. symtablestack:=tsymtablestack.create;
  1583. if not assigned(tobjectdef(ttypesym(p).typedef).genericdef) then
  1584. internalerror(200705151);
  1585. hmodule:=find_module_from_symtable(tobjectdef(ttypesym(p).typedef).genericdef.owner);
  1586. if hmodule=nil then
  1587. internalerror(200705152);
  1588. pu:=tused_unit(hmodule.used_units.first);
  1589. while assigned(pu) do
  1590. begin
  1591. if not assigned(pu.u.globalsymtable) then
  1592. internalerror(200705153);
  1593. symtablestack.push(pu.u.globalsymtable);
  1594. pu:=tused_unit(pu.next);
  1595. end;
  1596. symtablestack.push(hmodule.globalsymtable);
  1597. symtablestack.push(hmodule.localsymtable);
  1598. { definitions }
  1599. for i:=0 to tobjectdef(ttypesym(p).typedef).symtable.DefList.Count-1 do
  1600. begin
  1601. hp:=tdef(tobjectdef(ttypesym(p).typedef).symtable.DefList[i]);
  1602. if hp.typ=procdef then
  1603. begin
  1604. if assigned(tprocdef(hp).genericdef) and
  1605. (tprocdef(hp).genericdef.typ=procdef) and
  1606. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1607. begin
  1608. oldcurrent_filepos:=current_filepos;
  1609. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1610. current_tokenpos:=current_filepos;
  1611. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1612. read_proc_body(nil,tprocdef(hp));
  1613. current_filepos:=oldcurrent_filepos;
  1614. end
  1615. else
  1616. MessagePos1(tprocdef(tprocdef(hp).genericdef).fileinfo,sym_e_forward_not_resolved,tprocdef(tprocdef(hp).genericdef).fullprocname(false));
  1617. end;
  1618. end;
  1619. { Restore symtablestack }
  1620. symtablestack.free;
  1621. symtablestack:=oldsymtablestack;
  1622. end;
  1623. procedure generate_specialization_procs;
  1624. begin
  1625. if assigned(current_module.globalsymtable) then
  1626. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1627. if assigned(current_module.localsymtable) then
  1628. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1629. end;
  1630. end.