psub.pas 83 KB

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