psub.pas 64 KB

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