psub.pas 82 KB

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