psub.pas 130 KB

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