psub.pas 83 KB

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