psub.pas 114 KB

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