psub.pas 95 KB

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