psub.pas 64 KB

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