psub.pas 94 KB

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