psub.pas 90 KB

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