psub.pas 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325
  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(x86) or defined(arm)}
  867. { try to strip the stack frame }
  868. { set the framepointer to esp if:
  869. - no assembler directive, those are handled in assembler_block
  870. in pstatment.pas (for cases not caught by the Delphi
  871. exception below)
  872. - no exceptions are used
  873. - no pushes are used/esp modifications, could be:
  874. * outgoing parameters on the stack
  875. * incoming parameters on the stack
  876. * open arrays
  877. - no inline assembler
  878. or
  879. - Delphi mode
  880. - assembler directive
  881. - no pushes are used/esp modifications, could be:
  882. * outgoing parameters on the stack
  883. * incoming parameters on the stack
  884. * open arrays
  885. - no local variables
  886. - stack frame cannot be optimized if using Win64 SEH
  887. (at least with the current state of our codegenerator).
  888. }
  889. if ((po_assembler in procdef.procoptions) and
  890. (m_delphi in current_settings.modeswitches) and
  891. { localst at main_program_level is a staticsymtable }
  892. (procdef.localst.symtablelevel<>main_program_level) and
  893. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  894. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  895. not(cs_generate_stackframes in current_settings.localswitches) and
  896. not(po_assembler in procdef.procoptions) and
  897. ((flags*([pi_has_assembler_block,pi_is_assembler,
  898. pi_has_stackparameter,pi_needs_stackframe]+
  899. exception_flags[(target_info.cpu=cpu_i386)
  900. {$ifndef DISABLE_WIN64_SEH}
  901. or (target_info.system=system_x86_64_win64)
  902. {$endif DISABLE_WIN64_SEH}
  903. ]))=[])
  904. )
  905. then
  906. begin
  907. { we need the parameter info here to determine if the procedure gets
  908. parameters on the stack
  909. calling generate_parameter_info doesn't hurt but it costs time
  910. (necessary to init para_stack_size)
  911. }
  912. generate_parameter_info;
  913. if not(procdef.stack_tainting_parameter(calleeside)) and
  914. not(has_assembler_child) and (para_stack_size=0) then
  915. begin
  916. { Only need to set the framepointer }
  917. framepointer:=NR_STACK_POINTER_REG;
  918. tg.direction:=1;
  919. end;
  920. end;
  921. {$endif}
  922. {$ifdef MIPS}
  923. framepointer:=NR_STACK_POINTER_REG;
  924. tg.direction:=1;
  925. {$endif MIPS}
  926. {$ifdef ARM}
  927. if current_settings.cputype in cpu_thumb then
  928. tg.direction:=1;
  929. {$endif ARM}
  930. { set the start offset to the start of the temp area in the stack }
  931. set_first_temp_offset;
  932. end;
  933. function tcgprocinfo.has_assembler_child : boolean;
  934. var
  935. hp : tprocinfo;
  936. begin
  937. result:=false;
  938. hp:=get_first_nestedproc;
  939. while assigned(hp) do
  940. begin
  941. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  942. begin
  943. result:=true;
  944. exit;
  945. end;
  946. hp:=tprocinfo(hp.next);
  947. end;
  948. end;
  949. procedure tcgprocinfo.generate_code_tree;
  950. var
  951. hpi : tcgprocinfo;
  952. begin
  953. { generate code for this procedure }
  954. generate_code;
  955. { process nested procedures }
  956. hpi:=tcgprocinfo(get_first_nestedproc);
  957. while assigned(hpi) do
  958. begin
  959. hpi.generate_code_tree;
  960. hpi:=tcgprocinfo(hpi.next);
  961. end;
  962. resetprocdef;
  963. end;
  964. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  965. which can be called by OS during stack unwind. This resembles nested procedures,
  966. but finalizer procedures do not have their own local variables and work directly
  967. with the stack frame of parent. In particular, the tempgen must be shared, so
  968. 1) finalizer procedure is able to finalize temps of the parent,
  969. 2) if the finalizer procedure is complex enough to need its own temps, they are
  970. allocated in stack frame of parent, so second-level finalizer procedures are
  971. not needed.
  972. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  973. procedure (after the parent) and have to do it inline.
  974. This is called by platform-specific tryfinallynodes during pass2.
  975. Here we put away the codegen (which carries the register allocator state), process
  976. the 'nested' procedure, then restore previous cg and continue processing the parent
  977. procedure. generate_code() will create another cg, but not another tempgen because
  978. setup_tempgen() is not called for potype_exceptfilter procedures. }
  979. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  980. var
  981. saved_cg: tcg;
  982. saved_hlcg: thlcgobj;
  983. {$ifdef cpu64bitalu}
  984. saved_cg128 : tcg128;
  985. {$else cpu64bitalu}
  986. saved_cg64 : tcg64;
  987. {$endif cpu64bitalu}
  988. begin
  989. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  990. InternalError(201201141);
  991. { flush code generated this far }
  992. aktproccode.concatlist(current_asmdata.CurrAsmList);
  993. { save the codegen }
  994. saved_cg:=cg;
  995. saved_hlcg:=hlcg;
  996. cg:=nil;
  997. hlcg:=nil;
  998. {$ifdef cpu64bitalu}
  999. saved_cg128:=cg128;
  1000. cg128:=nil;
  1001. {$else cpu64bitalu}
  1002. saved_cg64:=cg64;
  1003. cg64:=nil;
  1004. {$endif cpu64bitalu}
  1005. nestedpi.generate_code;
  1006. { prevents generating code the second time when processing nested procedures }
  1007. nestedpi.resetprocdef;
  1008. cg:=saved_cg;
  1009. hlcg:=saved_hlcg;
  1010. {$ifdef cpu64bitalu}
  1011. cg128:=saved_cg128;
  1012. {$else cpu64bitalu}
  1013. cg64:=saved_cg64;
  1014. {$endif cpu64bitalu}
  1015. add_reg_instruction_hook:[email protected]_reg_instruction;
  1016. end;
  1017. procedure TCGProcinfo.CreateInlineInfo;
  1018. begin
  1019. new(procdef.inlininginfo);
  1020. include(procdef.procoptions,po_has_inlininginfo);
  1021. procdef.inlininginfo^.code:=code.getcopy;
  1022. procdef.inlininginfo^.flags:=flags;
  1023. { The blocknode needs to set an exit label }
  1024. if procdef.inlininginfo^.code.nodetype=blockn then
  1025. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1026. end;
  1027. procedure tcgprocinfo.generate_code;
  1028. var
  1029. old_current_procinfo : tprocinfo;
  1030. oldmaxfpuregisters : longint;
  1031. oldfilepos : tfileposinfo;
  1032. old_current_structdef : tabstractrecorddef;
  1033. templist : TAsmList;
  1034. headertai : tai;
  1035. i : integer;
  1036. varsym : tabstractnormalvarsym;
  1037. {RedoDFA : boolean;}
  1038. begin
  1039. { the initialization procedure can be empty, then we
  1040. don't need to generate anything. When it was an empty
  1041. procedure there would be at least a blocknode }
  1042. if not assigned(code) then
  1043. exit;
  1044. { We need valid code }
  1045. if Errorcount<>0 then
  1046. exit;
  1047. { No code can be generated for generic template }
  1048. if (df_generic in procdef.defoptions) then
  1049. internalerror(200511152);
  1050. { For regular procedures the RA and Tempgen shall not be available yet,
  1051. but exception filters reuse Tempgen of parent }
  1052. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1053. internalerror(200309201);
  1054. old_current_procinfo:=current_procinfo;
  1055. oldfilepos:=current_filepos;
  1056. old_current_structdef:=current_structdef;
  1057. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1058. current_procinfo:=self;
  1059. current_filepos:=entrypos;
  1060. current_structdef:=procdef.struct;
  1061. { add wrapping code if necessary (initialization of typed constants on
  1062. some platforms, initing of local variables and out parameters with
  1063. trashing values, ... }
  1064. { init/final code must be wrapped later (after code for main proc body
  1065. has been generated }
  1066. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1067. code:=cnodeutils.wrap_proc_body(procdef,code);
  1068. { automatic inlining? }
  1069. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1070. { inlining not turned off? }
  1071. (cs_do_inline in current_settings.localswitches) and
  1072. { no inlining yet? }
  1073. not(po_has_inlininginfo in procdef.procoptions) and not(has_nestedprocs) and
  1074. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1075. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1076. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1077. (not(procdef.proccalloption in [pocall_safecall])) and
  1078. { rough approximation if we should auto inline }
  1079. (node_count(code)<=10) then
  1080. begin
  1081. { Can we inline this procedure? }
  1082. if checknodeinlining(procdef) then
  1083. begin
  1084. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1085. include(procdef.procoptions,po_inline);
  1086. CreateInlineInfo;
  1087. end;
  1088. end;
  1089. templist:=TAsmList.create;
  1090. { add parast/localst to symtablestack }
  1091. add_to_symtablestack;
  1092. { clear register count }
  1093. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1094. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1095. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1096. if (procdef.localst.symtablelevel=main_program_level) and
  1097. (not current_module.is_unit) then
  1098. include(flags,pi_do_call);
  1099. { set implicit_finally flag when there are locals/paras to be finalized }
  1100. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1101. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1102. {$ifdef SUPPORT_SAFECALL}
  1103. { set implicit_finally flag for if procedure is safecall }
  1104. if (tf_safecall_exceptions in target_info.flags) and
  1105. (procdef.proccalloption=pocall_safecall) then
  1106. include(flags, pi_needs_implicit_finally);
  1107. {$endif}
  1108. { firstpass everything }
  1109. flowcontrol:=[];
  1110. do_firstpass(code);
  1111. {$ifdef i386}
  1112. procdef.fpu_used:=node_resources_fpu(code);
  1113. if procdef.fpu_used>0 then
  1114. include(flags,pi_uses_fpu);
  1115. {$endif i386}
  1116. { Print the node to tree.log }
  1117. if paraprintnodetree=1 then
  1118. printproc( 'after the firstpass');
  1119. { do this before adding the entry code else the tail recursion recognition won't work,
  1120. if this causes troubles, it must be if'ed
  1121. }
  1122. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1123. (pi_is_recursive in flags) then
  1124. do_opttail(code,procdef);
  1125. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1126. { creating dfa is not always possible }
  1127. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  1128. pi_needs_implicit_finally,pi_has_implicit_finally])=[]) then
  1129. begin
  1130. dfabuilder:=TDFABuilder.Create;
  1131. dfabuilder.createdfainfo(code);
  1132. { when life info is available, we can give more sophisticated warning about unintialized
  1133. variables }
  1134. { iterate through life info of the first node }
  1135. for i:=0 to dfabuilder.nodemap.count-1 do
  1136. begin
  1137. if DFASetIn(code.optinfo^.life,i) then
  1138. case tnode(dfabuilder.nodemap[i]).nodetype of
  1139. loadn:
  1140. begin
  1141. varsym:=tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry);
  1142. { Give warning/note for living locals }
  1143. if assigned(varsym.owner) and
  1144. not(vo_is_external in varsym.varoptions) then
  1145. begin
  1146. if (vo_is_funcret in varsym.varoptions) then
  1147. CGMessage(sym_w_function_result_uninitialized)
  1148. else
  1149. begin
  1150. if (varsym.owner=procdef.localst) and not (vo_is_typed_const in varsym.varoptions) then
  1151. CGMessage1(sym_w_uninitialized_local_variable,varsym.realname);
  1152. end;
  1153. end;
  1154. end;
  1155. end;
  1156. end;
  1157. include(flags,pi_dfaavailable);
  1158. end;
  1159. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1160. { our induction variable strength reduction doesn't like
  1161. for loops with more than one entry }
  1162. and not(pi_has_label in flags) then
  1163. begin
  1164. {RedoDFA:=}OptimizeInductionVariables(code);
  1165. end;
  1166. if cs_opt_nodecse in current_settings.optimizerswitches then
  1167. do_optcse(code);
  1168. if (cs_opt_remove_emtpy_proc in current_settings.optimizerswitches) and
  1169. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1170. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1171. procdef.isempty:=true;
  1172. { add implicit entry and exit code }
  1173. add_entry_exit_code;
  1174. { only do secondpass if there are no errors }
  1175. if (ErrorCount=0) then
  1176. begin
  1177. create_hlcodegen;
  1178. if (procdef.proctypeoption<>potype_exceptfilter) then
  1179. setup_tempgen;
  1180. { Create register allocator, must come after framepointer is known }
  1181. hlcg.init_register_allocators;
  1182. generate_parameter_info;
  1183. { allocate got register if needed }
  1184. allocate_got_register(aktproccode);
  1185. { Allocate space in temp/registers for parast and localst }
  1186. current_filepos:=entrypos;
  1187. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1188. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1189. { Store temp offset for information about 'real' temps }
  1190. tempstart:=tg.lasttemp;
  1191. { Generate code to load register parameters in temps and insert local
  1192. copies for values parameters. This must be done before the code for the
  1193. body is generated because the localloc is updated.
  1194. Note: The generated code will be inserted after the code generation of
  1195. the body is finished, because only then the position is known }
  1196. {$ifdef oldregvars}
  1197. assign_regvars(code);
  1198. {$endif oldreg}
  1199. current_filepos:=entrypos;
  1200. hlcg.gen_load_para_value(templist);
  1201. { caller paraloc info is also necessary in the stackframe_entry
  1202. code of the ppc (and possibly other processors) }
  1203. procdef.init_paraloc_info(callerside);
  1204. { generate code for the node tree }
  1205. do_secondpass(code);
  1206. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1207. { The position of the loadpara_asmnode is now known }
  1208. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1209. { first generate entry and initialize code with the correct
  1210. position and switches }
  1211. current_filepos:=entrypos;
  1212. current_settings.localswitches:=entryswitches;
  1213. cg.set_regalloc_live_range_direction(rad_backwards);
  1214. hlcg.gen_entry_code(templist);
  1215. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1216. hlcg.gen_initialize_code(templist);
  1217. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1218. { now generate finalize and exit code with the correct position
  1219. and switches }
  1220. current_filepos:=exitpos;
  1221. current_settings.localswitches:=exitswitches;
  1222. cg.set_regalloc_live_range_direction(rad_forward);
  1223. if assigned(finalize_procinfo) then
  1224. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  1225. else
  1226. begin
  1227. hlcg.gen_finalize_code(templist);
  1228. { the finalcode must be concated if there was no position available,
  1229. using insertlistafter will result in an insert at the start
  1230. when currentai=nil }
  1231. if assigned(final_asmnode) and assigned(final_asmnode.currenttai) then
  1232. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  1233. else
  1234. aktproccode.concatlist(templist);
  1235. end;
  1236. { insert exit label at the correct position }
  1237. hlcg.a_label(templist,CurrExitLabel);
  1238. if assigned(exitlabel_asmnode.currenttai) then
  1239. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1240. else
  1241. aktproccode.concatlist(templist);
  1242. { exit code }
  1243. hlcg.gen_exit_code(templist);
  1244. aktproccode.concatlist(templist);
  1245. {$ifdef OLDREGVARS}
  1246. { note: this must be done only after as much code as possible has }
  1247. { been generated. The result is that when you ungetregister() a }
  1248. { regvar, it will actually free the regvar (and alse free the }
  1249. { the regvars at the same time). Doing this too early will }
  1250. { confuse the register allocator, as the regvars will still be }
  1251. { used. It should be done before loading the result regs (so }
  1252. { they don't conflict with the regvars) and before }
  1253. { gen_entry_code (that one has to be able to allocate the }
  1254. { regvars again) (JM) }
  1255. free_regvars(aktproccode);
  1256. {$endif OLDREGVARS}
  1257. { generate symbol and save end of header position }
  1258. current_filepos:=entrypos;
  1259. hlcg.gen_proc_symbol(templist);
  1260. headertai:=tai(templist.last);
  1261. { insert symbol }
  1262. aktproccode.insertlist(templist);
  1263. { Free space in temp/registers for parast and localst, must be
  1264. done after gen_entry_code }
  1265. current_filepos:=exitpos;
  1266. { make sure the got/pic register doesn't get freed in the }
  1267. { middle of a loop }
  1268. if (cs_create_pic in current_settings.moduleswitches) and
  1269. (pi_needs_got in flags) and
  1270. (got<>NR_NO) then
  1271. cg.a_reg_sync(aktproccode,got);
  1272. gen_free_symtable(aktproccode,procdef.localst);
  1273. gen_free_symtable(aktproccode,procdef.parast);
  1274. { add code that will load the return value, this is not done
  1275. for assembler routines when they didn't reference the result
  1276. variable }
  1277. hlcg.gen_load_return_value(templist);
  1278. aktproccode.concatlist(templist);
  1279. { Already reserve all registers for stack checking code and
  1280. generate the call to the helper function }
  1281. if not(tf_no_generic_stackcheck in target_info.flags) and
  1282. (cs_check_stack in entryswitches) and
  1283. not(po_assembler in procdef.procoptions) and
  1284. (procdef.proctypeoption<>potype_proginit) then
  1285. begin
  1286. current_filepos:=entrypos;
  1287. gen_stack_check_call(templist);
  1288. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1289. end;
  1290. { this code (got loading) comes before everything which has }
  1291. { already been generated, so reset the info about already }
  1292. { backwards extended registers (so their live range can be }
  1293. { extended backwards even further if needed) }
  1294. { This code must be }
  1295. { a) generated after do_secondpass has been called }
  1296. { (because pi_needs_got may be set there) }
  1297. { b) generated before register allocation, because the }
  1298. { got/pic register can be a virtual one }
  1299. { c) inserted before the entry code, because the entry }
  1300. { code may need global symbols such as init rtti }
  1301. { d) inserted after the stackframe allocation, because }
  1302. { this register may have to be spilled }
  1303. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1304. current_filepos:=entrypos;
  1305. { load got if necessary }
  1306. cg.g_maybe_got_init(templist);
  1307. aktproccode.insertlistafter(headertai,templist);
  1308. { re-enable if more code at the end is ever generated here
  1309. cg.set_regalloc_live_range_direction(rad_forward);
  1310. }
  1311. {$ifndef NoOpt}
  1312. {$ifndef i386}
  1313. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1314. { do not optimize pure assembler procedures }
  1315. not(pi_is_assembler in flags) then
  1316. preregallocschedule(aktproccode);
  1317. {$endif i386}
  1318. {$endif NoOpt}
  1319. { The procedure body is finished, we can now
  1320. allocate the registers }
  1321. cg.do_register_allocation(aktproccode,headertai);
  1322. { translate imag. register to their real counter parts
  1323. this is necessary for debuginfo and verbose assembler output
  1324. when SSA will be implented, this will be more complicated because we've to
  1325. maintain location lists }
  1326. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1327. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1328. if (cs_create_pic in current_settings.moduleswitches) and
  1329. (pi_needs_got in flags) and
  1330. not(cs_no_regalloc in current_settings.globalswitches) and
  1331. (got<>NR_NO) then
  1332. cg.translate_register(got);
  1333. { Add save and restore of used registers }
  1334. current_filepos:=entrypos;
  1335. gen_save_used_regs(templist);
  1336. { Remember the last instruction of register saving block
  1337. (may be =nil for e.g. assembler procedures) }
  1338. endprologue_ai:=templist.last;
  1339. aktproccode.insertlistafter(headertai,templist);
  1340. current_filepos:=exitpos;
  1341. gen_restore_used_regs(aktproccode);
  1342. { We know the size of the stack, now we can generate the
  1343. parameter that is passed to the stack checking code }
  1344. if not(tf_no_generic_stackcheck in target_info.flags) and
  1345. (cs_check_stack in entryswitches) and
  1346. not(po_assembler in procdef.procoptions) and
  1347. (procdef.proctypeoption<>potype_proginit) then
  1348. begin
  1349. current_filepos:=entrypos;
  1350. gen_stack_check_size_para(templist);
  1351. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1352. end;
  1353. { Add entry code (stack allocation) after header }
  1354. current_filepos:=entrypos;
  1355. gen_proc_entry_code(templist);
  1356. aktproccode.insertlistafter(headertai,templist);
  1357. {$ifdef SUPPORT_SAFECALL}
  1358. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1359. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1360. (tf_safecall_exceptions in target_info.flags) and
  1361. (procdef.proccalloption=pocall_safecall) then
  1362. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1363. {$endif}
  1364. { Add exit code at the end }
  1365. current_filepos:=exitpos;
  1366. gen_proc_exit_code(templist);
  1367. aktproccode.concatlist(templist);
  1368. { check if the implicit finally has been generated. The flag
  1369. should already be set in pass1 }
  1370. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1371. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1372. (pi_needs_implicit_finally in flags) and
  1373. not(po_assembler in procdef.procoptions) and
  1374. not(pi_has_implicit_finally in flags) and
  1375. not(target_info.system in systems_garbage_collected_managed_types) then
  1376. internalerror(200405231);
  1377. {$ifndef NoOpt}
  1378. if not(cs_no_regalloc in current_settings.globalswitches) then
  1379. begin
  1380. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1381. { do not optimize pure assembler procedures }
  1382. not(pi_is_assembler in flags) then
  1383. optimize(aktproccode);
  1384. {$ifndef i386}
  1385. { schedule after assembler optimization, it could have brought up
  1386. new schedule possibilities }
  1387. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1388. { do not optimize pure assembler procedures }
  1389. not(pi_is_assembler in flags) then
  1390. preregallocschedule(aktproccode);
  1391. {$endif i386}
  1392. end;
  1393. {$endif NoOpt}
  1394. {$ifdef ARM}
  1395. { because of the limited constant size of the arm, all data access is done pc relative }
  1396. finalizearmcode(aktproccode,aktlocaldata);
  1397. {$endif ARM}
  1398. {$ifdef AVR}
  1399. { because of the limited branch distance of cond. branches, they must be replaced
  1400. somtimes by normal jmps and an inverse branch }
  1401. finalizeavrcode(aktproccode);
  1402. {$endif AVR}
  1403. { Add end symbol and debug info }
  1404. { this must be done after the pcrelativedata is appended else the distance calculation of
  1405. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1406. so it should be inserted before the end symbol (FK)
  1407. }
  1408. current_filepos:=exitpos;
  1409. hlcg.gen_proc_symbol_end(templist);
  1410. aktproccode.concatlist(templist);
  1411. {$ifdef fpc_compiler_has_fixup_jmps}
  1412. fixup_jmps(aktproccode);
  1413. {$endif}
  1414. { insert line debuginfo }
  1415. if (cs_debuginfo in current_settings.moduleswitches) or
  1416. (cs_use_lineinfo in current_settings.globalswitches) then
  1417. current_debuginfo.insertlineinfo(aktproccode);
  1418. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  1419. { only now we can remove the temps }
  1420. if (procdef.proctypeoption<>potype_exceptfilter) then
  1421. begin
  1422. tg.resettempgen;
  1423. tg.free;
  1424. tg:=nil;
  1425. end;
  1426. { stop tempgen and ra }
  1427. hlcg.done_register_allocators;
  1428. destroy_hlcodegen;
  1429. end;
  1430. dfabuilder.free;
  1431. { restore symtablestack }
  1432. remove_from_symtablestack;
  1433. { restore }
  1434. templist.free;
  1435. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1436. current_filepos:=oldfilepos;
  1437. current_structdef:=old_current_structdef;
  1438. current_procinfo:=old_current_procinfo;
  1439. end;
  1440. procedure tcgprocinfo.add_to_symtablestack;
  1441. begin
  1442. { insert symtables for the class, but only if it is no nested function }
  1443. if assigned(procdef.struct) and
  1444. not(assigned(parent) and
  1445. assigned(parent.procdef) and
  1446. assigned(parent.procdef.struct)) then
  1447. push_nested_hierarchy(procdef.struct);
  1448. { insert parasymtable in symtablestack when parsing
  1449. a function }
  1450. if procdef.parast.symtablelevel>=normal_function_level then
  1451. symtablestack.push(procdef.parast);
  1452. { insert localsymtable, except for the main procedure
  1453. (in that case the localst is the unit's static symtable,
  1454. which is already on the stack) }
  1455. if procdef.localst.symtablelevel>=normal_function_level then
  1456. symtablestack.push(procdef.localst);
  1457. end;
  1458. procedure tcgprocinfo.remove_from_symtablestack;
  1459. begin
  1460. { remove localsymtable }
  1461. if procdef.localst.symtablelevel>=normal_function_level then
  1462. symtablestack.pop(procdef.localst);
  1463. { remove parasymtable }
  1464. if procdef.parast.symtablelevel>=normal_function_level then
  1465. symtablestack.pop(procdef.parast);
  1466. { remove symtables for the class, but only if it is no nested function }
  1467. if assigned(procdef.struct) and
  1468. not(assigned(parent) and
  1469. assigned(parent.procdef) and
  1470. assigned(parent.procdef.struct)) then
  1471. pop_nested_hierarchy(procdef.struct);
  1472. end;
  1473. procedure tcgprocinfo.resetprocdef;
  1474. begin
  1475. { remove code tree, if not inline procedure }
  1476. if assigned(code) then
  1477. begin
  1478. { the inline procedure has already got a copy of the tree
  1479. stored in procdef.inlininginfo }
  1480. code.free;
  1481. code:=nil;
  1482. end;
  1483. end;
  1484. procedure tcgprocinfo.parse_body;
  1485. var
  1486. old_current_procinfo : tprocinfo;
  1487. old_block_type : tblock_type;
  1488. st : TSymtable;
  1489. old_current_structdef: tabstractrecorddef;
  1490. old_current_genericdef,
  1491. old_current_specializedef: tstoreddef;
  1492. old_parse_generic: boolean;
  1493. begin
  1494. old_current_procinfo:=current_procinfo;
  1495. old_block_type:=block_type;
  1496. old_current_structdef:=current_structdef;
  1497. old_current_genericdef:=current_genericdef;
  1498. old_current_specializedef:=current_specializedef;
  1499. old_parse_generic:=parse_generic;
  1500. current_procinfo:=self;
  1501. current_structdef:=procdef.struct;
  1502. if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1503. begin
  1504. current_genericdef:=current_structdef;
  1505. parse_generic:=true;
  1506. end;
  1507. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1508. current_specializedef:=current_structdef;
  1509. { calculate the lexical level }
  1510. if procdef.parast.symtablelevel>maxnesting then
  1511. Message(parser_e_too_much_lexlevel);
  1512. block_type:=bt_body;
  1513. {$ifdef state_tracking}
  1514. { aktstate:=Tstate_storage.create;}
  1515. {$endif state_tracking}
  1516. { allocate the symbol for this procedure }
  1517. alloc_proc_symbol(procdef);
  1518. { add parast/localst to symtablestack }
  1519. add_to_symtablestack;
  1520. { save entry info }
  1521. entrypos:=current_filepos;
  1522. entryswitches:=current_settings.localswitches;
  1523. if (df_generic in procdef.defoptions) then
  1524. begin
  1525. { start token recorder for generic template }
  1526. procdef.initgeneric;
  1527. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1528. end;
  1529. { parse the code ... }
  1530. code:=block(current_module.islibrary);
  1531. if (df_generic in procdef.defoptions) then
  1532. begin
  1533. { stop token recorder for generic template }
  1534. current_scanner.stoprecordtokens;
  1535. { Give an error for accesses in the static symtable that aren't visible
  1536. outside the current unit }
  1537. st:=procdef.owner;
  1538. while (st.symtabletype=ObjectSymtable) do
  1539. st:=st.defowner.owner;
  1540. if (pi_uses_static_symtable in flags) and
  1541. (st.symtabletype<>staticsymtable) then
  1542. Comment(V_Error,'Global Generic template references static symtable');
  1543. end;
  1544. { save exit info }
  1545. exitswitches:=current_settings.localswitches;
  1546. exitpos:=last_endtoken_filepos;
  1547. { the procedure is now defined }
  1548. procdef.forwarddef:=false;
  1549. if assigned(code) then
  1550. begin
  1551. { get a better entry point }
  1552. entrypos:=code.fileinfo;
  1553. { Finish type checking pass }
  1554. do_typecheckpass(code);
  1555. if assigned(procdef.parentfpinitblock) then
  1556. begin
  1557. tblocknode(code).left:=cstatementnode.create(procdef.parentfpinitblock,tblocknode(code).left);
  1558. do_typecheckpass(tblocknode(code).left);
  1559. procdef.parentfpinitblock:=nil;
  1560. end;
  1561. end;
  1562. { Check for unused labels, forwards, symbols for procedures. Static
  1563. symtable is checked in pmodules.
  1564. The check must be done after the typecheckpass }
  1565. if (Errorcount=0) and
  1566. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1567. begin
  1568. { check if forwards are resolved }
  1569. tstoredsymtable(procdef.localst).check_forwards;
  1570. { check if all labels are used }
  1571. tstoredsymtable(procdef.localst).checklabels;
  1572. { check for unused symbols, but only if there is no asm block }
  1573. if not(pi_has_assembler_block in flags) then
  1574. begin
  1575. tstoredsymtable(procdef.localst).allsymbolsused;
  1576. tstoredsymtable(procdef.parast).allsymbolsused;
  1577. end;
  1578. end;
  1579. if (po_inline in procdef.procoptions) and
  1580. { Can we inline this procedure? }
  1581. checknodeinlining(procdef) then
  1582. CreateInlineInfo;
  1583. { Print the node to tree.log }
  1584. if paraprintnodetree=1 then
  1585. printproc( 'after parsing');
  1586. { ... remove symbol tables }
  1587. remove_from_symtablestack;
  1588. {$ifdef state_tracking}
  1589. { aktstate.destroy;}
  1590. {$endif state_tracking}
  1591. current_structdef:=old_current_structdef;
  1592. current_genericdef:=old_current_genericdef;
  1593. current_specializedef:=old_current_specializedef;
  1594. current_procinfo:=old_current_procinfo;
  1595. parse_generic:=old_parse_generic;
  1596. { Restore old state }
  1597. block_type:=old_block_type;
  1598. end;
  1599. {****************************************************************************
  1600. PROCEDURE/FUNCTION PARSING
  1601. ****************************************************************************}
  1602. procedure check_init_paras(p:TObject;arg:pointer);
  1603. begin
  1604. if tsym(p).typ<>paravarsym then
  1605. exit;
  1606. with tparavarsym(p) do
  1607. if is_managed_type(vardef) and
  1608. (varspez in [vs_value,vs_out]) then
  1609. include(current_procinfo.flags,pi_do_call);
  1610. end;
  1611. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1612. {
  1613. Parses the procedure directives, then parses the procedure body, then
  1614. generates the code for it
  1615. }
  1616. var
  1617. oldfailtokenmode : tmodeswitches;
  1618. isnestedproc : boolean;
  1619. begin
  1620. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1621. { create a new procedure }
  1622. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1623. current_module.procinfo:=current_procinfo;
  1624. current_procinfo.procdef:=pd;
  1625. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1626. { Insert mangledname }
  1627. pd.aliasnames.insert(pd.mangledname);
  1628. { Handle Export of this procedure }
  1629. if (po_exports in pd.procoptions) and
  1630. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1631. begin
  1632. pd.aliasnames.insert(pd.procsym.realname);
  1633. if cs_link_deffile in current_settings.globalswitches then
  1634. deffile.AddExport(pd.mangledname);
  1635. end;
  1636. { Insert result variables in the localst }
  1637. insert_funcret_local(pd);
  1638. { check if there are para's which require initing -> set }
  1639. { pi_do_call (if not yet set) }
  1640. if not(pi_do_call in current_procinfo.flags) then
  1641. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1642. { set _FAIL as keyword if constructor }
  1643. if (pd.proctypeoption=potype_constructor) then
  1644. begin
  1645. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1646. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  1647. end;
  1648. tcgprocinfo(current_procinfo).parse_body;
  1649. { We can't support inlining for procedures that have nested
  1650. procedures because the nested procedures use a fixed offset
  1651. for accessing locals in the parent procedure (PFV) }
  1652. if current_procinfo.has_nestedprocs then
  1653. begin
  1654. if (df_generic in current_procinfo.procdef.defoptions) then
  1655. Comment(V_Error,'Generic methods cannot have nested procedures')
  1656. else
  1657. if (po_inline in current_procinfo.procdef.procoptions) then
  1658. begin
  1659. Message1(parser_h_not_supported_for_inline,'nested procedures');
  1660. Message(parser_h_inlining_disabled);
  1661. exclude(current_procinfo.procdef.procoptions,po_inline);
  1662. end;
  1663. end;
  1664. { When it's a nested procedure then defer the code generation,
  1665. when back at normal function level then generate the code
  1666. for all defered nested procedures and the current procedure }
  1667. if not isnestedproc then
  1668. begin
  1669. if not(df_generic in current_procinfo.procdef.defoptions) then
  1670. tcgprocinfo(current_procinfo).generate_code_tree;
  1671. end;
  1672. { reset _FAIL as _SELF normal }
  1673. if (pd.proctypeoption=potype_constructor) then
  1674. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1675. { release procinfo }
  1676. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1677. internalerror(200304274);
  1678. current_module.procinfo:=current_procinfo.parent;
  1679. { For specialization we didn't record the last semicolon. Moving this parsing
  1680. into the parse_body routine is not done because of having better file position
  1681. information available }
  1682. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1683. consume(_SEMICOLON);
  1684. if not isnestedproc then
  1685. { current_procinfo is checked for nil later on }
  1686. freeandnil(current_procinfo);
  1687. end;
  1688. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef);
  1689. {
  1690. Parses the procedure directives, then parses the procedure body, then
  1691. generates the code for it
  1692. }
  1693. var
  1694. old_current_procinfo : tprocinfo;
  1695. old_current_structdef: tabstractrecorddef;
  1696. old_current_genericdef,
  1697. old_current_specializedef: tstoreddef;
  1698. pdflags : tpdflags;
  1699. pd,firstpd : tprocdef;
  1700. s : string;
  1701. begin
  1702. { save old state }
  1703. old_current_procinfo:=current_procinfo;
  1704. old_current_structdef:=current_structdef;
  1705. old_current_genericdef:=current_genericdef;
  1706. old_current_specializedef:=current_specializedef;
  1707. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1708. to another procdef }
  1709. current_procinfo:=nil;
  1710. current_structdef:=nil;
  1711. current_genericdef:=nil;
  1712. current_specializedef:=nil;
  1713. if not assigned(usefwpd) then
  1714. { parse procedure declaration }
  1715. pd:=parse_proc_dec(isclassmethod,old_current_structdef)
  1716. else
  1717. pd:=usefwpd;
  1718. { set the default function options }
  1719. if parse_only then
  1720. begin
  1721. pd.forwarddef:=true;
  1722. { set also the interface flag, for better error message when the
  1723. implementation doesn't much this header }
  1724. pd.interfacedef:=true;
  1725. include(pd.procoptions,po_global);
  1726. pdflags:=[pd_interface];
  1727. end
  1728. else
  1729. begin
  1730. pdflags:=[pd_body];
  1731. if (not current_module.in_interface) then
  1732. include(pdflags,pd_implemen);
  1733. if (not current_module.is_unit) or
  1734. create_smartlink then
  1735. include(pd.procoptions,po_global);
  1736. pd.forwarddef:=false;
  1737. end;
  1738. if not assigned(usefwpd) then
  1739. begin
  1740. { parse the directives that may follow }
  1741. parse_proc_directives(pd,pdflags);
  1742. { hint directives, these can be separated by semicolons here,
  1743. that needs to be handled here with a loop (PFV) }
  1744. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1745. Consume(_SEMICOLON);
  1746. { Set calling convention }
  1747. handle_calling_convention(pd);
  1748. end;
  1749. { search for forward declarations }
  1750. if not proc_add_definition(pd) then
  1751. begin
  1752. { A method must be forward defined (in the object declaration) }
  1753. if assigned(pd.struct) and
  1754. (not assigned(old_current_structdef)) then
  1755. begin
  1756. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1757. tprocsym(pd.procsym).write_parameter_lists(pd);
  1758. end
  1759. else
  1760. begin
  1761. { Give a better error if there is a forward def in the interface and only
  1762. a single implementation }
  1763. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1764. if (not pd.forwarddef) and
  1765. (not pd.interfacedef) and
  1766. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1767. firstpd.forwarddef and
  1768. firstpd.interfacedef and
  1769. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1770. { don't give an error if it may be an overload }
  1771. not(m_fpc in current_settings.modeswitches) and
  1772. (not(po_overload in pd.procoptions) or
  1773. not(po_overload in firstpd.procoptions)) then
  1774. begin
  1775. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1776. tprocsym(pd.procsym).write_parameter_lists(pd);
  1777. end;
  1778. end;
  1779. end;
  1780. { Set mangled name }
  1781. proc_set_mangledname(pd);
  1782. { compile procedure when a body is needed }
  1783. if (pd_body in pdflags) then
  1784. begin
  1785. read_proc_body(old_current_procinfo,pd);
  1786. end
  1787. else
  1788. begin
  1789. { Handle imports }
  1790. if (po_external in pd.procoptions) then
  1791. begin
  1792. { External declared in implementation, and there was already a
  1793. forward (or interface) declaration then we need to generate
  1794. a stub that calls the external routine }
  1795. if (not pd.forwarddef) and
  1796. (pd.hasforward)
  1797. { it is unclear to me what's the use of the following condition,
  1798. so commented out, see also issue #18371 (FK)
  1799. and
  1800. not(
  1801. assigned(pd.import_dll) and
  1802. (target_info.system in [system_i386_wdosx,
  1803. system_arm_wince,system_i386_wince])
  1804. ) } then
  1805. begin
  1806. s:=proc_get_importname(pd);
  1807. if s<>'' then
  1808. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,s);
  1809. end;
  1810. { Import DLL specified? }
  1811. if assigned(pd.import_dll) then
  1812. begin
  1813. if assigned (pd.import_name) then
  1814. current_module.AddExternalImport(pd.import_dll^,
  1815. pd.import_name^,proc_get_importname(pd),
  1816. pd.import_nr,false,false)
  1817. else
  1818. current_module.AddExternalImport(pd.import_dll^,
  1819. proc_get_importname(pd),proc_get_importname(pd),
  1820. pd.import_nr,false,true);
  1821. end
  1822. else
  1823. begin
  1824. { add import name to external list for DLL scanning }
  1825. if tf_has_dllscanner in target_info.flags then
  1826. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1827. end;
  1828. end;
  1829. end;
  1830. { make sure that references to forward-declared functions are not }
  1831. { treated as references to external symbols, needed for darwin. }
  1832. { make sure we don't change the binding of real external symbols }
  1833. if not(po_external in pd.procoptions) then
  1834. begin
  1835. if (po_global in pd.procoptions) or
  1836. (cs_profile in current_settings.moduleswitches) then
  1837. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1838. else
  1839. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1840. end;
  1841. current_structdef:=old_current_structdef;
  1842. current_genericdef:=old_current_genericdef;
  1843. current_specializedef:=old_current_specializedef;
  1844. current_procinfo:=old_current_procinfo;
  1845. end;
  1846. {****************************************************************************
  1847. DECLARATION PARSING
  1848. ****************************************************************************}
  1849. { search in symtablestack for not complete classes }
  1850. procedure check_forward_class(p:TObject;arg:pointer);
  1851. begin
  1852. if (tsym(p).typ=typesym) and
  1853. (ttypesym(p).typedef.typ=objectdef) and
  1854. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1855. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1856. end;
  1857. procedure read_declarations(islibrary : boolean);
  1858. var
  1859. is_classdef:boolean;
  1860. begin
  1861. is_classdef:=false;
  1862. repeat
  1863. if not assigned(current_procinfo) then
  1864. internalerror(200304251);
  1865. case token of
  1866. _LABEL:
  1867. label_dec;
  1868. _CONST:
  1869. const_dec;
  1870. _TYPE:
  1871. type_dec;
  1872. _VAR:
  1873. var_dec;
  1874. _THREADVAR:
  1875. threadvar_dec;
  1876. _CLASS:
  1877. begin
  1878. is_classdef:=false;
  1879. if try_to_consume(_CLASS) then
  1880. begin
  1881. { class modifier is only allowed for procedures, functions, }
  1882. { constructors, destructors }
  1883. if not(token in [_FUNCTION,_PROCEDURE,_CONSTRUCTOR,_DESTRUCTOR,_OPERATOR]) and
  1884. not((token=_ID) and (idtoken=_OPERATOR)) then
  1885. Message(parser_e_procedure_or_function_expected);
  1886. if is_interface(current_structdef) then
  1887. Message(parser_e_no_static_method_in_interfaces)
  1888. else
  1889. { class methods are also allowed for Objective-C protocols }
  1890. is_classdef:=true;
  1891. end;
  1892. end;
  1893. _CONSTRUCTOR,
  1894. _DESTRUCTOR,
  1895. _FUNCTION,
  1896. _PROCEDURE,
  1897. _OPERATOR:
  1898. begin
  1899. read_proc(is_classdef,nil);
  1900. is_classdef:=false;
  1901. end;
  1902. _EXPORTS:
  1903. begin
  1904. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1905. begin
  1906. Message(parser_e_syntax_error);
  1907. consume_all_until(_SEMICOLON);
  1908. end
  1909. else if islibrary or
  1910. (target_info.system in systems_unit_program_exports) then
  1911. read_exports
  1912. else
  1913. begin
  1914. Message(parser_w_unsupported_feature);
  1915. consume(_BEGIN);
  1916. end;
  1917. end
  1918. else
  1919. begin
  1920. case idtoken of
  1921. _RESOURCESTRING:
  1922. begin
  1923. { m_class is needed, because the resourcestring
  1924. loading is in the ObjPas unit }
  1925. { if (m_class in current_settings.modeswitches) then}
  1926. resourcestring_dec
  1927. { else
  1928. break;}
  1929. end;
  1930. _OPERATOR:
  1931. begin
  1932. if is_classdef then
  1933. begin
  1934. read_proc(is_classdef,nil);
  1935. is_classdef:=false;
  1936. end
  1937. else
  1938. break;
  1939. end;
  1940. _PROPERTY:
  1941. begin
  1942. if (m_fpc in current_settings.modeswitches) then
  1943. property_dec
  1944. else
  1945. break;
  1946. end;
  1947. else
  1948. break;
  1949. end;
  1950. end;
  1951. end;
  1952. until false;
  1953. { add implementations for synthetic method declarations added by
  1954. the compiler (not for unit/program init functions, their localst
  1955. is the staticst -> would duplicate the work done in pmodules) }
  1956. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  1957. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  1958. { check for incomplete class definitions, this is only required
  1959. for fpc modes }
  1960. if (m_fpc in current_settings.modeswitches) then
  1961. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1962. end;
  1963. procedure read_interface_declarations;
  1964. begin
  1965. repeat
  1966. case token of
  1967. _CONST :
  1968. const_dec;
  1969. _TYPE :
  1970. type_dec;
  1971. _VAR :
  1972. var_dec;
  1973. _THREADVAR :
  1974. threadvar_dec;
  1975. _FUNCTION,
  1976. _PROCEDURE,
  1977. _OPERATOR :
  1978. read_proc(false,nil);
  1979. else
  1980. begin
  1981. case idtoken of
  1982. _RESOURCESTRING :
  1983. resourcestring_dec;
  1984. _PROPERTY:
  1985. begin
  1986. if (m_fpc in current_settings.modeswitches) then
  1987. property_dec
  1988. else
  1989. break;
  1990. end;
  1991. else
  1992. break;
  1993. end;
  1994. end;
  1995. end;
  1996. until false;
  1997. { check for incomplete class definitions, this is only required
  1998. for fpc modes }
  1999. if (m_fpc in current_settings.modeswitches) then
  2000. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2001. end;
  2002. {****************************************************************************
  2003. SPECIALIZATION BODY GENERATION
  2004. ****************************************************************************}
  2005. procedure specialize_objectdefs(p:TObject;arg:pointer);
  2006. var
  2007. oldcurrent_filepos : tfileposinfo;
  2008. specobj : tabstractrecorddef;
  2009. state : tspecializationstate;
  2010. procedure process_abstractrecorddef(def:tabstractrecorddef);
  2011. var
  2012. i : longint;
  2013. hp : tdef;
  2014. hmodule : tmodule;
  2015. begin
  2016. hmodule:=find_module_from_symtable(def.genericdef.owner);
  2017. if hmodule=nil then
  2018. internalerror(201202041);
  2019. for i:=0 to def.symtable.DefList.Count-1 do
  2020. begin
  2021. hp:=tdef(def.symtable.DefList[i]);
  2022. if hp.typ=procdef then
  2023. begin
  2024. { only generate the code if we need a body }
  2025. if assigned(tprocdef(hp).struct) and not tprocdef(hp).forwarddef then
  2026. continue;
  2027. if assigned(tprocdef(hp).genericdef) and
  2028. (tprocdef(hp).genericdef.typ=procdef) and
  2029. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  2030. begin
  2031. oldcurrent_filepos:=current_filepos;
  2032. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  2033. { use the index the module got from the current compilation process }
  2034. current_filepos.moduleindex:=hmodule.unit_index;
  2035. current_tokenpos:=current_filepos;
  2036. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  2037. read_proc_body(nil,tprocdef(hp));
  2038. current_filepos:=oldcurrent_filepos;
  2039. end
  2040. { synthetic routines will be implemented afterwards }
  2041. else if tprocdef(hp).synthetickind=tsk_none then
  2042. MessagePos1(tprocdef(hp).fileinfo,sym_e_forward_not_resolved,tprocdef(hp).fullprocname(false));
  2043. end
  2044. else
  2045. if hp.typ in [objectdef,recorddef] then
  2046. { generate code for subtypes as well }
  2047. process_abstractrecorddef(tabstractrecorddef(hp));
  2048. end;
  2049. end;
  2050. begin
  2051. if not((tsym(p).typ=typesym) and
  2052. (ttypesym(p).typedef.typesym=tsym(p)) and
  2053. (ttypesym(p).typedef.typ in [objectdef,recorddef]) and
  2054. (df_specialization in ttypesym(p).typedef.defoptions)
  2055. ) then
  2056. exit;
  2057. { Setup symtablestack a definition time }
  2058. specobj:=tabstractrecorddef(ttypesym(p).typedef);
  2059. if not (is_class_or_object(specobj) or is_record(specobj) or is_javaclass(specobj)) then
  2060. exit;
  2061. specialization_init(specobj.genericdef,state);
  2062. { procedure definitions for classes or objects }
  2063. process_abstractrecorddef(specobj);
  2064. specialization_done(state);
  2065. end;
  2066. procedure generate_specialization_procs;
  2067. begin
  2068. if assigned(current_module.globalsymtable) then
  2069. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  2070. if assigned(current_module.localsymtable) then
  2071. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  2072. end;
  2073. end.