psub.pas 115 KB

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