psub.pas 108 KB

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