psub.pas 131 KB

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