psub.pas 73 KB

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