psub.pas 92 KB

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