psub.pas 103 KB

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