psub.pas 67 KB

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