psub.pas 89 KB

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