psub.pas 87 KB

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