psub.pas 94 KB

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