psub.pas 82 KB

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