psub.pas 104 KB

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