psub.pas 93 KB

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