psub.pas 84 KB

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