psub.pas 82 KB

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