psub.pas 68 KB

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