psub.pas 123 KB

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