psub.pas 73 KB

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