psub.pas 81 KB

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