psub.pas 90 KB

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