psub.pas 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256
  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. { finish the parentfpstruct (add padding, ...) }
  330. finish_parentfpstruct(current_procinfo.procdef);
  331. end;
  332. end;
  333. function block(islibrary : boolean) : tnode;
  334. begin
  335. { parse const,types and vars }
  336. read_declarations(islibrary);
  337. { do we have an assembler block without the po_assembler?
  338. we should allow this for Delphi compatibility (PFV) }
  339. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  340. include(current_procinfo.procdef.procoptions,po_assembler);
  341. { Handle assembler block different }
  342. if (po_assembler in current_procinfo.procdef.procoptions) then
  343. begin
  344. block:=assembler_block;
  345. exit;
  346. end;
  347. {Unit initialization?.}
  348. if (
  349. assigned(current_procinfo.procdef.localst) and
  350. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  351. (current_module.is_unit or islibrary)
  352. ) then
  353. begin
  354. if (token=_END) then
  355. begin
  356. consume(_END);
  357. { We need at least a node, else the entry/exit code is not
  358. generated and thus no PASCALMAIN symbol which we need (PFV) }
  359. if islibrary then
  360. block:=cnothingnode.create
  361. else
  362. block:=nil;
  363. end
  364. else
  365. begin
  366. if token=_INITIALIZATION then
  367. begin
  368. { The library init code is already called and does not
  369. need to be in the initfinal table (PFV) }
  370. block:=statement_block(_INITIALIZATION);
  371. end
  372. else if token=_FINALIZATION then
  373. begin
  374. { when a unit has only a finalization section, we can come to this
  375. point when we try to read the nonh existing initalization section
  376. so we've to check if we are really try to parse the finalization }
  377. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  378. block:=statement_block(_FINALIZATION)
  379. else
  380. block:=nil;
  381. end
  382. else
  383. block:=statement_block(_BEGIN);
  384. end;
  385. end
  386. else
  387. begin
  388. { parse routine body }
  389. block:=statement_block(_BEGIN);
  390. init_main_block_syms(block);
  391. end;
  392. end;
  393. {****************************************************************************
  394. PROCEDURE/FUNCTION COMPILING
  395. ****************************************************************************}
  396. procedure printnode_reset;
  397. begin
  398. assign(printnodefile,treelogfilename);
  399. {$push}{$I-}
  400. rewrite(printnodefile);
  401. {$pop}
  402. if ioresult<>0 then
  403. begin
  404. Comment(V_Error,'Error creating '+treelogfilename);
  405. exit;
  406. end;
  407. close(printnodefile);
  408. end;
  409. procedure add_label_init(p:TObject;arg:pointer);
  410. begin
  411. if tstoredsym(p).typ=labelsym then
  412. begin
  413. addstatement(tstatementnode(arg^),
  414. cifnode.create(caddnode.create(equaln,
  415. ccallnode.createintern('fpc_setjmp',
  416. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  417. cordconstnode.create(1,search_system_proc('fpc_setjmp').returndef,true))
  418. ,cgotonode.create(tlabelsym(p)),nil)
  419. );
  420. end;
  421. end;
  422. function generate_bodyentry_block:tnode;
  423. var
  424. srsym : tsym;
  425. para : tcallparanode;
  426. call : tcallnode;
  427. newstatement : tstatementnode;
  428. def : tabstractrecorddef;
  429. begin
  430. result:=internalstatements(newstatement);
  431. if assigned(current_structdef) then
  432. begin
  433. { a constructor needs a help procedure }
  434. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  435. begin
  436. if is_class(current_structdef) or
  437. (
  438. is_objectpascal_helper(current_structdef) and
  439. is_class(tobjectdef(current_structdef).extendeddef)
  440. ) then
  441. begin
  442. if is_objectpascal_helper(current_structdef) then
  443. def:=tabstractrecorddef(tobjectdef(current_structdef).extendeddef)
  444. else
  445. def:=current_structdef;
  446. srsym:=search_struct_member(def,'NEWINSTANCE');
  447. if assigned(srsym) and
  448. (srsym.typ=procsym) then
  449. begin
  450. { if vmt=1 then newinstance }
  451. addstatement(newstatement,cifnode.create(
  452. caddnode.create_internal(equaln,
  453. ctypeconvnode.create_internal(
  454. load_vmt_pointer_node,
  455. voidpointertype),
  456. cpointerconstnode.create(1,voidpointertype)),
  457. cassignmentnode.create(
  458. ctypeconvnode.create_internal(
  459. load_self_pointer_node,
  460. voidpointertype),
  461. ccallnode.create(nil,tprocsym(srsym),srsym.owner,
  462. ctypeconvnode.create_internal(load_self_pointer_node,cclassrefdef.create(current_structdef)),
  463. [],nil)),
  464. nil));
  465. end
  466. else
  467. internalerror(200305108);
  468. end
  469. else
  470. if is_object(current_structdef) then
  471. begin
  472. { parameter 3 : vmt_offset }
  473. { parameter 2 : address of pointer to vmt,
  474. this is required to allow setting the vmt to -1 to indicate
  475. that memory was allocated }
  476. { parameter 1 : self pointer }
  477. para:=ccallparanode.create(
  478. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  479. ccallparanode.create(
  480. ctypeconvnode.create_internal(
  481. load_vmt_pointer_node,
  482. voidpointertype),
  483. ccallparanode.create(
  484. ctypeconvnode.create_internal(
  485. load_self_pointer_node,
  486. voidpointertype),
  487. nil)));
  488. addstatement(newstatement,cassignmentnode.create(
  489. ctypeconvnode.create_internal(
  490. load_self_pointer_node,
  491. voidpointertype),
  492. ccallnode.createintern('fpc_help_constructor',para)));
  493. end
  494. else
  495. if is_javaclass(current_structdef) or
  496. ((target_info.system in systems_jvm) and
  497. is_record(current_structdef)) then
  498. begin
  499. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  500. not current_procinfo.ConstructorCallingConstructor then
  501. begin
  502. { call inherited constructor }
  503. if is_javaclass(current_structdef) then
  504. srsym:=search_struct_member_no_helper(tobjectdef(current_structdef).childof,'CREATE')
  505. else
  506. srsym:=search_struct_member_no_helper(java_fpcbaserecordtype,'CREATE');
  507. if assigned(srsym) and
  508. (srsym.typ=procsym) then
  509. begin
  510. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited],nil);
  511. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  512. addstatement(newstatement,call);
  513. end
  514. else
  515. internalerror(2011010312);
  516. end;
  517. end
  518. else
  519. if not is_record(current_structdef) and
  520. not (
  521. is_objectpascal_helper(current_structdef) and
  522. (tobjectdef(current_structdef).extendeddef.typ<>objectdef)
  523. ) then
  524. internalerror(200305103);
  525. { if self=nil then exit
  526. calling fail instead of exit is useless because
  527. there is nothing to dispose (PFV) }
  528. if is_class_or_object(current_structdef) then
  529. addstatement(newstatement,cifnode.create(
  530. caddnode.create(equaln,
  531. load_self_pointer_node,
  532. cnilnode.create),
  533. cexitnode.create(nil),
  534. nil));
  535. end;
  536. { maybe call BeforeDestruction for classes }
  537. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  538. is_class(current_structdef) then
  539. begin
  540. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  541. if assigned(srsym) and
  542. (srsym.typ=procsym) then
  543. begin
  544. { if vmt>0 then beforedestruction }
  545. addstatement(newstatement,cifnode.create(
  546. caddnode.create(gtn,
  547. ctypeconvnode.create_internal(
  548. load_vmt_pointer_node,ptrsinttype),
  549. ctypeconvnode.create_internal(
  550. cnilnode.create,ptrsinttype)),
  551. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  552. nil));
  553. end
  554. else
  555. internalerror(200305104);
  556. end;
  557. end;
  558. if m_non_local_goto in current_settings.modeswitches then
  559. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  560. end;
  561. function generate_bodyexit_block:tnode;
  562. var
  563. srsym : tsym;
  564. para : tcallparanode;
  565. newstatement : tstatementnode;
  566. oldlocalswitches: tlocalswitches;
  567. begin
  568. result:=internalstatements(newstatement);
  569. if assigned(current_structdef) then
  570. begin
  571. { Don't test self and the vmt here. The reason is that }
  572. { a constructor already checks whether these are valid }
  573. { before. Further, in case of TThread the thread may }
  574. { free the class instance right after AfterConstruction }
  575. { has been called, so it may no longer be valid (JM) }
  576. oldlocalswitches:=current_settings.localswitches;
  577. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  578. { a destructor needs a help procedure }
  579. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  580. begin
  581. if is_class(current_structdef) then
  582. begin
  583. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  584. if assigned(srsym) and
  585. (srsym.typ=procsym) then
  586. begin
  587. { if self<>0 and vmt<>0 then freeinstance }
  588. addstatement(newstatement,cifnode.create(
  589. caddnode.create(andn,
  590. caddnode.create(unequaln,
  591. load_self_pointer_node,
  592. cnilnode.create),
  593. caddnode.create(unequaln,
  594. ctypeconvnode.create(
  595. load_vmt_pointer_node,
  596. voidpointertype),
  597. cpointerconstnode.create(0,voidpointertype))),
  598. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  599. nil));
  600. end
  601. else
  602. internalerror(2003051001);
  603. end
  604. else
  605. if is_object(current_structdef) then
  606. begin
  607. { finalize object data, but only if not in inherited call }
  608. if is_managed_type(current_structdef) then
  609. begin
  610. addstatement(newstatement,cifnode.create(
  611. caddnode.create(unequaln,
  612. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  613. cnilnode.create),
  614. cnodeutils.finalize_data_node(load_self_node),
  615. nil));
  616. end;
  617. { parameter 3 : vmt_offset }
  618. { parameter 2 : pointer to vmt }
  619. { parameter 1 : self pointer }
  620. para:=ccallparanode.create(
  621. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  622. ccallparanode.create(
  623. ctypeconvnode.create_internal(
  624. load_vmt_pointer_node,
  625. voidpointertype),
  626. ccallparanode.create(
  627. ctypeconvnode.create_internal(
  628. load_self_pointer_node,
  629. voidpointertype),
  630. nil)));
  631. addstatement(newstatement,
  632. ccallnode.createintern('fpc_help_destructor',para));
  633. end
  634. else if is_javaclass(current_structdef) then
  635. begin
  636. { nothing to do }
  637. end
  638. else
  639. internalerror(200305105);
  640. end;
  641. current_settings.localswitches:=oldlocalswitches;
  642. end;
  643. end;
  644. {****************************************************************************
  645. TCGProcInfo
  646. ****************************************************************************}
  647. destructor tcgprocinfo.destroy;
  648. var
  649. i : longint;
  650. begin
  651. if assigned(tempinfo_flags_map) then
  652. begin
  653. for i:=0 to tempinfo_flags_map.count-1 do
  654. dispose(ptempinfo_flags_entry(tempinfo_flags_map[i]));
  655. tempinfo_flags_map.free;
  656. end;
  657. code.free;
  658. inherited destroy;
  659. end;
  660. function tcgprocinfo.calc_stackframe_size:longint;
  661. begin
  662. result:=Align(tg.direction*tg.lasttemp,current_settings.alignment.localalignmin);
  663. end;
  664. procedure tcgprocinfo.printproc(pass:string);
  665. begin
  666. assign(printnodefile,treelogfilename);
  667. {$push}{$I-}
  668. append(printnodefile);
  669. if ioresult<>0 then
  670. rewrite(printnodefile);
  671. {$pop}
  672. if ioresult<>0 then
  673. begin
  674. Comment(V_Error,'Error creating '+treelogfilename);
  675. exit;
  676. end;
  677. writeln(printnodefile);
  678. writeln(printnodefile,'*******************************************************************************');
  679. writeln(printnodefile, pass);
  680. writeln(printnodefile,procdef.fullprocname(false));
  681. writeln(printnodefile,'*******************************************************************************');
  682. printnode(printnodefile,code);
  683. close(printnodefile);
  684. end;
  685. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  686. var
  687. oldlocalswitches: tlocalswitches;
  688. srsym: tsym;
  689. constructionblock,
  690. exceptblock,
  691. newblock: tblocknode;
  692. newstatement: tstatementnode;
  693. pd: tprocdef;
  694. constructionsuccessful: tlocalvarsym;
  695. begin
  696. if assigned(procdef.struct) and
  697. (procdef.proctypeoption=potype_constructor) then
  698. begin
  699. withexceptblock:=
  700. withexceptblock and
  701. not(target_info.system in systems_garbage_collected_managed_types);
  702. { Don't test self and the vmt here. See generate_bodyexit_block }
  703. { why (JM) }
  704. oldlocalswitches:=current_settings.localswitches;
  705. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  706. { call AfterConstruction for classes }
  707. constructionsuccessful:=nil;
  708. if is_class(procdef.struct) then
  709. begin
  710. constructionsuccessful:=clocalvarsym.create(internaltypeprefixName[itp_vmt_afterconstruction_local],vs_value,ptrsinttype,[]);
  711. procdef.localst.insert(constructionsuccessful,false);
  712. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  713. if not assigned(srsym) or
  714. (srsym.typ<>procsym) then
  715. internalerror(200305106);
  716. current_filepos:=entrypos;
  717. constructionblock:=internalstatements(newstatement);
  718. { initialise constructionsuccessful with -1, indicating that
  719. the construction was not successful and hence
  720. beforedestruction should not be called if a destructor is
  721. called from the constructor }
  722. addstatement(newstatement,cassignmentnode.create(
  723. cloadnode.create(constructionsuccessful,procdef.localst),
  724. genintconstnode(-1))
  725. );
  726. { first execute all constructor code. If no exception
  727. occurred then we will execute afterconstruction,
  728. otherwise we won't (the exception will jump over us) }
  729. addstatement(newstatement,tocode);
  730. current_filepos:=exitpos;
  731. { if implicit finally node wasn't created, then exit label and
  732. finalization code must be handled here and placed before
  733. afterconstruction }
  734. if not ((pi_needs_implicit_finally in flags) and
  735. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  736. begin
  737. include(tocode.flags,nf_block_with_exit);
  738. if procdef.proctypeoption<>potype_exceptfilter then
  739. addstatement(newstatement,cfinalizetempsnode.create);
  740. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  741. temps_finalized:=true;
  742. end;
  743. { construction successful -> beforedestruction should be called
  744. if an exception happens now }
  745. addstatement(newstatement,cassignmentnode.create(
  746. cloadnode.create(constructionsuccessful,procdef.localst),
  747. genintconstnode(1))
  748. );
  749. { Self can be nil when fail is called }
  750. { if self<>nil and vmt<>nil then afterconstruction }
  751. addstatement(newstatement,cifnode.create(
  752. caddnode.create(andn,
  753. caddnode.create(unequaln,
  754. load_self_node,
  755. cnilnode.create),
  756. caddnode.create(unequaln,
  757. load_vmt_pointer_node,
  758. cnilnode.create)),
  759. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  760. nil));
  761. tocode:=constructionblock;
  762. end;
  763. if withexceptblock and (procdef.struct.typ=objectdef) then
  764. begin
  765. { Generate the implicit "fail" code for a constructor (destroy
  766. in case an exception happened) }
  767. pd:=tobjectdef(procdef.struct).find_destructor;
  768. { this will always be the case for classes, since tobject has
  769. a destructor }
  770. if assigned(pd) or is_object(procdef.struct) then
  771. begin
  772. current_filepos:=exitpos;
  773. exceptblock:=internalstatements(newstatement);
  774. { first free the instance if non-nil }
  775. if assigned(pd) then
  776. { if vmt<>0 then call destructor }
  777. addstatement(newstatement,
  778. cifnode.create(
  779. caddnode.create(unequaln,
  780. load_vmt_pointer_node,
  781. cnilnode.create),
  782. { cnf_create_failed -> don't call BeforeDestruction }
  783. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed],nil),
  784. nil))
  785. else
  786. { object without destructor, call 'fail' helper }
  787. addstatement(newstatement,
  788. ccallnode.createintern('fpc_help_fail',
  789. ccallparanode.create(
  790. cordconstnode.create(tobjectdef(procdef.struct).vmt_offset,s32inttype,false),
  791. ccallparanode.create(
  792. ctypeconvnode.create_internal(
  793. load_vmt_pointer_node,
  794. voidpointertype),
  795. ccallparanode.create(
  796. ctypeconvnode.create_internal(
  797. load_self_pointer_node,
  798. voidpointertype),
  799. nil))))
  800. );
  801. { then re-raise the exception }
  802. addstatement(newstatement,craisenode.create(nil,nil,nil));
  803. current_filepos:=entrypos;
  804. newblock:=internalstatements(newstatement);
  805. { try
  806. tocode
  807. except
  808. exceptblock
  809. end
  810. }
  811. addstatement(newstatement,ctryexceptnode.create(
  812. tocode,
  813. nil,
  814. exceptblock));
  815. tocode:=newblock;
  816. end;
  817. end;
  818. current_settings.localswitches:=oldlocalswitches;
  819. end;
  820. end;
  821. procedure tcgprocinfo.add_entry_exit_code;
  822. var
  823. finalcode,
  824. bodyentrycode,
  825. bodyexitcode,
  826. wrappedbody,
  827. newblock : tnode;
  828. codestatement,
  829. newstatement : tstatementnode;
  830. oldfilepos : tfileposinfo;
  831. is_constructor: boolean;
  832. begin
  833. is_constructor:=assigned(procdef.struct) and
  834. (procdef.proctypeoption=potype_constructor);
  835. oldfilepos:=current_filepos;
  836. { Generate code/locations used at start of proc }
  837. current_filepos:=entrypos;
  838. entry_asmnode:=casmnode.create_get_position;
  839. loadpara_asmnode:=casmnode.create_get_position;
  840. stackcheck_asmnode:=casmnode.create_get_position;
  841. init_asmnode:=casmnode.create_get_position;
  842. bodyentrycode:=generate_bodyentry_block;
  843. { Generate code/locations used at end of proc }
  844. current_filepos:=exitpos;
  845. exitlabel_asmnode:=casmnode.create_get_position;
  846. temps_finalized:=false;
  847. bodyexitcode:=generate_bodyexit_block;
  848. { Check if bodyexitcode is not empty }
  849. with tstatementnode(tblocknode(bodyexitcode).statements) do
  850. if (statement.nodetype<>nothingn) or assigned(next) then
  851. { Indicate that the extra code is executed after the exit statement }
  852. include(flowcontrol,fc_no_direct_exit);
  853. { Generate procedure by combining init+body+final,
  854. depending on the implicit finally we need to add
  855. an try...finally...end wrapper }
  856. current_filepos:=entrypos;
  857. newblock:=internalstatements(newstatement);
  858. { initialization is common for all cases }
  859. addstatement(newstatement,loadpara_asmnode);
  860. addstatement(newstatement,stackcheck_asmnode);
  861. addstatement(newstatement,entry_asmnode);
  862. cnodeutils.procdef_block_add_implicit_initialize_nodes(procdef,newstatement);
  863. addstatement(newstatement,init_asmnode);
  864. if assigned(procdef.parentfpinitblock) then
  865. begin
  866. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  867. begin
  868. { could be an asmn in case of a pure assembler procedure,
  869. but those shouldn't access nested variables }
  870. addstatement(newstatement,procdef.parentfpinitblock);
  871. end
  872. else
  873. procdef.parentfpinitblock.free;
  874. procdef.parentfpinitblock:=nil;
  875. end;
  876. addstatement(newstatement,bodyentrycode);
  877. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  878. (pi_needs_implicit_finally in flags) and
  879. { but it's useless in init/final code of units }
  880. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  881. not(target_info.system in systems_garbage_collected_managed_types) and
  882. (f_exceptions in features) then
  883. begin
  884. { Any result of managed type must be returned in parameter }
  885. if is_managed_type(procdef.returndef) and
  886. (not paramanager.ret_in_param(procdef.returndef,procdef)) and
  887. (not is_class(procdef.returndef)) then
  888. InternalError(2013121301);
  889. { Generate special exception block only needed when
  890. implicit finally is used }
  891. current_filepos:=exitpos;
  892. { Generate code that will be in the try...finally }
  893. finalcode:=internalstatements(codestatement);
  894. if procdef.proctypeoption<>potype_exceptfilter then
  895. addstatement(codestatement,cfinalizetempsnode.create);
  896. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,codestatement);
  897. temps_finalized:=true;
  898. current_filepos:=entrypos;
  899. wrappedbody:=ctryfinallynode.create_implicit(code,finalcode);
  900. { afterconstruction must be called after finalizetemps, because it
  901. has to execute after the temps have been finalised in case of a
  902. refcounted class (afterconstruction decreases the refcount
  903. without freeing the instance if the count becomes nil, while
  904. the finalising of the temps can free the instance) }
  905. maybe_add_constructor_wrapper(wrappedbody,true);
  906. addstatement(newstatement,wrappedbody);
  907. addstatement(newstatement,exitlabel_asmnode);
  908. addstatement(newstatement,bodyexitcode);
  909. { set flag the implicit finally has been generated }
  910. include(flags,pi_has_implicit_finally);
  911. end
  912. else
  913. begin
  914. { constructors need destroy-on-exception code even if they don't
  915. have managed variables/temps }
  916. maybe_add_constructor_wrapper(code,
  917. (cs_implicit_exceptions in current_settings.moduleswitches) and (f_exceptions in features));
  918. current_filepos:=entrypos;
  919. addstatement(newstatement,code);
  920. current_filepos:=exitpos;
  921. if assigned(nestedexitlabel) then
  922. addstatement(newstatement,clabelnode.create(cnothingnode.create,nestedexitlabel));
  923. addstatement(newstatement,exitlabel_asmnode);
  924. addstatement(newstatement,bodyexitcode);
  925. if not is_constructor then
  926. begin
  927. if procdef.proctypeoption<>potype_exceptfilter then
  928. addstatement(newstatement,cfinalizetempsnode.create);
  929. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  930. temps_finalized:=true;
  931. end;
  932. end;
  933. if not temps_finalized then
  934. begin
  935. current_filepos:=exitpos;
  936. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  937. end;
  938. do_firstpass(newblock);
  939. code:=newblock;
  940. current_filepos:=oldfilepos;
  941. end;
  942. procedure clearrefs(p:TObject;arg:pointer);
  943. begin
  944. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  945. if tabstractvarsym(p).refs>1 then
  946. tabstractvarsym(p).refs:=1;
  947. end;
  948. procedure translate_registers(p:TObject;list:pointer);
  949. begin
  950. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  951. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  952. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  953. begin
  954. if not(cs_no_regalloc in current_settings.globalswitches) then
  955. begin
  956. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  957. if (tabstractnormalvarsym(p).localloc.registerhi<>NR_NO) then
  958. cg.translate_register(tabstractnormalvarsym(p).localloc.registerhi);
  959. end;
  960. end;
  961. end;
  962. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(riscv32) or defined(riscv64) or defined(m68k)}
  963. const
  964. exception_flags: array[boolean] of tprocinfoflags = (
  965. [],
  966. [pi_uses_exceptions,pi_needs_implicit_finally,pi_has_implicit_finally]
  967. );
  968. {$endif}
  969. procedure tcgprocinfo.setup_tempgen;
  970. begin
  971. tg:=tgobjclass.create;
  972. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(m68k)}
  973. {$if defined(arm)}
  974. { frame and stack pointer must be always the same on arm thumb so it makes no
  975. sense to fiddle with a frame pointer }
  976. if GenerateThumbCode then
  977. begin
  978. framepointer:=NR_STACK_POINTER_REG;
  979. tg.direction:=1;
  980. end
  981. else
  982. {$endif defined(arm)}
  983. begin
  984. { try to strip the stack frame }
  985. { set the framepointer to esp if:
  986. - no assembler directive, those are handled in assembler_block
  987. in pstatment.pas (for cases not caught by the Delphi
  988. exception below)
  989. - no exceptions are used
  990. - no pushes are used/esp modifications, could be:
  991. * outgoing parameters on the stack on non-fixed stack target
  992. * incoming parameters on the stack
  993. * open arrays
  994. - no inline assembler
  995. or
  996. - Delphi mode
  997. - assembler directive
  998. - no pushes are used/esp modifications, could be:
  999. * outgoing parameters on the stack
  1000. * incoming parameters on the stack
  1001. * open arrays
  1002. - no local variables
  1003. - stack frame cannot be optimized if using Win64 SEH
  1004. (at least with the current state of our codegenerator).
  1005. }
  1006. if ((po_assembler in procdef.procoptions) and
  1007. (m_delphi in current_settings.modeswitches) and
  1008. { localst at main_program_level is a staticsymtable }
  1009. (procdef.localst.symtablelevel<>main_program_level) and
  1010. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  1011. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  1012. not(cs_generate_stackframes in current_settings.localswitches) and
  1013. not(cs_profile in current_settings.moduleswitches) and
  1014. not(po_assembler in procdef.procoptions) and
  1015. not ((pi_has_stackparameter in flags)
  1016. {$ifndef arm} { Outgoing parameter(s) on stack do not need stackframe on x86 targets
  1017. with fixed stack. On ARM it fails, see bug #25050 }
  1018. and (not paramanager.use_fixed_stack)
  1019. {$endif arm}
  1020. ) and
  1021. ((flags*([pi_has_assembler_block,pi_is_assembler,
  1022. pi_needs_stackframe]+
  1023. exception_flags[((target_info.cpu=cpu_i386) and (not paramanager.use_fixed_stack))
  1024. {$ifndef DISABLE_WIN64_SEH}
  1025. or (target_info.system=system_x86_64_win64)
  1026. {$endif DISABLE_WIN64_SEH}
  1027. ]))=[])
  1028. )
  1029. then
  1030. begin
  1031. { we need the parameter info here to determine if the procedure gets
  1032. parameters on the stack
  1033. calling generate_parameter_info doesn't hurt but it costs time
  1034. (necessary to init para_stack_size)
  1035. }
  1036. generate_parameter_info;
  1037. if not(procdef.stack_tainting_parameter(calleeside)) and
  1038. not(has_assembler_child)
  1039. { parasize must be really zero, this means also that no result may be returned
  1040. in a parameter }
  1041. and not((current_procinfo.procdef.proccalloption in clearstack_pocalls) and
  1042. not(current_procinfo.procdef.generate_safecall_wrapper) and
  1043. paramanager.ret_in_param(current_procinfo.procdef.returndef,current_procinfo.procdef)) then
  1044. begin
  1045. { Only need to set the framepointer }
  1046. framepointer:=NR_STACK_POINTER_REG;
  1047. tg.direction:=1;
  1048. end
  1049. {$if defined(arm)}
  1050. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1051. in case parameters are passed on the stack.
  1052. However, the draw back is, if the estimation fails, compilation will break later on
  1053. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1054. multipass compilation of subroutines must be supported
  1055. }
  1056. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1057. not(has_assembler_child) then
  1058. begin
  1059. { Only need to set the framepointer }
  1060. framepointer:=NR_STACK_POINTER_REG;
  1061. tg.direction:=1;
  1062. include(flags,pi_estimatestacksize);
  1063. set_first_temp_offset;
  1064. procdef.has_paraloc_info:=callnoside;
  1065. generate_parameter_info;
  1066. exit;
  1067. end;
  1068. {$endif defined(arm)}
  1069. end;
  1070. end;
  1071. {$endif defined(x86) or defined(arm) or defined(m68k)}
  1072. {$if defined(xtensa)}
  1073. { On xtensa, the stack frame size can be estimated to avoid using an extra frame pointer,
  1074. in case parameters are passed on the stack.
  1075. However, the draw back is, if the estimation fails, compilation will break later on
  1076. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1077. multipass compilation of subroutines must be supported
  1078. }
  1079. if procdef.stack_tainting_parameter(calleeside) then
  1080. begin
  1081. include(flags,pi_estimatestacksize);
  1082. set_first_temp_offset;
  1083. procdef.has_paraloc_info:=callnoside;
  1084. generate_parameter_info;
  1085. exit;
  1086. end;
  1087. {$endif defined(xtensa)}
  1088. { set the start offset to the start of the temp area in the stack }
  1089. set_first_temp_offset;
  1090. end;
  1091. procedure tcgprocinfo.OptimizeNodeTree;
  1092. var
  1093. i : integer;
  1094. RedoDFA: Boolean;
  1095. {RedoDFA : boolean;}
  1096. begin
  1097. { do this before adding the entry code else the tail recursion recognition won't work,
  1098. if this causes troubles, it must be if'ed
  1099. }
  1100. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1101. (pi_is_recursive in flags) then
  1102. do_opttail(code,procdef);
  1103. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1104. do_optconstpropagate(code);
  1105. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1106. { creating dfa is not always possible }
  1107. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1108. begin
  1109. dfabuilder:=TDFABuilder.Create;
  1110. dfabuilder.createdfainfo(code);
  1111. include(flags,pi_dfaavailable);
  1112. RedoDFA:=false;
  1113. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1114. { our induction variable strength reduction doesn't like
  1115. for loops with more than one entry }
  1116. and not(pi_has_label in flags) then
  1117. begin
  1118. RedoDFA:=OptimizeInductionVariables(code);
  1119. end;
  1120. if RedoDFA then
  1121. begin
  1122. dfabuilder.resetdfainfo(code);
  1123. dfabuilder.createdfainfo(code);
  1124. include(flags,pi_dfaavailable);
  1125. end;
  1126. if cs_opt_forloop in current_settings.optimizerswitches then
  1127. RedoDFA:=OptimizeForLoop(code);
  1128. RedoDFA:=ConvertForLoops(code) or RedoDFA;
  1129. if RedoDFA then
  1130. begin
  1131. dfabuilder.resetdfainfo(code);
  1132. dfabuilder.createdfainfo(code);
  1133. include(flags,pi_dfaavailable);
  1134. end;
  1135. { when life info is available, we can give more sophisticated warning about uninitialized
  1136. variables ...
  1137. ... but not for the finalization section of a unit, we would need global dfa to handle
  1138. it properly }
  1139. if potype_unitfinalize<>procdef.proctypeoption then
  1140. { iterate through life info of the first node }
  1141. for i:=0 to dfabuilder.nodemap.count-1 do
  1142. begin
  1143. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1144. begin
  1145. { do not warn for certain parameters: }
  1146. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1147. { do not warn about parameters passed by var }
  1148. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1149. { function result is passed by var but it must be initialized }
  1150. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1151. { do not warn about initialized hidden parameters }
  1152. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1153. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1154. end
  1155. else
  1156. begin
  1157. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1158. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1159. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1160. end;
  1161. end;
  1162. end
  1163. else
  1164. begin
  1165. ConvertForLoops(code);
  1166. end;
  1167. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1168. do_optdeadstoreelim(code);
  1169. if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
  1170. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1171. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1172. procdef.isempty:=true;
  1173. if cs_opt_nodecse in current_settings.optimizerswitches then
  1174. do_optcse(code);
  1175. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1176. do_optloadmodifystore(code);
  1177. if cs_opt_consts in current_settings.optimizerswitches then
  1178. do_consttovar(code);
  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. { only do secondpass if there are no errors }
  1777. if (ErrorCount<>0) then
  1778. begin
  1779. {$ifdef DEBUG_NODE_XML}
  1780. { Print out nodes as they appear after the first pass }
  1781. XMLPrintProc(False);
  1782. {$endif DEBUG_NODE_XML}
  1783. end
  1784. else
  1785. begin
  1786. create_hlcodegen;
  1787. setup_eh;
  1788. if (procdef.proctypeoption<>potype_exceptfilter) then
  1789. setup_tempgen;
  1790. { Create register allocator, must come after framepointer is known }
  1791. hlcg.init_register_allocators;
  1792. generate_parameter_info;
  1793. { allocate got register if needed }
  1794. allocate_got_register(aktproccode);
  1795. { allocate got register if needed }
  1796. allocate_tls_register(aktproccode);
  1797. { Allocate space in temp/registers for parast and localst }
  1798. current_filepos:=entrypos;
  1799. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1800. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1801. { Store temp offset for information about 'real' temps }
  1802. tempstart:=tg.lasttemp;
  1803. { Generate code to load register parameters in temps and insert local
  1804. copies for values parameters. This must be done before the code for the
  1805. body is generated because the localloc is updated.
  1806. Note: The generated code will be inserted after the code generation of
  1807. the body is finished, because only then the position is known }
  1808. {$ifdef oldregvars}
  1809. assign_regvars(code);
  1810. {$endif oldreg}
  1811. current_filepos:=entrypos;
  1812. hlcg.gen_load_para_value(templist);
  1813. { caller paraloc info is also necessary in the stackframe_entry
  1814. code of the ppc (and possibly other processors) }
  1815. procdef.init_paraloc_info(callerside);
  1816. CalcExecutionWeights(code);
  1817. { Print the node to tree.log }
  1818. if paraprintnodetree <> 0 then
  1819. printproc( 'right before code generation');
  1820. {$ifdef DEBUG_NODE_XML}
  1821. { Print out nodes as they appear after the first pass }
  1822. XMLPrintProc(False);
  1823. {$endif DEBUG_NODE_XML}
  1824. { generate code for the node tree }
  1825. do_secondpass(code);
  1826. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1827. { The position of the loadpara_asmnode is now known }
  1828. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1829. oldswitches:=current_settings.localswitches;
  1830. { first generate entry and initialize code with the correct
  1831. position and switches }
  1832. current_filepos:=entrypos;
  1833. current_settings.localswitches:=entryswitches;
  1834. cg.set_regalloc_live_range_direction(rad_backwards);
  1835. hlcg.gen_entry_code(templist);
  1836. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1837. hlcg.gen_initialize_code(templist);
  1838. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1839. { now generate finalize and exit code with the correct position
  1840. and switches }
  1841. current_filepos:=exitpos;
  1842. current_settings.localswitches:=exitswitches;
  1843. cg.set_regalloc_live_range_direction(rad_forward);
  1844. if assigned(finalize_procinfo) then
  1845. begin
  1846. if target_info.system in [system_aarch64_win64] then
  1847. tcgprocinfo(finalize_procinfo).store_tempflags
  1848. else
  1849. generate_exceptfilter(tcgprocinfo(finalize_procinfo));
  1850. end
  1851. else if not temps_finalized then
  1852. begin
  1853. hlcg.gen_finalize_code(templist);
  1854. { the finalcode must be concated if there was no position available,
  1855. using insertlistafter will result in an insert at the start
  1856. when currentai=nil }
  1857. aktproccode.concatlist(templist);
  1858. end;
  1859. { insert exit label at the correct position }
  1860. hlcg.a_label(templist,CurrExitLabel);
  1861. if assigned(exitlabel_asmnode.currenttai) then
  1862. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1863. else
  1864. aktproccode.concatlist(templist);
  1865. { exit code }
  1866. hlcg.gen_exit_code(templist);
  1867. aktproccode.concatlist(templist);
  1868. { reset switches }
  1869. current_settings.localswitches:=oldswitches;
  1870. {$ifdef OLDREGVARS}
  1871. { note: this must be done only after as much code as possible has }
  1872. { been generated. The result is that when you ungetregister() a }
  1873. { regvar, it will actually free the regvar (and alse free the }
  1874. { the regvars at the same time). Doing this too early will }
  1875. { confuse the register allocator, as the regvars will still be }
  1876. { used. It should be done before loading the result regs (so }
  1877. { they don't conflict with the regvars) and before }
  1878. { gen_entry_code (that one has to be able to allocate the }
  1879. { regvars again) (JM) }
  1880. free_regvars(aktproccode);
  1881. {$endif OLDREGVARS}
  1882. { generate symbol and save end of header position }
  1883. current_filepos:=entrypos;
  1884. hlcg.gen_proc_symbol(templist);
  1885. headertai:=tai(templist.last);
  1886. { insert symbol }
  1887. aktproccode.insertlist(templist);
  1888. { Free space in temp/registers for parast and localst, must be
  1889. done after gen_entry_code }
  1890. current_filepos:=exitpos;
  1891. { make sure the got/pic register doesn't get freed in the }
  1892. { middle of a loop }
  1893. if (tf_pic_uses_got in target_info.flags) and
  1894. (pi_needs_got in flags) and
  1895. (got<>NR_NO) then
  1896. cg.a_reg_sync(aktproccode,got);
  1897. if (pi_needs_tls in flags) and
  1898. (tlsoffset<>NR_NO) then
  1899. cg.a_reg_sync(aktproccode,tlsoffset);
  1900. gen_free_symtable(aktproccode,procdef.localst);
  1901. gen_free_symtable(aktproccode,procdef.parast);
  1902. { add code that will load the return value, this is not done
  1903. for assembler routines when they didn't reference the result
  1904. variable }
  1905. hlcg.gen_load_return_value(templist);
  1906. aktproccode.concatlist(templist);
  1907. { Already reserve all registers for stack checking code and
  1908. generate the call to the helper function }
  1909. if not(tf_no_generic_stackcheck in target_info.flags) and
  1910. (cs_check_stack in entryswitches) and
  1911. not(po_assembler in procdef.procoptions) and
  1912. (procdef.proctypeoption<>potype_proginit) then
  1913. begin
  1914. current_filepos:=entrypos;
  1915. hlcg.gen_stack_check_call(templist);
  1916. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1917. end;
  1918. { this code (got loading) comes before everything which has }
  1919. { already been generated, so reset the info about already }
  1920. { backwards extended registers (so their live range can be }
  1921. { extended backwards even further if needed) }
  1922. { This code must be }
  1923. { a) generated after do_secondpass has been called }
  1924. { (because pi_needs_got may be set there) }
  1925. { b) generated before register allocation, because the }
  1926. { got/pic register can be a virtual one }
  1927. { c) inserted before the entry code, because the entry }
  1928. { code may need global symbols such as init rtti }
  1929. { d) inserted after the stackframe allocation, because }
  1930. { this register may have to be spilled }
  1931. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1932. current_filepos:=entrypos;
  1933. { load got if necessary }
  1934. cg.g_maybe_got_init(templist);
  1935. aktproccode.insertlistafter(headertai,templist);
  1936. { init tls if needed }
  1937. cg.g_maybe_tls_init(templist);
  1938. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1939. { re-enable if more code at the end is ever generated here
  1940. cg.set_regalloc_live_range_direction(rad_forward);
  1941. }
  1942. {$ifndef NoOpt}
  1943. {$ifndef i386}
  1944. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1945. { do not optimize pure assembler procedures }
  1946. not(pi_is_assembler in flags) then
  1947. preregallocschedule(aktproccode);
  1948. {$endif i386}
  1949. {$endif NoOpt}
  1950. { The procedure body is finished, we can now
  1951. allocate the registers }
  1952. cg.do_register_allocation(aktproccode,headertai);
  1953. { translate imag. register to their real counter parts
  1954. this is necessary for debuginfo and verbose assembler output
  1955. when SSA will be implemented, this will be more complicated because we've to
  1956. maintain location lists }
  1957. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1958. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1959. if (tf_pic_uses_got in target_info.flags) and (pi_needs_got in flags) and
  1960. not(cs_no_regalloc in current_settings.globalswitches) and
  1961. (got<>NR_NO) then
  1962. cg.translate_register(got);
  1963. { Add save and restore of used registers }
  1964. current_filepos:=entrypos;
  1965. gen_save_used_regs(templist);
  1966. { Remember the last instruction of register saving block
  1967. (may be =nil for e.g. assembler procedures) }
  1968. endprologue_ai:=templist.last;
  1969. aktproccode.insertlistafter(headertai,templist);
  1970. current_filepos:=exitpos;
  1971. gen_restore_used_regs(aktproccode);
  1972. { We know the size of the stack, now we can generate the
  1973. parameter that is passed to the stack checking code }
  1974. if not(tf_no_generic_stackcheck in target_info.flags) and
  1975. (cs_check_stack in entryswitches) and
  1976. not(po_assembler in procdef.procoptions) and
  1977. (procdef.proctypeoption<>potype_proginit) then
  1978. begin
  1979. current_filepos:=entrypos;
  1980. hlcg.gen_stack_check_size_para(templist);
  1981. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1982. end;
  1983. current_procinfo.set_eh_info;
  1984. { Add entry code (stack allocation) after header }
  1985. current_filepos:=entrypos;
  1986. gen_proc_entry_code(templist);
  1987. aktproccode.insertlistafter(headertai,templist);
  1988. {$ifdef SUPPORT_SAFECALL}
  1989. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1990. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1991. (tf_safecall_exceptions in target_info.flags) and
  1992. (procdef.proccalloption=pocall_safecall) then
  1993. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1994. {$endif}
  1995. { Add exit code at the end }
  1996. current_filepos:=exitpos;
  1997. gen_proc_exit_code(templist);
  1998. aktproccode.concatlist(templist);
  1999. { check if the implicit finally has been generated. The flag
  2000. should already be set in pass1 }
  2001. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  2002. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  2003. (pi_needs_implicit_finally in flags) and
  2004. not(pi_has_implicit_finally in flags) and
  2005. not(target_info.system in systems_garbage_collected_managed_types) then
  2006. internalerror(200405231);
  2007. { sanity check }
  2008. if not(assigned(current_procinfo.procdef.personality)) and
  2009. (tf_use_psabieh in target_info.flags) and
  2010. ((pi_uses_exceptions in flags) or
  2011. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  2012. (pi_needs_implicit_finally in flags))) then
  2013. Internalerror(2019021005);
  2014. { Position markers are only used to insert additional code after the secondpass
  2015. and before this point. They are of no use in optimizer. Instead of checking and
  2016. ignoring all over the optimizer, just remove them here. }
  2017. delete_marker(entry_asmnode);
  2018. delete_marker(loadpara_asmnode);
  2019. delete_marker(exitlabel_asmnode);
  2020. delete_marker(stackcheck_asmnode);
  2021. delete_marker(init_asmnode);
  2022. {$ifndef NoOpt}
  2023. if not(cs_no_regalloc in current_settings.globalswitches) then
  2024. begin
  2025. if (cs_opt_level1 in current_settings.optimizerswitches) and
  2026. { do not optimize pure assembler procedures }
  2027. not(pi_is_assembler in flags) then
  2028. optimize(aktproccode);
  2029. {$ifndef i386}
  2030. { schedule after assembler optimization, it could have brought up
  2031. new schedule possibilities }
  2032. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  2033. { do not optimize pure assembler procedures }
  2034. not(pi_is_assembler in flags) then
  2035. preregallocschedule(aktproccode);
  2036. {$endif i386}
  2037. end;
  2038. {$endif NoOpt}
  2039. { Perform target-specific processing if necessary }
  2040. postprocess_code;
  2041. { Add end symbol and debug info }
  2042. { this must be done after the pcrelativedata is appended else the distance calculation of
  2043. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  2044. so it should be inserted before the end symbol (FK)
  2045. }
  2046. current_filepos:=exitpos;
  2047. hlcg.gen_proc_symbol_end(templist);
  2048. aktproccode.concatlist(templist);
  2049. { insert line debuginfo }
  2050. if (cs_debuginfo in current_settings.moduleswitches) or
  2051. (cs_use_lineinfo in current_settings.globalswitches) then
  2052. begin
  2053. { We only do this after the code generated because
  2054. otherwise for-loop counters moved to the struct cause
  2055. errors. And doing it before optimisation passes have run
  2056. causes problems when they manually look up symbols
  2057. like result and self (nutils.load_self_node etc). Still
  2058. do it nevertheless to to assist debug info generation
  2059. (hide original symbols, add absolutevarsyms that redirect
  2060. to their new locations in the parentfpstruct) }
  2061. if assigned(current_procinfo.procdef.parentfpstruct) then
  2062. redirect_parentfpstruct_local_syms(current_procinfo.procdef);
  2063. current_debuginfo.insertlineinfo(aktproccode);
  2064. end;
  2065. finish_eh;
  2066. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  2067. { now generate code for any exception filters (they need the tempgen) }
  2068. generate_code_exceptfilters;
  2069. { only now we can remove the temps }
  2070. if (procdef.proctypeoption<>potype_exceptfilter) then
  2071. begin
  2072. tg.resettempgen;
  2073. tg.free;
  2074. tg:=nil;
  2075. end;
  2076. { stop tempgen and ra }
  2077. hlcg.done_register_allocators;
  2078. destroy_hlcodegen;
  2079. end;
  2080. dfabuilder.free;
  2081. { restore symtablestack }
  2082. remove_from_symtablestack;
  2083. { restore }
  2084. templist.free;
  2085. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  2086. current_filepos:=oldfilepos;
  2087. current_structdef:=old_current_structdef;
  2088. current_procinfo:=old_current_procinfo;
  2089. end;
  2090. procedure tcgprocinfo.add_to_symtablestack;
  2091. begin
  2092. { insert symtables for the class, but only if it is no nested function }
  2093. if assigned(procdef.struct) and
  2094. not(assigned(parent) and
  2095. assigned(parent.procdef) and
  2096. assigned(parent.procdef.struct)) then
  2097. push_nested_hierarchy(procdef.struct);
  2098. { insert parasymtable in symtablestack when parsing
  2099. a function }
  2100. if procdef.parast.symtablelevel>=normal_function_level then
  2101. symtablestack.push(procdef.parast);
  2102. { insert localsymtable, except for the main procedure
  2103. (in that case the localst is the unit's static symtable,
  2104. which is already on the stack) }
  2105. if procdef.localst.symtablelevel>=normal_function_level then
  2106. symtablestack.push(procdef.localst);
  2107. end;
  2108. procedure tcgprocinfo.remove_from_symtablestack;
  2109. begin
  2110. { remove localsymtable }
  2111. if procdef.localst.symtablelevel>=normal_function_level then
  2112. symtablestack.pop(procdef.localst);
  2113. { remove parasymtable }
  2114. if procdef.parast.symtablelevel>=normal_function_level then
  2115. symtablestack.pop(procdef.parast);
  2116. { remove symtables for the class, but only if it is no nested function }
  2117. if assigned(procdef.struct) and
  2118. not(assigned(parent) and
  2119. assigned(parent.procdef) and
  2120. assigned(parent.procdef.struct)) then
  2121. pop_nested_hierarchy(procdef.struct);
  2122. end;
  2123. procedure tcgprocinfo.resetprocdef;
  2124. begin
  2125. { remove code tree, if not inline procedure }
  2126. if assigned(code) then
  2127. begin
  2128. { the inline procedure has already got a copy of the tree
  2129. stored in procdef.inlininginfo }
  2130. code.free;
  2131. code:=nil;
  2132. end;
  2133. end;
  2134. procedure tcgprocinfo.parse_body;
  2135. var
  2136. old_current_procinfo : tprocinfo;
  2137. old_block_type : tblock_type;
  2138. st : TSymtable;
  2139. old_current_structdef: tabstractrecorddef;
  2140. old_current_genericdef,
  2141. old_current_specializedef: tstoreddef;
  2142. parentfpinitblock: tnode;
  2143. old_parse_generic: boolean;
  2144. recordtokens : boolean;
  2145. begin
  2146. old_current_procinfo:=current_procinfo;
  2147. old_block_type:=block_type;
  2148. old_current_structdef:=current_structdef;
  2149. old_current_genericdef:=current_genericdef;
  2150. old_current_specializedef:=current_specializedef;
  2151. old_parse_generic:=parse_generic;
  2152. current_procinfo:=self;
  2153. current_structdef:=procdef.struct;
  2154. { check if the definitions of certain types are available which might not be available in older rtls and
  2155. which are assigned "on the fly" in types_dec }
  2156. {$if not defined(jvm) and not defined(wasm)}
  2157. if not assigned(rec_exceptaddr) then
  2158. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  2159. if not assigned(rec_tguid) then
  2160. Message1(cg_f_internal_type_not_found,'TGUID');
  2161. if not assigned(rec_jmp_buf) then
  2162. Message1(cg_f_internal_type_not_found,'JMP_BUF');
  2163. {$endif}
  2164. { if the procdef is truly a generic (thus takes parameters itself) then
  2165. /that/ is our genericdef, not the - potentially - generic struct }
  2166. if procdef.is_generic then
  2167. begin
  2168. current_genericdef:=procdef;
  2169. parse_generic:=true;
  2170. end
  2171. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  2172. begin
  2173. current_genericdef:=current_structdef;
  2174. parse_generic:=true;
  2175. end;
  2176. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  2177. current_specializedef:=current_structdef;
  2178. { calculate the lexical level }
  2179. if procdef.parast.symtablelevel>maxnesting then
  2180. Message(parser_e_too_much_lexlevel);
  2181. block_type:=bt_body;
  2182. {$ifdef state_tracking}
  2183. { aktstate:=Tstate_storage.create;}
  2184. {$endif state_tracking}
  2185. { allocate the symbol for this procedure }
  2186. alloc_proc_symbol(procdef);
  2187. { add parast/localst to symtablestack }
  2188. add_to_symtablestack;
  2189. { save entry info }
  2190. entrypos:=current_filepos;
  2191. entryswitches:=current_settings.localswitches;
  2192. recordtokens:=procdef.is_generic or
  2193. (
  2194. assigned(procdef.struct) and
  2195. (df_generic in procdef.struct.defoptions) and
  2196. assigned(procdef.owner) and
  2197. (procdef.owner.defowner=procdef.struct)
  2198. );
  2199. if recordtokens then
  2200. begin
  2201. { start token recorder for generic template }
  2202. procdef.initgeneric;
  2203. current_scanner.startrecordtokens(procdef.generictokenbuf);
  2204. end;
  2205. { parse the code ... }
  2206. code:=block(current_module.islibrary);
  2207. if recordtokens then
  2208. begin
  2209. { stop token recorder for generic template }
  2210. current_scanner.stoprecordtokens;
  2211. { Give an error for accesses in the static symtable that aren't visible
  2212. outside the current unit }
  2213. st:=procdef.owner;
  2214. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  2215. st:=st.defowner.owner;
  2216. if (pi_uses_static_symtable in flags) and
  2217. (st.symtabletype<>staticsymtable) then
  2218. Message(parser_e_global_generic_references_static);
  2219. end;
  2220. { save exit info }
  2221. exitswitches:=current_settings.localswitches;
  2222. exitpos:=last_endtoken_filepos;
  2223. { the procedure is now defined }
  2224. procdef.forwarddef:=false;
  2225. procdef.is_implemented:=true;
  2226. if assigned(code) then
  2227. begin
  2228. { get a better entry point }
  2229. entrypos:=code.fileinfo;
  2230. { Finish type checking pass }
  2231. do_typecheckpass(code);
  2232. if assigned(procdef.parentfpinitblock) then
  2233. begin
  2234. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  2235. begin
  2236. parentfpinitblock:=procdef.parentfpinitblock;
  2237. do_typecheckpass(parentfpinitblock);
  2238. procdef.parentfpinitblock:=parentfpinitblock;
  2239. end
  2240. end;
  2241. end;
  2242. { Check for unused labels, forwards, symbols for procedures. Static
  2243. symtable is checked in pmodules.
  2244. The check must be done after the typecheckpass }
  2245. if (Errorcount=0) and
  2246. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  2247. begin
  2248. { check if forwards are resolved }
  2249. tstoredsymtable(procdef.localst).check_forwards;
  2250. { check if all labels are used }
  2251. tstoredsymtable(procdef.localst).checklabels;
  2252. { check for unused symbols, but only if there is no asm block }
  2253. if not(pi_has_assembler_block in flags) then
  2254. begin
  2255. tstoredsymtable(procdef.localst).allsymbolsused;
  2256. tstoredsymtable(procdef.parast).allsymbolsused;
  2257. end;
  2258. end;
  2259. if (po_inline in procdef.procoptions) and
  2260. { Can we inline this procedure? }
  2261. checknodeinlining(procdef) then
  2262. CreateInlineInfo;
  2263. { Print the node to tree.log }
  2264. if paraprintnodetree <> 0 then
  2265. printproc( 'after parsing');
  2266. {$ifdef DEBUG_NODE_XML}
  2267. { Methods of generic classes don't get any code generated, so output
  2268. the node tree here }
  2269. if (df_generic in procdef.defoptions) then
  2270. XMLPrintProc(True);
  2271. {$endif DEBUG_NODE_XML}
  2272. { ... remove symbol tables }
  2273. remove_from_symtablestack;
  2274. {$ifdef state_tracking}
  2275. { aktstate.destroy;}
  2276. {$endif state_tracking}
  2277. current_structdef:=old_current_structdef;
  2278. current_genericdef:=old_current_genericdef;
  2279. current_specializedef:=old_current_specializedef;
  2280. current_procinfo:=old_current_procinfo;
  2281. parse_generic:=old_parse_generic;
  2282. { Restore old state }
  2283. block_type:=old_block_type;
  2284. end;
  2285. {****************************************************************************
  2286. PROCEDURE/FUNCTION PARSING
  2287. ****************************************************************************}
  2288. procedure check_init_paras(p:TObject;arg:pointer);
  2289. begin
  2290. if tsym(p).typ<>paravarsym then
  2291. exit;
  2292. with tparavarsym(p) do
  2293. if (is_managed_type(vardef) and
  2294. (varspez in [vs_value,vs_out])) or
  2295. (is_shortstring(vardef) and
  2296. (varspez=vs_value)) then
  2297. include(current_procinfo.flags,pi_do_call);
  2298. end;
  2299. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  2300. {
  2301. Parses the procedure directives, then parses the procedure body, then
  2302. generates the code for it
  2303. }
  2304. var
  2305. oldfailtokenmode : tmodeswitches;
  2306. isnestedproc : boolean;
  2307. begin
  2308. Message1(parser_d_procedure_start,pd.fullprocname(false));
  2309. oldfailtokenmode:=[];
  2310. { create a new procedure }
  2311. current_procinfo:=cprocinfo.create(old_current_procinfo);
  2312. current_module.procinfo:=current_procinfo;
  2313. current_procinfo.procdef:=pd;
  2314. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  2315. { Insert mangledname }
  2316. pd.aliasnames.insert(pd.mangledname);
  2317. { Handle Export of this procedure }
  2318. if (po_exports in pd.procoptions) and
  2319. (target_info.system in [system_i386_os2,system_i386_emx]) then
  2320. begin
  2321. pd.aliasnames.insert(pd.procsym.realname);
  2322. if cs_link_deffile in current_settings.globalswitches then
  2323. deffile.AddExport(pd.mangledname);
  2324. end;
  2325. { Insert result variables in the localst }
  2326. insert_funcret_local(pd);
  2327. { check if there are para's which require initing -> set }
  2328. { pi_do_call (if not yet set) }
  2329. if not(pi_do_call in current_procinfo.flags) then
  2330. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  2331. { set _FAIL as keyword if constructor }
  2332. if (pd.proctypeoption=potype_constructor) then
  2333. begin
  2334. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  2335. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  2336. end;
  2337. tcgprocinfo(current_procinfo).parse_body;
  2338. { reset _FAIL as _SELF normal }
  2339. if (pd.proctypeoption=potype_constructor) then
  2340. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  2341. { When it's a nested procedure then defer the code generation,
  2342. when back at normal function level then generate the code
  2343. for all defered nested procedures and the current procedure }
  2344. if not isnestedproc then
  2345. begin
  2346. if not(df_generic in current_procinfo.procdef.defoptions) then
  2347. begin
  2348. { also generate the bodies for all previously done
  2349. specializations so that we might inline them }
  2350. generate_specialization_procs;
  2351. tcgprocinfo(current_procinfo).generate_code_tree;
  2352. end;
  2353. end;
  2354. { release procinfo }
  2355. if tprocinfo(current_module.procinfo)<>current_procinfo then
  2356. internalerror(200304274);
  2357. current_module.procinfo:=current_procinfo.parent;
  2358. { For specialization we didn't record the last semicolon. Moving this parsing
  2359. into the parse_body routine is not done because of having better file position
  2360. information available }
  2361. if not current_procinfo.procdef.is_specialization and
  2362. (
  2363. not assigned(current_procinfo.procdef.struct) or
  2364. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  2365. or not (
  2366. assigned(current_procinfo.procdef.owner) and
  2367. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  2368. )
  2369. ) then
  2370. consume(_SEMICOLON);
  2371. if not isnestedproc then
  2372. { current_procinfo is checked for nil later on }
  2373. freeandnil(current_procinfo);
  2374. end;
  2375. procedure read_proc_body(pd:tprocdef);
  2376. var
  2377. old_module_procinfo : tobject;
  2378. old_current_procinfo : tprocinfo;
  2379. begin
  2380. old_current_procinfo:=current_procinfo;
  2381. old_module_procinfo:=current_module.procinfo;
  2382. current_procinfo:=nil;
  2383. current_module.procinfo:=nil;
  2384. read_proc_body(nil,pd);
  2385. current_procinfo:=old_current_procinfo;
  2386. current_module.procinfo:=old_module_procinfo;
  2387. end;
  2388. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  2389. {
  2390. Parses the procedure directives, then parses the procedure body, then
  2391. generates the code for it
  2392. }
  2393. var
  2394. old_current_procinfo : tprocinfo;
  2395. old_current_structdef: tabstractrecorddef;
  2396. old_current_genericdef,
  2397. old_current_specializedef: tstoreddef;
  2398. pdflags : tpdflags;
  2399. pd,firstpd : tprocdef;
  2400. {$ifdef genericdef_for_nested}
  2401. def : tprocdef;
  2402. srsym : tsym;
  2403. i : longint;
  2404. {$endif genericdef_for_nested}
  2405. begin
  2406. { save old state }
  2407. old_current_procinfo:=current_procinfo;
  2408. old_current_structdef:=current_structdef;
  2409. old_current_genericdef:=current_genericdef;
  2410. old_current_specializedef:=current_specializedef;
  2411. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  2412. to another procdef }
  2413. current_procinfo:=nil;
  2414. current_structdef:=nil;
  2415. current_genericdef:=nil;
  2416. current_specializedef:=nil;
  2417. if not assigned(usefwpd) then
  2418. { parse procedure declaration }
  2419. pd:=parse_proc_dec(isclassmethod,old_current_structdef,isgeneric)
  2420. else
  2421. pd:=usefwpd;
  2422. { set the default function options }
  2423. if parse_only then
  2424. begin
  2425. pd.forwarddef:=true;
  2426. { set also the interface flag, for better error message when the
  2427. implementation doesn't match this header }
  2428. pd.interfacedef:=true;
  2429. include(pd.procoptions,po_global);
  2430. pdflags:=[pd_interface];
  2431. end
  2432. else
  2433. begin
  2434. pdflags:=[pd_body];
  2435. if (not current_module.in_interface) then
  2436. include(pdflags,pd_implemen);
  2437. if (not current_module.is_unit) or
  2438. create_smartlink_library then
  2439. include(pd.procoptions,po_global);
  2440. pd.forwarddef:=false;
  2441. end;
  2442. if not assigned(usefwpd) then
  2443. begin
  2444. { parse the directives that may follow }
  2445. parse_proc_directives(pd,pdflags);
  2446. { hint directives, these can be separated by semicolons here,
  2447. that needs to be handled here with a loop (PFV) }
  2448. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  2449. Consume(_SEMICOLON);
  2450. { Set calling convention }
  2451. if parse_only then
  2452. handle_calling_convention(pd,hcc_default_actions_intf)
  2453. else
  2454. handle_calling_convention(pd,hcc_default_actions_impl)
  2455. end;
  2456. { search for forward declarations }
  2457. if not proc_add_definition(pd) then
  2458. begin
  2459. { One may not implement a method of a type declared in a different unit }
  2460. if assigned(pd.struct) and
  2461. (pd.struct.symtable.moduleid<>current_module.moduleid) and
  2462. not pd.is_specialization then
  2463. begin
  2464. MessagePos1(pd.fileinfo,parser_e_method_for_type_in_other_unit,pd.struct.typesymbolprettyname);
  2465. end
  2466. { A method must be forward defined (in the object declaration) }
  2467. else if assigned(pd.struct) and
  2468. (not assigned(old_current_structdef)) then
  2469. begin
  2470. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  2471. tprocsym(pd.procsym).write_parameter_lists(pd);
  2472. end
  2473. else
  2474. begin
  2475. { Give a better error if there is a forward def in the interface and only
  2476. a single implementation }
  2477. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  2478. if (not pd.forwarddef) and
  2479. (not pd.interfacedef) and
  2480. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  2481. firstpd.forwarddef and
  2482. firstpd.interfacedef and
  2483. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  2484. { don't give an error if it may be an overload }
  2485. not(m_fpc in current_settings.modeswitches) and
  2486. (not(po_overload in pd.procoptions) or
  2487. not(po_overload in firstpd.procoptions)) then
  2488. begin
  2489. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  2490. tprocsym(pd.procsym).write_parameter_lists(pd);
  2491. end
  2492. else
  2493. begin
  2494. if pd.is_generic and not assigned(pd.struct) then
  2495. tprocsym(pd.procsym).owner.includeoption(sto_has_generic);
  2496. end;
  2497. end;
  2498. end;
  2499. { Set mangled name }
  2500. proc_set_mangledname(pd);
  2501. { inherit generic flags from parent routine }
  2502. if assigned(old_current_procinfo) and
  2503. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2504. begin
  2505. if df_generic in old_current_procinfo.procdef.defoptions then
  2506. include(pd.defoptions,df_generic);
  2507. if df_specialization in old_current_procinfo.procdef.defoptions then
  2508. begin
  2509. include(pd.defoptions,df_specialization);
  2510. { the procdefs encountered here are nested procdefs of which
  2511. their complete definition also resides inside the current token
  2512. stream, thus access to their genericdef is not required }
  2513. {$ifdef genericdef_for_nested}
  2514. { find the corresponding routine in the generic routine }
  2515. if not assigned(old_current_procinfo.procdef.genericdef) then
  2516. internalerror(2016121701);
  2517. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(pd.procsym.name));
  2518. if not assigned(srsym) or (srsym.typ<>procsym) then
  2519. internalerror(2016121702);
  2520. { in practice the generic procdef should be at the same index
  2521. as the index of the current procdef, but as there *might* be
  2522. differences between the amount of defs generated for the
  2523. specialization and the generic search for the def using
  2524. parameter comparison }
  2525. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2526. begin
  2527. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2528. if (compare_paras(def.paras,pd.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2529. (compare_defs(def.returndef,pd.returndef,nothingn)=te_exact) then
  2530. begin
  2531. pd.genericdef:=def;
  2532. break;
  2533. end;
  2534. end;
  2535. if not assigned(pd.genericdef) then
  2536. internalerror(2016121703);
  2537. {$endif}
  2538. end;
  2539. end;
  2540. { compile procedure when a body is needed }
  2541. if (pd_body in pdflags) then
  2542. begin
  2543. read_proc_body(old_current_procinfo,pd);
  2544. end
  2545. else
  2546. begin
  2547. { Handle imports }
  2548. if (po_external in pd.procoptions) then
  2549. begin
  2550. import_external_proc(pd);
  2551. {$ifdef cpuhighleveltarget}
  2552. { it's hard to factor this out in a virtual method, because the
  2553. generic version (the one inside this ifdef) doesn't fit in
  2554. hlcgobj but in symcreat or here, while the other version
  2555. doesn't fit in symcreat (since it uses the code generator).
  2556. Maybe we need another class for this kind of code that could
  2557. either be symcreat- or hlcgobj-based
  2558. }
  2559. if (not pd.forwarddef) and
  2560. (pd.hasforward) and
  2561. (proc_get_importname(pd)<>'') then
  2562. begin
  2563. { we cannot handle the callee-side of variadic functions (and
  2564. even if we could, e.g. LLVM cannot call through to something
  2565. else in that case) }
  2566. if is_c_variadic(pd) then
  2567. Message1(parser_e_callthrough_varargs,pd.fullprocname(false));
  2568. call_through_new_name(pd,proc_get_importname(pd));
  2569. include(pd.implprocoptions,pio_thunk);
  2570. end
  2571. else
  2572. {$endif cpuhighleveltarget}
  2573. begin
  2574. create_hlcodegen;
  2575. hlcg.handle_external_proc(
  2576. current_asmdata.asmlists[al_procedures],
  2577. pd,
  2578. proc_get_importname(pd));
  2579. destroy_hlcodegen;
  2580. end
  2581. end;
  2582. end;
  2583. { always register public functions that are only declared in the
  2584. implementation section as they might be called using an external
  2585. declaration from another unit }
  2586. if (po_global in pd.procoptions) and
  2587. not pd.interfacedef and
  2588. ([df_generic,df_specialization]*pd.defoptions=[]) then
  2589. begin
  2590. pd.register_def;
  2591. pd.procsym.register_sym;
  2592. end;
  2593. { make sure that references to forward-declared functions are not }
  2594. { treated as references to external symbols, needed for darwin. }
  2595. { make sure we don't change the binding of real external symbols }
  2596. if (([po_external,po_weakexternal]*pd.procoptions)=[]) and (pocall_internproc<>pd.proccalloption) then
  2597. current_asmdata.DefineProcAsmSymbol(pd,pd.mangledname,pd.needsglobalasmsym);
  2598. current_structdef:=old_current_structdef;
  2599. current_genericdef:=old_current_genericdef;
  2600. current_specializedef:=old_current_specializedef;
  2601. current_procinfo:=old_current_procinfo;
  2602. end;
  2603. procedure import_external_proc(pd:tprocdef);
  2604. var
  2605. name : string;
  2606. begin
  2607. if not (po_external in pd.procoptions) then
  2608. internalerror(2015121101);
  2609. { Import DLL specified? }
  2610. if assigned(pd.import_dll) then
  2611. begin
  2612. if assigned (pd.import_name) then
  2613. current_module.AddExternalImport(pd.import_dll^,
  2614. pd.import_name^,proc_get_importname(pd),
  2615. pd.import_nr,false,false)
  2616. else
  2617. current_module.AddExternalImport(pd.import_dll^,
  2618. proc_get_importname(pd),proc_get_importname(pd),
  2619. pd.import_nr,false,true);
  2620. end
  2621. else
  2622. begin
  2623. name:=proc_get_importname(pd);
  2624. { add import name to external list for DLL scanning }
  2625. if tf_has_dllscanner in target_info.flags then
  2626. current_module.dllscannerinputlist.Add(name,pd);
  2627. { needed for units that use functions in packages this way }
  2628. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2629. end;
  2630. end;
  2631. {****************************************************************************
  2632. DECLARATION PARSING
  2633. ****************************************************************************}
  2634. { search in symtablestack for not complete classes }
  2635. procedure check_forward_class(p:TObject;arg:pointer);
  2636. begin
  2637. if (tsym(p).typ=typesym) and
  2638. (ttypesym(p).typedef.typ=objectdef) and
  2639. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2640. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2641. end;
  2642. {$ifdef DEBUG_NODE_XML}
  2643. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  2644. var
  2645. T: Text;
  2646. begin
  2647. Assign(T, current_module.ppxfilename);
  2648. {$push} {$I-}
  2649. Rewrite(T);
  2650. if IOResult<>0 then
  2651. begin
  2652. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2653. current_module.ppxfilefail := True;
  2654. Exit;
  2655. end;
  2656. {$pop}
  2657. { Mark the node dump file as available for writing }
  2658. current_module.ppxfilefail := False;
  2659. WriteLn(T, '<?xml version="1.0" encoding="utf-8"?>');
  2660. WriteLn(T, '<', RootName, ' name="', ModuleName, '">');
  2661. Close(T);
  2662. printnodeindention := printnodespacing;
  2663. end;
  2664. procedure XMLFinalizeNodeFile(RootName: shortstring);
  2665. var
  2666. T: Text;
  2667. begin
  2668. if current_module.ppxfilefail then
  2669. Exit;
  2670. current_module.ppxfilefail := True; { File is now considered closed no matter what happens }
  2671. Assign(T, current_module.ppxfilename);
  2672. {$push} {$I-}
  2673. Append(T);
  2674. if IOResult<>0 then
  2675. begin
  2676. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2677. Exit;
  2678. end;
  2679. {$pop}
  2680. WriteLn(T, '</', RootName, '>');
  2681. Close(T);
  2682. end;
  2683. {$endif DEBUG_NODE_XML}
  2684. procedure read_declarations(islibrary : boolean);
  2685. var
  2686. hadgeneric : boolean;
  2687. procedure handle_unexpected_had_generic;
  2688. begin
  2689. if hadgeneric then
  2690. begin
  2691. Message(parser_e_procedure_or_function_expected);
  2692. hadgeneric:=false;
  2693. end;
  2694. end;
  2695. var
  2696. is_classdef:boolean;
  2697. begin
  2698. is_classdef:=false;
  2699. hadgeneric:=false;
  2700. repeat
  2701. if not assigned(current_procinfo) then
  2702. internalerror(200304251);
  2703. case token of
  2704. _LABEL:
  2705. begin
  2706. handle_unexpected_had_generic;
  2707. label_dec;
  2708. end;
  2709. _CONST:
  2710. begin
  2711. handle_unexpected_had_generic;
  2712. const_dec(hadgeneric);
  2713. end;
  2714. _TYPE:
  2715. begin
  2716. handle_unexpected_had_generic;
  2717. type_dec(hadgeneric);
  2718. end;
  2719. _VAR:
  2720. begin
  2721. handle_unexpected_had_generic;
  2722. var_dec(hadgeneric);
  2723. end;
  2724. _THREADVAR:
  2725. begin
  2726. handle_unexpected_had_generic;
  2727. threadvar_dec(hadgeneric);
  2728. end;
  2729. _CLASS:
  2730. begin
  2731. is_classdef:=false;
  2732. if try_to_consume(_CLASS) then
  2733. begin
  2734. { class modifier is only allowed for procedures, functions, }
  2735. { constructors, destructors }
  2736. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2737. not((token=_ID) and (idtoken=_OPERATOR)) then
  2738. Message(parser_e_procedure_or_function_expected);
  2739. if is_interface(current_structdef) then
  2740. Message(parser_e_no_static_method_in_interfaces)
  2741. else
  2742. { class methods are also allowed for Objective-C protocols }
  2743. is_classdef:=true;
  2744. end;
  2745. end;
  2746. _CONSTRUCTOR,
  2747. _DESTRUCTOR,
  2748. _FUNCTION,
  2749. _PROCEDURE,
  2750. _OPERATOR:
  2751. begin
  2752. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2753. begin
  2754. Message(parser_e_procedure_or_function_expected);
  2755. hadgeneric:=false;
  2756. end;
  2757. read_proc(is_classdef,nil,hadgeneric);
  2758. is_classdef:=false;
  2759. hadgeneric:=false;
  2760. end;
  2761. _EXPORTS:
  2762. begin
  2763. handle_unexpected_had_generic;
  2764. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2765. begin
  2766. Message(parser_e_syntax_error);
  2767. consume_all_until(_SEMICOLON);
  2768. end
  2769. else if islibrary or
  2770. (target_info.system in systems_unit_program_exports) then
  2771. read_exports
  2772. else
  2773. begin
  2774. Message(parser_w_unsupported_feature);
  2775. consume(_BEGIN);
  2776. end;
  2777. end;
  2778. _PROPERTY:
  2779. begin
  2780. handle_unexpected_had_generic;
  2781. if (m_fpc in current_settings.modeswitches) then
  2782. property_dec
  2783. else
  2784. break;
  2785. end;
  2786. else
  2787. begin
  2788. case idtoken of
  2789. _RESOURCESTRING:
  2790. begin
  2791. handle_unexpected_had_generic;
  2792. { m_class is needed, because the resourcestring
  2793. loading is in the ObjPas unit }
  2794. { if (m_class in current_settings.modeswitches) then}
  2795. resourcestring_dec(hadgeneric)
  2796. { else
  2797. break;}
  2798. end;
  2799. _OPERATOR:
  2800. begin
  2801. handle_unexpected_had_generic;
  2802. if is_classdef then
  2803. begin
  2804. read_proc(is_classdef,nil,false);
  2805. is_classdef:=false;
  2806. end
  2807. else
  2808. break;
  2809. end;
  2810. _GENERIC:
  2811. begin
  2812. handle_unexpected_had_generic;
  2813. if not (m_delphi in current_settings.modeswitches) then
  2814. begin
  2815. consume(_ID);
  2816. hadgeneric:=true;
  2817. end
  2818. else
  2819. break;
  2820. end
  2821. else
  2822. break;
  2823. end;
  2824. end;
  2825. end;
  2826. until false;
  2827. { add implementations for synthetic method declarations added by
  2828. the compiler (not for unit/program init functions, their localst
  2829. is the staticst -> would duplicate the work done in pmodules) }
  2830. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  2831. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2832. { check for incomplete class definitions, this is only required
  2833. for fpc modes }
  2834. if (m_fpc in current_settings.modeswitches) then
  2835. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2836. end;
  2837. procedure read_interface_declarations;
  2838. var
  2839. hadgeneric : boolean;
  2840. procedure handle_unexpected_had_generic;
  2841. begin
  2842. if hadgeneric then
  2843. begin
  2844. Message(parser_e_procedure_or_function_expected);
  2845. hadgeneric:=false;
  2846. end;
  2847. end;
  2848. begin
  2849. hadgeneric:=false;
  2850. repeat
  2851. case token of
  2852. _CONST :
  2853. begin
  2854. handle_unexpected_had_generic;
  2855. const_dec(hadgeneric);
  2856. end;
  2857. _TYPE :
  2858. begin
  2859. handle_unexpected_had_generic;
  2860. type_dec(hadgeneric);
  2861. end;
  2862. _VAR :
  2863. begin
  2864. handle_unexpected_had_generic;
  2865. var_dec(hadgeneric);
  2866. end;
  2867. _THREADVAR :
  2868. begin
  2869. handle_unexpected_had_generic;
  2870. threadvar_dec(hadgeneric);
  2871. end;
  2872. _FUNCTION,
  2873. _PROCEDURE,
  2874. _OPERATOR :
  2875. begin
  2876. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2877. begin
  2878. message(parser_e_procedure_or_function_expected);
  2879. hadgeneric:=false;
  2880. end;
  2881. read_proc(false,nil,hadgeneric);
  2882. hadgeneric:=false;
  2883. end;
  2884. else
  2885. begin
  2886. case idtoken of
  2887. _RESOURCESTRING :
  2888. begin
  2889. handle_unexpected_had_generic;
  2890. resourcestring_dec(hadgeneric);
  2891. end;
  2892. _PROPERTY:
  2893. begin
  2894. handle_unexpected_had_generic;
  2895. if (m_fpc in current_settings.modeswitches) then
  2896. property_dec
  2897. else
  2898. break;
  2899. end;
  2900. _GENERIC:
  2901. begin
  2902. handle_unexpected_had_generic;
  2903. if not (m_delphi in current_settings.modeswitches) then
  2904. begin
  2905. hadgeneric:=true;
  2906. consume(_ID);
  2907. end
  2908. else
  2909. break;
  2910. end
  2911. else
  2912. break;
  2913. end;
  2914. end;
  2915. end;
  2916. until false;
  2917. { check for incomplete class definitions, this is only required
  2918. for fpc modes }
  2919. if (m_fpc in current_settings.modeswitches) then
  2920. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2921. end;
  2922. end.