psub.pas 73 KB

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