psub.pas 126 KB

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