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