psub.pas 104 KB

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