psub.pas 70 KB

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