psub.pas 83 KB

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