psub.pas 129 KB

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