psub.pas 71 KB

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