psub.pas 123 KB

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