psub.pas 86 KB

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