psub.pas 69 KB

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