psub.pas 64 KB

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