psub.pas 81 KB

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