psub.pas 95 KB

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