psub.pas 89 KB

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