psub.pas 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  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. {$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. TAsmList(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 : TAsmList;
  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. templist:=TAsmList.create;
  628. { add parast/localst to symtablestack }
  629. add_to_symtablestack;
  630. { when size optimization only count occurrence }
  631. if cs_opt_size in aktoptimizerswitches then
  632. cg.t_times:=1
  633. else
  634. { reference for repetition is 100 }
  635. cg.t_times:=100;
  636. { clear register count }
  637. procdef.localst.foreach_static(@clearrefs,nil);
  638. procdef.parast.foreach_static(@clearrefs,nil);
  639. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  640. if (procdef.localst.symtablelevel=main_program_level) and
  641. (not current_module.is_unit) then
  642. include(flags,pi_do_call);
  643. { set implicit_finally flag when there are locals/paras to be finalized }
  644. procdef.parast.foreach_static(@check_finalize_paras,nil);
  645. procdef.localst.foreach_static(@check_finalize_locals,nil);
  646. { firstpass everything }
  647. flowcontrol:=[];
  648. do_firstpass(code);
  649. if code.registersfpu>0 then
  650. include(flags,pi_uses_fpu);
  651. { add implicit entry and exit code }
  652. add_entry_exit_code;
  653. { only do secondpass if there are no errors }
  654. if (ErrorCount=0) then
  655. begin
  656. { set the start offset to the start of the temp area in the stack }
  657. tg:=ttgobj.create;
  658. {$ifdef x86}
  659. { try to strip the stack frame }
  660. { set the framepointer to esp if:
  661. - no assembler directive, those are handled elsewhere
  662. - no exceptions are used
  663. - no debug info
  664. - no pushes are used/esp modifications, could be:
  665. * outgoing parameters on the stack
  666. * incoming parameters on the stack
  667. * open arrays
  668. - no inline assembler
  669. }
  670. if (cs_opt_level1 in aktoptimizerswitches) and
  671. not(po_assembler in procdef.procoptions) and
  672. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  673. pi_needs_implicit_finally,pi_has_implicit_finally,pi_has_stackparameter])=[]) then
  674. begin
  675. { we need the parameter info here to determine if the procedure gets
  676. parameters on the stack
  677. calling generate_parameter_info doesn't hurt but it costs time
  678. }
  679. generate_parameter_info;
  680. if not(stack_tainting_parameter) and
  681. not(has_assembler_child) then
  682. begin
  683. { Only need to set the framepointer }
  684. framepointer:=NR_STACK_POINTER_REG;
  685. tg.direction:=1;
  686. end;
  687. end;
  688. {$endif x86}
  689. { Create register allocator }
  690. cg.init_register_allocators;
  691. set_first_temp_offset;
  692. generate_parameter_info;
  693. { Allocate space in temp/registers for parast and localst }
  694. aktfilepos:=entrypos;
  695. gen_alloc_symtable(aktproccode,procdef.parast);
  696. gen_alloc_symtable(aktproccode,procdef.localst);
  697. { Store temp offset for information about 'real' temps }
  698. tempstart:=tg.lasttemp;
  699. { Generate code to load register parameters in temps and insert local
  700. copies for values parameters. This must be done before the code for the
  701. body is generated because the localloc is updated.
  702. Note: The generated code will be inserted after the code generation of
  703. the body is finished, because only then the position is known }
  704. {$ifdef oldregvars}
  705. assign_regvars(code);
  706. {$endif oldreg}
  707. aktfilepos:=entrypos;
  708. gen_load_para_value(templist);
  709. { caller paraloc info is also necessary in the stackframe_entry
  710. code of the ppc (and possibly other processors) }
  711. if not procdef.has_paraloc_info then
  712. begin
  713. procdef.requiredargarea:=paramanager.create_paraloc_info(procdef,callerside);
  714. procdef.has_paraloc_info:=true;
  715. end;
  716. { generate code for the node tree }
  717. do_secondpass(code);
  718. aktproccode.concatlist(current_asmdata.CurrAsmList);
  719. {$ifdef i386}
  720. procdef.fpu_used:=code.registersfpu;
  721. {$endif i386}
  722. { The position of the loadpara_asmnode is now known }
  723. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  724. { first generate entry and initialize code with the correct
  725. position and switches }
  726. aktfilepos:=entrypos;
  727. aktlocalswitches:=entryswitches;
  728. cg.set_regalloc_extend_backwards(true);
  729. gen_entry_code(templist);
  730. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  731. gen_initialize_code(templist);
  732. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  733. { now generate finalize and exit code with the correct position
  734. and switches }
  735. aktfilepos:=exitpos;
  736. aktlocalswitches:=exitswitches;
  737. cg.set_regalloc_extend_backwards(false);
  738. gen_finalize_code(templist);
  739. { the finalcode must be concated if there was no position available,
  740. using insertlistafter will result in an insert at the start
  741. when currentai=nil }
  742. if assigned(final_asmnode.currenttai) then
  743. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  744. else
  745. aktproccode.concatlist(templist);
  746. { insert exit label at the correct position }
  747. cg.a_label(templist,CurrExitLabel);
  748. if assigned(exitlabel_asmnode.currenttai) then
  749. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  750. else
  751. aktproccode.concatlist(templist);
  752. { exit code }
  753. gen_exit_code(templist);
  754. aktproccode.concatlist(templist);
  755. {$ifdef OLDREGVARS}
  756. { note: this must be done only after as much code as possible has }
  757. { been generated. The result is that when you ungetregister() a }
  758. { regvar, it will actually free the regvar (and alse free the }
  759. { the regvars at the same time). Doing this too early will }
  760. { confuse the register allocator, as the regvars will still be }
  761. { used. It should be done before loading the result regs (so }
  762. { they don't conflict with the regvars) and before }
  763. { gen_entry_code (that one has to be able to allocate the }
  764. { regvars again) (JM) }
  765. free_regvars(aktproccode);
  766. {$endif OLDREGVARS}
  767. { generate symbol and save end of header position }
  768. aktfilepos:=entrypos;
  769. gen_proc_symbol(templist);
  770. headertai:=tai(templist.last);
  771. { insert symbol }
  772. aktproccode.insertlist(templist);
  773. { Free space in temp/registers for parast and localst, must be
  774. done after gen_entry_code }
  775. aktfilepos:=exitpos;
  776. gen_free_symtable(aktproccode,procdef.localst);
  777. gen_free_symtable(aktproccode,procdef.parast);
  778. { add code that will load the return value, this is not done
  779. for assembler routines when they didn't reference the result
  780. variable }
  781. gen_load_return_value(templist);
  782. aktproccode.concatlist(templist);
  783. { Already reserve all registers for stack checking code and
  784. generate the call to the helper function }
  785. if (cs_check_stack in entryswitches) and
  786. not(po_assembler in procdef.procoptions) and
  787. (procdef.proctypeoption<>potype_proginit) then
  788. begin
  789. aktfilepos:=entrypos;
  790. gen_stack_check_call(templist);
  791. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  792. end;
  793. { load got if necessary }
  794. cg.set_regalloc_extend_backwards(true);
  795. aktfilepos:=entrypos;
  796. gen_got_load(templist);
  797. aktproccode.insertlistafter(headertai,templist);
  798. cg.set_regalloc_extend_backwards(false);
  799. { The procedure body is finished, we can now
  800. allocate the registers }
  801. cg.do_register_allocation(aktproccode,headertai);
  802. { translate imag. register to their real counter parts
  803. this is necessary for debuginfo and verbose assembler output
  804. when SSA will be implented, this will be more complicated because we've to
  805. maintain location lists }
  806. current_procinfo.procdef.parast.foreach_static(@translate_registers,templist);
  807. current_procinfo.procdef.localst.foreach_static(@translate_registers,templist);
  808. { Add save and restore of used registers }
  809. aktfilepos:=entrypos;
  810. gen_save_used_regs(templist);
  811. aktproccode.insertlistafter(headertai,templist);
  812. aktfilepos:=exitpos;
  813. gen_restore_used_regs(aktproccode);
  814. { We know the size of the stack, now we can generate the
  815. parameter that is passed to the stack checking code }
  816. if (cs_check_stack in entryswitches) and
  817. not(po_assembler in procdef.procoptions) and
  818. (procdef.proctypeoption<>potype_proginit) then
  819. begin
  820. aktfilepos:=entrypos;
  821. gen_stack_check_size_para(templist);
  822. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  823. end;
  824. { Add entry code (stack allocation) after header }
  825. aktfilepos:=entrypos;
  826. gen_proc_entry_code(templist);
  827. aktproccode.insertlistafter(headertai,templist);
  828. { Add exit code at the end }
  829. aktfilepos:=exitpos;
  830. gen_proc_exit_code(templist);
  831. aktproccode.concatlist(templist);
  832. { check if the implicit finally has been generated. The flag
  833. should already be set in pass1 }
  834. if (cs_implicit_exceptions in aktmoduleswitches) and
  835. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  836. (pi_needs_implicit_finally in flags) and
  837. not(pi_has_implicit_finally in flags) then
  838. internalerror(200405231);
  839. {$ifndef NoOpt}
  840. if not(cs_no_regalloc in aktglobalswitches) then
  841. begin
  842. if (cs_opt_level1 in aktoptimizerswitches) and
  843. { do not optimize pure assembler procedures }
  844. not(pi_is_assembler in flags) then
  845. optimize(aktproccode);
  846. end;
  847. {$endif NoOpt}
  848. {$ifdef ARM}
  849. { because of the limited constant size of the arm, all data access is done pc relative }
  850. insertpcrelativedata(aktproccode,aktlocaldata);
  851. {$endif ARM}
  852. { Add end symbol and debug info }
  853. { this must be done after the pcrelativedata is appended else the distance calculation of
  854. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  855. so it should be inserted before the end symbol (FK)
  856. }
  857. aktfilepos:=exitpos;
  858. gen_proc_symbol_end(templist);
  859. aktproccode.concatlist(templist);
  860. {$ifdef POWERPC}
  861. fixup_jmps(aktproccode);
  862. {$endif POWERPC}
  863. {$ifdef POWERPC64}
  864. fixup_jmps(aktproccode);
  865. {$endif POWERPC64}
  866. { insert line debuginfo }
  867. if (cs_debuginfo in aktmoduleswitches) or
  868. (cs_use_lineinfo in aktglobalswitches) then
  869. debuginfo.insertlineinfo(aktproccode);
  870. { add the procedure to the al_procedures }
  871. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  872. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  873. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  874. { save local data (casetable) also in the same file }
  875. if assigned(aktlocaldata) and
  876. (not aktlocaldata.empty) then
  877. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  878. { only now we can remove the temps }
  879. tg.resettempgen;
  880. { stop tempgen and ra }
  881. tg.free;
  882. cg.done_register_allocators;
  883. tg:=nil;
  884. end;
  885. { restore symtablestack }
  886. remove_from_symtablestack;
  887. { restore }
  888. templist.free;
  889. aktmaxfpuregisters:=oldaktmaxfpuregisters;
  890. aktfilepos:=oldfilepos;
  891. current_procinfo:=oldprocinfo;
  892. end;
  893. procedure tcgprocinfo.add_to_symtablestack;
  894. var
  895. _class,hp : tobjectdef;
  896. begin
  897. { insert symtables for the class, but only if it is no nested function }
  898. if assigned(procdef._class) and
  899. not(assigned(parent) and
  900. assigned(parent.procdef) and
  901. assigned(parent.procdef._class)) then
  902. begin
  903. { insert them in the reverse order }
  904. hp:=nil;
  905. repeat
  906. _class:=procdef._class;
  907. while _class.childof<>hp do
  908. _class:=_class.childof;
  909. hp:=_class;
  910. symtablestack.push(_class.symtable);
  911. until hp=procdef._class;
  912. end;
  913. { insert parasymtable in symtablestack when parsing
  914. a function }
  915. if procdef.parast.symtablelevel>=normal_function_level then
  916. symtablestack.push(procdef.parast);
  917. { insert localsymtable }
  918. symtablestack.push(procdef.localst);
  919. end;
  920. procedure tcgprocinfo.remove_from_symtablestack;
  921. var
  922. _class : tobjectdef;
  923. begin
  924. { remove localsymtable }
  925. symtablestack.pop(procdef.localst);
  926. { remove parasymtable }
  927. if procdef.parast.symtablelevel>=normal_function_level then
  928. symtablestack.pop(procdef.parast);
  929. { remove symtables for the class, but only if it is no nested function }
  930. if assigned(procdef._class) and
  931. not(assigned(parent) and
  932. assigned(parent.procdef) and
  933. assigned(parent.procdef._class)) then
  934. begin
  935. _class:=procdef._class;
  936. while assigned(_class) do
  937. begin
  938. symtablestack.pop(_class.symtable);
  939. _class:=_class.childof;
  940. end;
  941. end;
  942. end;
  943. procedure tcgprocinfo.resetprocdef;
  944. begin
  945. { remove code tree, if not inline procedure }
  946. if assigned(code) then
  947. begin
  948. { the inline procedure has already got a copy of the tree
  949. stored in procdef.inlininginfo }
  950. code.free;
  951. code:=nil;
  952. end;
  953. end;
  954. function checknodeinlining(procdef: tprocdef): boolean;
  955. var
  956. i : integer;
  957. currpara : tparavarsym;
  958. begin
  959. result := false;
  960. if (pi_has_assembler_block in current_procinfo.flags) then
  961. exit;
  962. for i:=0 to procdef.paras.count-1 do
  963. begin
  964. currpara:=tparavarsym(procdef.paras[i]);
  965. { we can't handle formaldefs and special arrays (the latter may need a }
  966. { re-basing of the index, i.e. if you pass an array[1..10] as open array, }
  967. { you have to add 1 to all index operations if you directly inline it }
  968. if ((currpara.varspez in [vs_out,vs_var,vs_const]) and
  969. (currpara.vartype.def.deftype=formaldef)) or
  970. is_special_array(currpara.vartype.def) then
  971. exit;
  972. end;
  973. result:=true;
  974. end;
  975. procedure tcgprocinfo.parse_body;
  976. var
  977. oldprocinfo : tprocinfo;
  978. oldblock_type : tblock_type;
  979. st : tsymtable;
  980. begin
  981. oldprocinfo:=current_procinfo;
  982. oldblock_type:=block_type;
  983. { reset break and continue labels }
  984. block_type:=bt_body;
  985. current_procinfo:=self;
  986. { calculate the lexical level }
  987. if procdef.parast.symtablelevel>maxnesting then
  988. Message(parser_e_too_much_lexlevel);
  989. { static is also important for local procedures !! }
  990. if (po_staticmethod in procdef.procoptions) then
  991. allow_only_static:=true
  992. else if (procdef.parast.symtablelevel=normal_function_level) then
  993. allow_only_static:=false;
  994. {$ifdef state_tracking}
  995. { aktstate:=Tstate_storage.create;}
  996. {$endif state_tracking}
  997. { allocate the symbol for this procedure }
  998. alloc_proc_symbol(procdef);
  999. { create a local symbol table for this routine }
  1000. if not assigned(procdef.localst) then
  1001. procdef.insert_localst;
  1002. { add parast/localst to symtablestack }
  1003. add_to_symtablestack;
  1004. { save entry info }
  1005. entrypos:=aktfilepos;
  1006. entryswitches:=aktlocalswitches;
  1007. if (df_generic in procdef.defoptions) then
  1008. begin
  1009. { start token recorder for generic template }
  1010. procdef.initgeneric;
  1011. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1012. end;
  1013. { parse the code ... }
  1014. code:=block(current_module.islibrary);
  1015. if (df_generic in procdef.defoptions) then
  1016. begin
  1017. { stop token recorder for generic template }
  1018. current_scanner.stoprecordtokens;
  1019. { Give a warning for accesses in the static symtable that aren't visible
  1020. outside the current unit }
  1021. st:=procdef.owner;
  1022. while (st.symtabletype=objectsymtable) do
  1023. st:=st.defowner.owner;
  1024. if (pi_uses_static_symtable in flags) and
  1025. (st.symtabletype<>staticsymtable) then
  1026. Comment(V_Warning,'Global Generic template references static symtable');
  1027. end;
  1028. { save exit info }
  1029. exitswitches:=aktlocalswitches;
  1030. exitpos:=last_endtoken_filepos;
  1031. { the procedure is now defined }
  1032. procdef.forwarddef:=false;
  1033. if assigned(code) then
  1034. begin
  1035. { get a better entry point }
  1036. entrypos:=code.fileinfo;
  1037. { Finish type checking pass }
  1038. do_resulttypepass(code);
  1039. end;
  1040. { Check for unused labels, forwards, symbols for procedures. Static
  1041. symtable is checked in pmodules.
  1042. The check must be done after the resulttypepass }
  1043. if (Errorcount=0) and
  1044. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1045. begin
  1046. { check if forwards are resolved }
  1047. tstoredsymtable(procdef.localst).check_forwards;
  1048. { check if all labels are used }
  1049. tstoredsymtable(procdef.localst).checklabels;
  1050. { remove cross unit overloads }
  1051. tstoredsymtable(procdef.localst).unchain_overloaded;
  1052. { check for unused symbols, but only if there is no asm block }
  1053. if not(pi_has_assembler_block in flags) then
  1054. begin
  1055. tstoredsymtable(procdef.localst).allsymbolsused;
  1056. tstoredsymtable(procdef.parast).allsymbolsused;
  1057. end;
  1058. end;
  1059. if (po_inline in procdef.procoptions) then
  1060. begin
  1061. { Can we inline this procedure? }
  1062. if checknodeinlining(procdef) then
  1063. begin
  1064. new(procdef.inlininginfo);
  1065. include(procdef.procoptions,po_has_inlininginfo);
  1066. procdef.inlininginfo^.code:=code.getcopy;
  1067. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1068. { The blocknode needs to set an exit label }
  1069. if procdef.inlininginfo^.code.nodetype=blockn then
  1070. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1071. end;
  1072. end;
  1073. { Print the node to tree.log }
  1074. if paraprintnodetree=1 then
  1075. printproc;
  1076. { ... remove symbol tables }
  1077. remove_from_symtablestack;
  1078. {$ifdef state_tracking}
  1079. { aktstate.destroy;}
  1080. {$endif state_tracking}
  1081. { reset to normal non static function }
  1082. if (procdef.parast.symtablelevel=normal_function_level) then
  1083. allow_only_static:=false;
  1084. current_procinfo:=oldprocinfo;
  1085. { Restore old state }
  1086. block_type:=oldblock_type;
  1087. end;
  1088. {****************************************************************************
  1089. PROCEDURE/FUNCTION PARSING
  1090. ****************************************************************************}
  1091. procedure check_init_paras(p:tnamedindexitem;arg:pointer);
  1092. begin
  1093. if tsym(p).typ<>paravarsym then
  1094. exit;
  1095. with tparavarsym(p) do
  1096. if (not is_class(vartype.def) and
  1097. vartype.def.needs_inittable and
  1098. (varspez in [vs_value,vs_out])) then
  1099. include(current_procinfo.flags,pi_do_call);
  1100. end;
  1101. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1102. {
  1103. Parses the procedure directives, then parses the procedure body, then
  1104. generates the code for it
  1105. }
  1106. procedure do_generate_code(pi:tcgprocinfo);
  1107. var
  1108. hpi : tcgprocinfo;
  1109. begin
  1110. { generate code for this procedure }
  1111. pi.generate_code;
  1112. { process nested procs }
  1113. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1114. while assigned(hpi) do
  1115. begin
  1116. do_generate_code(hpi);
  1117. hpi:=tcgprocinfo(hpi.next);
  1118. end;
  1119. pi.resetprocdef;
  1120. end;
  1121. var
  1122. oldfailtokenmode : tmodeswitch;
  1123. isnestedproc : boolean;
  1124. begin
  1125. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1126. { create a new procedure }
  1127. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1128. current_module.procinfo:=current_procinfo;
  1129. current_procinfo.procdef:=pd;
  1130. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1131. { Insert mangledname }
  1132. pd.aliasnames.insert(pd.mangledname);
  1133. { Handle Export of this procedure }
  1134. if (po_exports in pd.procoptions) and
  1135. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1136. begin
  1137. pd.aliasnames.insert(pd.procsym.realname);
  1138. if cs_link_deffile in aktglobalswitches then
  1139. deffile.AddExport(pd.mangledname);
  1140. end;
  1141. { Insert result variables in the localst }
  1142. insert_funcret_local(pd);
  1143. { check if there are para's which require initing -> set }
  1144. { pi_do_call (if not yet set) }
  1145. if not(pi_do_call in current_procinfo.flags) then
  1146. pd.parast.foreach_static(@check_init_paras,nil);
  1147. { set _FAIL as keyword if constructor }
  1148. if (pd.proctypeoption=potype_constructor) then
  1149. begin
  1150. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1151. tokeninfo^[_FAIL].keyword:=m_all;
  1152. end;
  1153. tcgprocinfo(current_procinfo).parse_body;
  1154. { When it's a nested procedure then defer the code generation,
  1155. when back at normal function level then generate the code
  1156. for all defered nested procedures and the current procedure }
  1157. if isnestedproc then
  1158. tcgprocinfo(current_procinfo.parent).nestedprocs.insert(current_procinfo)
  1159. else
  1160. begin
  1161. { We can't support inlining for procedures that have nested
  1162. procedures because the nested procedures use a fixed offset
  1163. for accessing locals in the parent procedure (PFV) }
  1164. if (tcgprocinfo(current_procinfo).nestedprocs.count>0) then
  1165. begin
  1166. if (df_generic in current_procinfo.procdef.defoptions) then
  1167. {$warning TODO Add error message for nested procs in generics}
  1168. internalerror(200511151)
  1169. else if (po_inline in current_procinfo.procdef.procoptions) then
  1170. begin
  1171. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1172. Message(parser_w_inlining_disabled);
  1173. current_procinfo.procdef.proccalloption:=pocall_default;
  1174. end;
  1175. end;
  1176. if not(df_generic in current_procinfo.procdef.defoptions) then
  1177. do_generate_code(tcgprocinfo(current_procinfo));
  1178. end;
  1179. { reset _FAIL as _SELF normal }
  1180. if (pd.proctypeoption=potype_constructor) then
  1181. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1182. { release procinfo }
  1183. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1184. internalerror(200304274);
  1185. current_module.procinfo:=current_procinfo.parent;
  1186. { For specialization we didn't record the last semicolon. Moving this parsing
  1187. into the parse_body routine is not done because of having better file position
  1188. information available }
  1189. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1190. consume(_SEMICOLON);
  1191. if not isnestedproc then
  1192. current_procinfo.free;
  1193. end;
  1194. procedure read_proc;
  1195. {
  1196. Parses the procedure directives, then parses the procedure body, then
  1197. generates the code for it
  1198. }
  1199. procedure do_generate_code(pi:tcgprocinfo);
  1200. var
  1201. hpi : tcgprocinfo;
  1202. begin
  1203. { generate code for this procedure }
  1204. pi.generate_code;
  1205. { process nested procs }
  1206. hpi:=tcgprocinfo(pi.nestedprocs.first);
  1207. while assigned(hpi) do
  1208. begin
  1209. do_generate_code(hpi);
  1210. hpi:=tcgprocinfo(hpi.next);
  1211. end;
  1212. pi.resetprocdef;
  1213. end;
  1214. var
  1215. old_current_procinfo : tprocinfo;
  1216. pdflags : tpdflags;
  1217. pd : tprocdef;
  1218. s : string;
  1219. begin
  1220. { save old state }
  1221. old_current_procinfo:=current_procinfo;
  1222. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1223. to an other procdef }
  1224. current_procinfo:=nil;
  1225. { parse procedure declaration }
  1226. if assigned(old_current_procinfo) and
  1227. assigned(old_current_procinfo.procdef) then
  1228. pd:=parse_proc_dec(old_current_procinfo.procdef._class)
  1229. else
  1230. pd:=parse_proc_dec(nil);
  1231. { set the default function options }
  1232. if parse_only then
  1233. begin
  1234. pd.forwarddef:=true;
  1235. { set also the interface flag, for better error message when the
  1236. implementation doesn't much this header }
  1237. pd.interfacedef:=true;
  1238. include(pd.procoptions,po_global);
  1239. pdflags:=[pd_interface];
  1240. end
  1241. else
  1242. begin
  1243. pdflags:=[pd_body];
  1244. if (not current_module.in_interface) then
  1245. include(pdflags,pd_implemen);
  1246. if (not current_module.is_unit) or
  1247. maybe_smartlink_symbol or
  1248. {
  1249. taking addresses of static procedures goes wrong
  1250. if they aren't global when pic is used (FK)
  1251. }
  1252. (cs_create_pic in aktmoduleswitches) then
  1253. include(pd.procoptions,po_global);
  1254. pd.forwarddef:=false;
  1255. end;
  1256. { parse the directives that may follow }
  1257. parse_proc_directives(pd,pdflags);
  1258. { hint directives, these can be separated by semicolons here,
  1259. that needs to be handled here with a loop (PFV) }
  1260. while try_consume_hintdirective(pd.symoptions) do
  1261. Consume(_SEMICOLON);
  1262. { Set calling convention }
  1263. handle_calling_convention(pd);
  1264. { search for forward declarations }
  1265. if not proc_add_definition(pd) then
  1266. begin
  1267. { A method must be forward defined (in the object declaration) }
  1268. if assigned(pd._class) and
  1269. (not assigned(old_current_procinfo.procdef._class)) then
  1270. begin
  1271. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1272. tprocsym(pd.procsym).write_parameter_lists(pd);
  1273. end
  1274. else
  1275. begin
  1276. { Give a better error if there is a forward def in the interface and only
  1277. a single implementation }
  1278. if (not pd.forwarddef) and
  1279. (not pd.interfacedef) and
  1280. (tprocsym(pd.procsym).procdef_count>1) and
  1281. tprocsym(pd.procsym).first_procdef.forwarddef and
  1282. tprocsym(pd.procsym).first_procdef.interfacedef and
  1283. not(tprocsym(pd.procsym).procdef_count>2) then
  1284. begin
  1285. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1286. tprocsym(pd.procsym).write_parameter_lists(pd);
  1287. end;
  1288. end;
  1289. end;
  1290. { Set mangled name }
  1291. proc_set_mangledname(pd);
  1292. { compile procedure when a body is needed }
  1293. if (pd_body in pdflags) then
  1294. begin
  1295. read_proc_body(old_current_procinfo,pd);
  1296. end
  1297. else
  1298. begin
  1299. { Handle imports }
  1300. if (po_external in pd.procoptions) then
  1301. begin
  1302. { External declared in implementation, and there was already a
  1303. forward (or interface) declaration then we need to generate
  1304. a stub that calls the external routine }
  1305. if (not pd.forwarddef) and
  1306. (pd.hasforward) and
  1307. not(
  1308. assigned(pd.import_dll) and
  1309. (
  1310. (
  1311. GenerateImportSection and
  1312. (target_info.system in [system_i386_win32])
  1313. ) or
  1314. (
  1315. target_info.system in [system_i386_wdosx,system_i386_emx,system_i386_os2,
  1316. system_arm_wince,system_i386_wince]
  1317. )
  1318. )
  1319. ) then
  1320. begin
  1321. s:=proc_get_importname(pd);
  1322. if s<>'' then
  1323. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,{$IFDEF POWERPC64}'.'+{$ENDIF}s);
  1324. end;
  1325. { Import DLL specified? }
  1326. if assigned(pd.import_dll) then
  1327. begin
  1328. { create importlib if not already done }
  1329. if not(current_module.uses_imports) then
  1330. begin
  1331. current_module.uses_imports:=true;
  1332. importlib.preparelib(current_module.realmodulename^);
  1333. end;
  1334. if assigned(pd.import_name) then
  1335. importlib.importprocedure(pd,pd.import_dll^,pd.import_nr,pd.import_name^)
  1336. else
  1337. importlib.importprocedure(pd,pd.import_dll^,pd.import_nr,'');
  1338. end
  1339. else
  1340. begin
  1341. { add import name to external list for DLL scanning }
  1342. if tf_has_dllscanner in target_info.flags then
  1343. current_module.externals.insert(tExternalsItem.create(proc_get_importname(pd)));
  1344. end;
  1345. end;
  1346. end;
  1347. { make sure that references to forward-declared functions are not }
  1348. { treated as references to external symbols, needed for darwin. }
  1349. { make sure we don't change the binding of real external symbols }
  1350. if not(po_external in pd.procoptions) then
  1351. begin
  1352. if (po_global in pd.procoptions) or
  1353. (cs_profile in aktmoduleswitches) then
  1354. current_asmdata.newasmsymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1355. else
  1356. current_asmdata.newasmsymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1357. end;
  1358. current_procinfo:=old_current_procinfo;
  1359. end;
  1360. {****************************************************************************
  1361. DECLARATION PARSING
  1362. ****************************************************************************}
  1363. { search in symtablestack for not complete classes }
  1364. procedure check_forward_class(p : tnamedindexitem;arg:pointer);
  1365. begin
  1366. if (tsym(p).typ=typesym) and
  1367. (ttypesym(p).restype.def.deftype=objectdef) and
  1368. (oo_is_forward in tobjectdef(ttypesym(p).restype.def).objectoptions) then
  1369. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1370. end;
  1371. procedure read_declarations(islibrary : boolean);
  1372. begin
  1373. repeat
  1374. if not assigned(current_procinfo) then
  1375. internalerror(200304251);
  1376. case token of
  1377. _LABEL:
  1378. label_dec;
  1379. _CONST:
  1380. const_dec;
  1381. _TYPE:
  1382. type_dec;
  1383. _VAR:
  1384. var_dec;
  1385. _THREADVAR:
  1386. threadvar_dec;
  1387. _CONSTRUCTOR,
  1388. _DESTRUCTOR,
  1389. _FUNCTION,
  1390. _PROCEDURE,
  1391. _OPERATOR,
  1392. _CLASS:
  1393. read_proc;
  1394. _EXPORTS:
  1395. begin
  1396. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1397. begin
  1398. Message(parser_e_syntax_error);
  1399. consume_all_until(_SEMICOLON);
  1400. end
  1401. else if islibrary or
  1402. (target_info.system in system_unit_program_exports) then
  1403. read_exports
  1404. else
  1405. begin
  1406. Message(parser_w_unsupported_feature);
  1407. consume(_BEGIN);
  1408. end;
  1409. end
  1410. else
  1411. begin
  1412. case idtoken of
  1413. _RESOURCESTRING :
  1414. begin
  1415. { m_class is needed, because the resourcestring
  1416. loading is in the ObjPas unit }
  1417. if (m_class in aktmodeswitches) then
  1418. resourcestring_dec
  1419. else
  1420. break;
  1421. end;
  1422. _PROPERTY:
  1423. begin
  1424. if (m_fpc in aktmodeswitches) then
  1425. property_dec
  1426. else
  1427. break;
  1428. end;
  1429. else
  1430. break;
  1431. end;
  1432. end;
  1433. end;
  1434. until false;
  1435. { check for incomplete class definitions, this is only required
  1436. for fpc modes }
  1437. if (m_fpc in aktmodeswitches) then
  1438. current_procinfo.procdef.localst.foreach_static(@check_forward_class,nil);
  1439. end;
  1440. procedure read_interface_declarations;
  1441. begin
  1442. repeat
  1443. case token of
  1444. _CONST :
  1445. const_dec;
  1446. _TYPE :
  1447. type_dec;
  1448. _VAR :
  1449. var_dec;
  1450. _THREADVAR :
  1451. threadvar_dec;
  1452. _FUNCTION,
  1453. _PROCEDURE,
  1454. _OPERATOR :
  1455. read_proc;
  1456. else
  1457. begin
  1458. case idtoken of
  1459. _RESOURCESTRING :
  1460. resourcestring_dec;
  1461. _PROPERTY:
  1462. begin
  1463. if (m_fpc in aktmodeswitches) then
  1464. property_dec
  1465. else
  1466. break;
  1467. end;
  1468. else
  1469. break;
  1470. end;
  1471. end;
  1472. end;
  1473. until false;
  1474. { check for incomplete class definitions, this is only required
  1475. for fpc modes }
  1476. if (m_fpc in aktmodeswitches) then
  1477. symtablestack.top.foreach_static(@check_forward_class,nil);
  1478. end;
  1479. {****************************************************************************
  1480. SPECIALIZATION BODY GENERATION
  1481. ****************************************************************************}
  1482. procedure specialize_objectdefs(p:tnamedindexitem;arg:pointer);
  1483. var
  1484. hp : tdef;
  1485. oldaktfilepos : tfileposinfo;
  1486. begin
  1487. if not((tsym(p).typ=typesym) and
  1488. (ttypesym(p).restype.def.deftype=objectdef) and
  1489. (df_specialization in ttypesym(p).restype.def.defoptions)
  1490. ) then
  1491. exit;
  1492. { definitions }
  1493. hp:=tdef(tobjectdef(ttypesym(p).restype.def).symtable.defindex.first);
  1494. while assigned(hp) do
  1495. begin
  1496. if hp.deftype=procdef then
  1497. begin
  1498. if not(
  1499. assigned(tprocdef(hp).genericdef) and
  1500. (tprocdef(hp).genericdef.deftype=procdef) and
  1501. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf)
  1502. ) then
  1503. internalerror(200512111);
  1504. oldaktfilepos:=aktfilepos;
  1505. aktfilepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1506. akttokenpos:=aktfilepos;
  1507. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1508. read_proc_body(nil,tprocdef(hp));
  1509. aktfilepos:=oldaktfilepos;
  1510. end;
  1511. hp:=tdef(hp.indexnext);
  1512. end;
  1513. end;
  1514. procedure generate_specialization_procs;
  1515. begin
  1516. if assigned(current_module.globalsymtable) then
  1517. current_module.globalsymtable.foreach_static(@specialize_objectdefs,nil);
  1518. if assigned(current_module.localsymtable) then
  1519. begin
  1520. symtablestack.push(current_module.localsymtable);
  1521. current_module.localsymtable.foreach_static(@specialize_objectdefs,nil);
  1522. symtablestack.pop(current_module.localsymtable);
  1523. end;
  1524. end;
  1525. end.