psub.pas 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941
  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. oldswitches : tlocalswitches;
  1350. templist : TAsmList;
  1351. headertai : tai;
  1352. i : integer;
  1353. {RedoDFA : boolean;}
  1354. procedure delete_marker(anode: tasmnode);
  1355. var
  1356. ai: tai;
  1357. begin
  1358. if assigned(anode) then
  1359. begin
  1360. ai:=anode.currenttai;
  1361. if assigned(ai) then
  1362. begin
  1363. aktproccode.remove(ai);
  1364. ai.free;
  1365. anode.currenttai:=nil;
  1366. end;
  1367. end;
  1368. end;
  1369. begin
  1370. { the initialization procedure can be empty, then we
  1371. don't need to generate anything. When it was an empty
  1372. procedure there would be at least a blocknode }
  1373. if not assigned(code) then
  1374. exit;
  1375. { We need valid code }
  1376. if Errorcount<>0 then
  1377. exit;
  1378. { No code can be generated for generic template }
  1379. if (df_generic in procdef.defoptions) then
  1380. internalerror(200511152);
  1381. { For regular procedures the RA and Tempgen shall not be available yet,
  1382. but exception filters reuse Tempgen of parent }
  1383. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1384. internalerror(200309201);
  1385. old_current_procinfo:=current_procinfo;
  1386. oldfilepos:=current_filepos;
  1387. old_current_structdef:=current_structdef;
  1388. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1389. current_procinfo:=self;
  1390. current_filepos:=entrypos;
  1391. current_structdef:=procdef.struct;
  1392. { store start of user code, it must be a block node, it will be used later one to
  1393. check variable lifeness }
  1394. include(code.flags,nf_usercode_entry);
  1395. { add wrapping code if necessary (initialization of typed constants on
  1396. some platforms, initing of local variables and out parameters with
  1397. trashing values, ...) }
  1398. { init/final code must be wrapped later (after code for main proc body
  1399. has been generated) }
  1400. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1401. code:=cnodeutils.wrap_proc_body(procdef,code);
  1402. { automatic inlining? }
  1403. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1404. { inlining not turned off? }
  1405. (cs_do_inline in current_settings.localswitches) and
  1406. not(po_noinline in procdef.procoptions) and
  1407. { no inlining yet? }
  1408. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1409. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1410. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1411. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1412. (not(procdef.proccalloption in [pocall_safecall])) and
  1413. { rough approximation if we should auto inline }
  1414. (node_count(code)<=10) then
  1415. begin
  1416. { Can we inline this procedure? }
  1417. if checknodeinlining(procdef) then
  1418. begin
  1419. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1420. include(procdef.procoptions,po_inline);
  1421. CreateInlineInfo;
  1422. end;
  1423. end;
  1424. templist:=TAsmList.create;
  1425. { add parast/localst to symtablestack }
  1426. add_to_symtablestack;
  1427. { clear register count }
  1428. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1429. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1430. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1431. if (procdef.localst.symtablelevel=main_program_level) and
  1432. (not current_module.is_unit) then
  1433. begin
  1434. include(flags,pi_do_call);
  1435. { the main program never returns due to the do_exit call }
  1436. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1437. include(procdef.procoptions,po_noreturn);
  1438. end;
  1439. { set implicit_finally flag when there are locals/paras to be finalized }
  1440. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1441. begin
  1442. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1443. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1444. end;
  1445. {$ifdef SUPPORT_SAFECALL}
  1446. { set implicit_finally flag for if procedure is safecall }
  1447. if (tf_safecall_exceptions in target_info.flags) and
  1448. (procdef.proccalloption=pocall_safecall) then
  1449. include(flags, pi_needs_implicit_finally);
  1450. {$endif}
  1451. { firstpass everything }
  1452. flowcontrol:=[];
  1453. do_firstpass(code);
  1454. {$if defined(i386) or defined(i8086)}
  1455. if node_resources_fpu(code)>0 then
  1456. include(flags,pi_uses_fpu);
  1457. {$endif i386 or i8086}
  1458. { Print the node to tree.log }
  1459. if paraprintnodetree <> 0 then
  1460. printproc( 'after the firstpass');
  1461. { do this before adding the entry code else the tail recursion recognition won't work,
  1462. if this causes troubles, it must be if'ed
  1463. }
  1464. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1465. (pi_is_recursive in flags) then
  1466. do_opttail(code,procdef);
  1467. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1468. do_optconstpropagate(code);
  1469. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1470. { creating dfa is not always possible }
  1471. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1472. begin
  1473. dfabuilder:=TDFABuilder.Create;
  1474. dfabuilder.createdfainfo(code);
  1475. include(flags,pi_dfaavailable);
  1476. { when life info is available, we can give more sophisticated warning about uninitialized
  1477. variables ...
  1478. ... but not for the finalization section of a unit, we would need global dfa to handle
  1479. it properly }
  1480. if potype_unitfinalize<>procdef.proctypeoption then
  1481. { iterate through life info of the first node }
  1482. for i:=0 to dfabuilder.nodemap.count-1 do
  1483. begin
  1484. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1485. begin
  1486. { do not warn for certain parameters: }
  1487. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1488. { do not warn about parameters passed by var }
  1489. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1490. { function result is passed by var but it must be initialized }
  1491. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1492. { do not warn about initialized hidden parameters }
  1493. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1494. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1495. end
  1496. else
  1497. begin
  1498. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1499. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1500. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1501. end;
  1502. end;
  1503. end;
  1504. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1505. do_optdeadstoreelim(code);
  1506. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1507. { our induction variable strength reduction doesn't like
  1508. for loops with more than one entry }
  1509. and not(pi_has_label in flags) then
  1510. begin
  1511. {RedoDFA:=}OptimizeInductionVariables(code);
  1512. end;
  1513. if (cs_opt_remove_emtpy_proc in current_settings.optimizerswitches) and
  1514. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1515. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1516. procdef.isempty:=true;
  1517. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1518. require a tls register, so check for such variables }
  1519. check_for_threadvars_in_initfinal;
  1520. { add implicit entry and exit code }
  1521. add_entry_exit_code;
  1522. if cs_opt_nodecse in current_settings.optimizerswitches then
  1523. do_optcse(code);
  1524. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1525. do_optloadmodifystore(code);
  1526. { only do secondpass if there are no errors }
  1527. if (ErrorCount=0) then
  1528. begin
  1529. create_hlcodegen;
  1530. setup_eh;
  1531. if (procdef.proctypeoption<>potype_exceptfilter) then
  1532. setup_tempgen;
  1533. { Create register allocator, must come after framepointer is known }
  1534. hlcg.init_register_allocators;
  1535. generate_parameter_info;
  1536. { allocate got register if needed }
  1537. allocate_got_register(aktproccode);
  1538. { allocate got register if needed }
  1539. allocate_tls_register(aktproccode);
  1540. { Allocate space in temp/registers for parast and localst }
  1541. current_filepos:=entrypos;
  1542. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1543. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1544. { Store temp offset for information about 'real' temps }
  1545. tempstart:=tg.lasttemp;
  1546. { Generate code to load register parameters in temps and insert local
  1547. copies for values parameters. This must be done before the code for the
  1548. body is generated because the localloc is updated.
  1549. Note: The generated code will be inserted after the code generation of
  1550. the body is finished, because only then the position is known }
  1551. {$ifdef oldregvars}
  1552. assign_regvars(code);
  1553. {$endif oldreg}
  1554. current_filepos:=entrypos;
  1555. hlcg.gen_load_para_value(templist);
  1556. { caller paraloc info is also necessary in the stackframe_entry
  1557. code of the ppc (and possibly other processors) }
  1558. procdef.init_paraloc_info(callerside);
  1559. CalcExecutionWeights(code);
  1560. { Print the node to tree.log }
  1561. if paraprintnodetree <> 0 then
  1562. printproc( 'right before code generation');
  1563. { generate code for the node tree }
  1564. do_secondpass(code);
  1565. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1566. { The position of the loadpara_asmnode is now known }
  1567. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1568. oldswitches:=current_settings.localswitches;
  1569. { first generate entry and initialize code with the correct
  1570. position and switches }
  1571. current_filepos:=entrypos;
  1572. current_settings.localswitches:=entryswitches;
  1573. cg.set_regalloc_live_range_direction(rad_backwards);
  1574. hlcg.gen_entry_code(templist);
  1575. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1576. hlcg.gen_initialize_code(templist);
  1577. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1578. { now generate finalize and exit code with the correct position
  1579. and switches }
  1580. current_filepos:=exitpos;
  1581. current_settings.localswitches:=exitswitches;
  1582. cg.set_regalloc_live_range_direction(rad_forward);
  1583. if assigned(finalize_procinfo) then
  1584. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  1585. else if not temps_finalized then
  1586. begin
  1587. hlcg.gen_finalize_code(templist);
  1588. { the finalcode must be concated if there was no position available,
  1589. using insertlistafter will result in an insert at the start
  1590. when currentai=nil }
  1591. aktproccode.concatlist(templist);
  1592. end;
  1593. { insert exit label at the correct position }
  1594. hlcg.a_label(templist,CurrExitLabel);
  1595. if assigned(exitlabel_asmnode.currenttai) then
  1596. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1597. else
  1598. aktproccode.concatlist(templist);
  1599. { exit code }
  1600. hlcg.gen_exit_code(templist);
  1601. aktproccode.concatlist(templist);
  1602. { reset switches }
  1603. current_settings.localswitches:=oldswitches;
  1604. {$ifdef OLDREGVARS}
  1605. { note: this must be done only after as much code as possible has }
  1606. { been generated. The result is that when you ungetregister() a }
  1607. { regvar, it will actually free the regvar (and alse free the }
  1608. { the regvars at the same time). Doing this too early will }
  1609. { confuse the register allocator, as the regvars will still be }
  1610. { used. It should be done before loading the result regs (so }
  1611. { they don't conflict with the regvars) and before }
  1612. { gen_entry_code (that one has to be able to allocate the }
  1613. { regvars again) (JM) }
  1614. free_regvars(aktproccode);
  1615. {$endif OLDREGVARS}
  1616. { generate symbol and save end of header position }
  1617. current_filepos:=entrypos;
  1618. hlcg.gen_proc_symbol(templist);
  1619. headertai:=tai(templist.last);
  1620. { insert symbol }
  1621. aktproccode.insertlist(templist);
  1622. { Free space in temp/registers for parast and localst, must be
  1623. done after gen_entry_code }
  1624. current_filepos:=exitpos;
  1625. { make sure the got/pic register doesn't get freed in the }
  1626. { middle of a loop }
  1627. if (tf_pic_uses_got in target_info.flags) and
  1628. (pi_needs_got in flags) and
  1629. (got<>NR_NO) then
  1630. cg.a_reg_sync(aktproccode,got);
  1631. if (pi_needs_tls in flags) and
  1632. (tlsoffset<>NR_NO) then
  1633. cg.a_reg_sync(aktproccode,tlsoffset);
  1634. gen_free_symtable(aktproccode,procdef.localst);
  1635. gen_free_symtable(aktproccode,procdef.parast);
  1636. { add code that will load the return value, this is not done
  1637. for assembler routines when they didn't reference the result
  1638. variable }
  1639. hlcg.gen_load_return_value(templist);
  1640. aktproccode.concatlist(templist);
  1641. { Already reserve all registers for stack checking code and
  1642. generate the call to the helper function }
  1643. if not(tf_no_generic_stackcheck in target_info.flags) and
  1644. (cs_check_stack in entryswitches) and
  1645. not(po_assembler in procdef.procoptions) and
  1646. (procdef.proctypeoption<>potype_proginit) then
  1647. begin
  1648. current_filepos:=entrypos;
  1649. hlcg.gen_stack_check_call(templist);
  1650. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1651. end;
  1652. { this code (got loading) comes before everything which has }
  1653. { already been generated, so reset the info about already }
  1654. { backwards extended registers (so their live range can be }
  1655. { extended backwards even further if needed) }
  1656. { This code must be }
  1657. { a) generated after do_secondpass has been called }
  1658. { (because pi_needs_got may be set there) }
  1659. { b) generated before register allocation, because the }
  1660. { got/pic register can be a virtual one }
  1661. { c) inserted before the entry code, because the entry }
  1662. { code may need global symbols such as init rtti }
  1663. { d) inserted after the stackframe allocation, because }
  1664. { this register may have to be spilled }
  1665. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1666. current_filepos:=entrypos;
  1667. { load got if necessary }
  1668. cg.g_maybe_got_init(templist);
  1669. aktproccode.insertlistafter(headertai,templist);
  1670. { init tls if needed }
  1671. cg.g_maybe_tls_init(templist);
  1672. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1673. { re-enable if more code at the end is ever generated here
  1674. cg.set_regalloc_live_range_direction(rad_forward);
  1675. }
  1676. {$ifndef NoOpt}
  1677. {$ifndef i386}
  1678. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1679. { do not optimize pure assembler procedures }
  1680. not(pi_is_assembler in flags) then
  1681. preregallocschedule(aktproccode);
  1682. {$endif i386}
  1683. {$endif NoOpt}
  1684. { The procedure body is finished, we can now
  1685. allocate the registers }
  1686. cg.do_register_allocation(aktproccode,headertai);
  1687. { translate imag. register to their real counter parts
  1688. this is necessary for debuginfo and verbose assembler output
  1689. when SSA will be implented, this will be more complicated because we've to
  1690. maintain location lists }
  1691. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1692. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1693. if (tf_pic_uses_got in target_info.flags) and (pi_needs_got in flags) and
  1694. not(cs_no_regalloc in current_settings.globalswitches) and
  1695. (got<>NR_NO) then
  1696. cg.translate_register(got);
  1697. { Add save and restore of used registers }
  1698. current_filepos:=entrypos;
  1699. gen_save_used_regs(templist);
  1700. { Remember the last instruction of register saving block
  1701. (may be =nil for e.g. assembler procedures) }
  1702. endprologue_ai:=templist.last;
  1703. aktproccode.insertlistafter(headertai,templist);
  1704. current_filepos:=exitpos;
  1705. gen_restore_used_regs(aktproccode);
  1706. { We know the size of the stack, now we can generate the
  1707. parameter that is passed to the stack checking code }
  1708. if not(tf_no_generic_stackcheck in target_info.flags) and
  1709. (cs_check_stack in entryswitches) and
  1710. not(po_assembler in procdef.procoptions) and
  1711. (procdef.proctypeoption<>potype_proginit) then
  1712. begin
  1713. current_filepos:=entrypos;
  1714. hlcg.gen_stack_check_size_para(templist);
  1715. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1716. end;
  1717. current_procinfo.set_eh_info;
  1718. { Add entry code (stack allocation) after header }
  1719. current_filepos:=entrypos;
  1720. gen_proc_entry_code(templist);
  1721. aktproccode.insertlistafter(headertai,templist);
  1722. {$ifdef SUPPORT_SAFECALL}
  1723. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1724. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1725. (tf_safecall_exceptions in target_info.flags) and
  1726. (procdef.proccalloption=pocall_safecall) then
  1727. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1728. {$endif}
  1729. { Add exit code at the end }
  1730. current_filepos:=exitpos;
  1731. gen_proc_exit_code(templist);
  1732. aktproccode.concatlist(templist);
  1733. { check if the implicit finally has been generated. The flag
  1734. should already be set in pass1 }
  1735. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1736. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1737. (pi_needs_implicit_finally in flags) and
  1738. not(pi_has_implicit_finally in flags) and
  1739. not(target_info.system in systems_garbage_collected_managed_types) then
  1740. internalerror(200405231);
  1741. { sanity check }
  1742. if not(assigned(current_procinfo.procdef.personality)) and
  1743. (tf_use_psabieh in target_info.flags) and
  1744. ((pi_uses_exceptions in flags) or
  1745. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1746. (pi_needs_implicit_finally in flags))) then
  1747. Internalerror(2019021005);
  1748. { Position markers are only used to insert additional code after the secondpass
  1749. and before this point. They are of no use in optimizer. Instead of checking and
  1750. ignoring all over the optimizer, just remove them here. }
  1751. delete_marker(entry_asmnode);
  1752. delete_marker(loadpara_asmnode);
  1753. delete_marker(exitlabel_asmnode);
  1754. delete_marker(stackcheck_asmnode);
  1755. delete_marker(init_asmnode);
  1756. {$ifndef NoOpt}
  1757. if not(cs_no_regalloc in current_settings.globalswitches) then
  1758. begin
  1759. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1760. { do not optimize pure assembler procedures }
  1761. not(pi_is_assembler in flags) then
  1762. optimize(aktproccode);
  1763. {$ifndef i386}
  1764. { schedule after assembler optimization, it could have brought up
  1765. new schedule possibilities }
  1766. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1767. { do not optimize pure assembler procedures }
  1768. not(pi_is_assembler in flags) then
  1769. preregallocschedule(aktproccode);
  1770. {$endif i386}
  1771. end;
  1772. {$endif NoOpt}
  1773. { Perform target-specific processing if necessary }
  1774. postprocess_code;
  1775. { Add end symbol and debug info }
  1776. { this must be done after the pcrelativedata is appended else the distance calculation of
  1777. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1778. so it should be inserted before the end symbol (FK)
  1779. }
  1780. current_filepos:=exitpos;
  1781. hlcg.gen_proc_symbol_end(templist);
  1782. aktproccode.concatlist(templist);
  1783. { insert line debuginfo }
  1784. if (cs_debuginfo in current_settings.moduleswitches) or
  1785. (cs_use_lineinfo in current_settings.globalswitches) then
  1786. current_debuginfo.insertlineinfo(aktproccode);
  1787. finish_eh;
  1788. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  1789. { only now we can remove the temps }
  1790. if (procdef.proctypeoption<>potype_exceptfilter) then
  1791. begin
  1792. tg.resettempgen;
  1793. tg.free;
  1794. tg:=nil;
  1795. end;
  1796. { stop tempgen and ra }
  1797. hlcg.done_register_allocators;
  1798. destroy_hlcodegen;
  1799. end;
  1800. dfabuilder.free;
  1801. { restore symtablestack }
  1802. remove_from_symtablestack;
  1803. { restore }
  1804. templist.free;
  1805. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1806. current_filepos:=oldfilepos;
  1807. current_structdef:=old_current_structdef;
  1808. current_procinfo:=old_current_procinfo;
  1809. end;
  1810. procedure tcgprocinfo.add_to_symtablestack;
  1811. begin
  1812. { insert symtables for the class, but only if it is no nested function }
  1813. if assigned(procdef.struct) and
  1814. not(assigned(parent) and
  1815. assigned(parent.procdef) and
  1816. assigned(parent.procdef.struct)) then
  1817. push_nested_hierarchy(procdef.struct);
  1818. { insert parasymtable in symtablestack when parsing
  1819. a function }
  1820. if procdef.parast.symtablelevel>=normal_function_level then
  1821. symtablestack.push(procdef.parast);
  1822. { insert localsymtable, except for the main procedure
  1823. (in that case the localst is the unit's static symtable,
  1824. which is already on the stack) }
  1825. if procdef.localst.symtablelevel>=normal_function_level then
  1826. symtablestack.push(procdef.localst);
  1827. end;
  1828. procedure tcgprocinfo.remove_from_symtablestack;
  1829. begin
  1830. { remove localsymtable }
  1831. if procdef.localst.symtablelevel>=normal_function_level then
  1832. symtablestack.pop(procdef.localst);
  1833. { remove parasymtable }
  1834. if procdef.parast.symtablelevel>=normal_function_level then
  1835. symtablestack.pop(procdef.parast);
  1836. { remove symtables for the class, but only if it is no nested function }
  1837. if assigned(procdef.struct) and
  1838. not(assigned(parent) and
  1839. assigned(parent.procdef) and
  1840. assigned(parent.procdef.struct)) then
  1841. pop_nested_hierarchy(procdef.struct);
  1842. end;
  1843. procedure tcgprocinfo.resetprocdef;
  1844. begin
  1845. { remove code tree, if not inline procedure }
  1846. if assigned(code) then
  1847. begin
  1848. { the inline procedure has already got a copy of the tree
  1849. stored in procdef.inlininginfo }
  1850. code.free;
  1851. code:=nil;
  1852. end;
  1853. end;
  1854. procedure tcgprocinfo.parse_body;
  1855. var
  1856. old_current_procinfo : tprocinfo;
  1857. old_block_type : tblock_type;
  1858. st : TSymtable;
  1859. old_current_structdef: tabstractrecorddef;
  1860. old_current_genericdef,
  1861. old_current_specializedef: tstoreddef;
  1862. parentfpinitblock: tnode;
  1863. old_parse_generic: boolean;
  1864. recordtokens : boolean;
  1865. begin
  1866. old_current_procinfo:=current_procinfo;
  1867. old_block_type:=block_type;
  1868. old_current_structdef:=current_structdef;
  1869. old_current_genericdef:=current_genericdef;
  1870. old_current_specializedef:=current_specializedef;
  1871. old_parse_generic:=parse_generic;
  1872. current_procinfo:=self;
  1873. current_structdef:=procdef.struct;
  1874. { check if the definitions of certain types are available which might not be available in older rtls and
  1875. which are assigned "on the fly" in types_dec }
  1876. {$ifndef jvm}
  1877. if not assigned(rec_exceptaddr) then
  1878. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  1879. if not assigned(rec_tguid) then
  1880. Message1(cg_f_internal_type_not_found,'TGUID');
  1881. if not assigned(rec_jmp_buf) then
  1882. Message1(cg_f_internal_type_not_found,'TJMPBUF');
  1883. {$endif}
  1884. { if the procdef is truly a generic (thus takes parameters itself) then
  1885. /that/ is our genericdef, not the - potentially - generic struct }
  1886. if procdef.is_generic then
  1887. begin
  1888. current_genericdef:=procdef;
  1889. parse_generic:=true;
  1890. end
  1891. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1892. begin
  1893. current_genericdef:=current_structdef;
  1894. parse_generic:=true;
  1895. end;
  1896. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1897. current_specializedef:=current_structdef;
  1898. { calculate the lexical level }
  1899. if procdef.parast.symtablelevel>maxnesting then
  1900. Message(parser_e_too_much_lexlevel);
  1901. block_type:=bt_body;
  1902. {$ifdef state_tracking}
  1903. { aktstate:=Tstate_storage.create;}
  1904. {$endif state_tracking}
  1905. { allocate the symbol for this procedure }
  1906. alloc_proc_symbol(procdef);
  1907. { add parast/localst to symtablestack }
  1908. add_to_symtablestack;
  1909. { save entry info }
  1910. entrypos:=current_filepos;
  1911. entryswitches:=current_settings.localswitches;
  1912. recordtokens:=procdef.is_generic or
  1913. (
  1914. assigned(procdef.struct) and
  1915. (df_generic in procdef.struct.defoptions) and
  1916. assigned(procdef.owner) and
  1917. (procdef.owner.defowner=procdef.struct)
  1918. );
  1919. if recordtokens then
  1920. begin
  1921. { start token recorder for generic template }
  1922. procdef.initgeneric;
  1923. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1924. end;
  1925. { parse the code ... }
  1926. code:=block(current_module.islibrary);
  1927. if recordtokens then
  1928. begin
  1929. { stop token recorder for generic template }
  1930. current_scanner.stoprecordtokens;
  1931. { Give an error for accesses in the static symtable that aren't visible
  1932. outside the current unit }
  1933. st:=procdef.owner;
  1934. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  1935. st:=st.defowner.owner;
  1936. if (pi_uses_static_symtable in flags) and
  1937. (st.symtabletype<>staticsymtable) then
  1938. Message(parser_e_global_generic_references_static);
  1939. end;
  1940. { save exit info }
  1941. exitswitches:=current_settings.localswitches;
  1942. exitpos:=last_endtoken_filepos;
  1943. { the procedure is now defined }
  1944. procdef.forwarddef:=false;
  1945. if assigned(code) then
  1946. begin
  1947. { get a better entry point }
  1948. entrypos:=code.fileinfo;
  1949. { Finish type checking pass }
  1950. do_typecheckpass(code);
  1951. if assigned(procdef.parentfpinitblock) then
  1952. begin
  1953. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  1954. begin
  1955. parentfpinitblock:=procdef.parentfpinitblock;
  1956. do_typecheckpass(parentfpinitblock);
  1957. procdef.parentfpinitblock:=parentfpinitblock;
  1958. end
  1959. end;
  1960. end;
  1961. { Check for unused labels, forwards, symbols for procedures. Static
  1962. symtable is checked in pmodules.
  1963. The check must be done after the typecheckpass }
  1964. if (Errorcount=0) and
  1965. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1966. begin
  1967. { check if forwards are resolved }
  1968. tstoredsymtable(procdef.localst).check_forwards;
  1969. { check if all labels are used }
  1970. tstoredsymtable(procdef.localst).checklabels;
  1971. { check for unused symbols, but only if there is no asm block }
  1972. if not(pi_has_assembler_block in flags) then
  1973. begin
  1974. tstoredsymtable(procdef.localst).allsymbolsused;
  1975. tstoredsymtable(procdef.parast).allsymbolsused;
  1976. end;
  1977. end;
  1978. if (po_inline in procdef.procoptions) and
  1979. { Can we inline this procedure? }
  1980. checknodeinlining(procdef) then
  1981. CreateInlineInfo;
  1982. { Print the node to tree.log }
  1983. if paraprintnodetree <> 0 then
  1984. printproc( 'after parsing');
  1985. {$ifdef DEBUG_NODE_XML}
  1986. printnodeindention := printnodespacing;
  1987. XMLPrintProc;
  1988. {$endif DEBUG_NODE_XML}
  1989. { ... remove symbol tables }
  1990. remove_from_symtablestack;
  1991. {$ifdef state_tracking}
  1992. { aktstate.destroy;}
  1993. {$endif state_tracking}
  1994. current_structdef:=old_current_structdef;
  1995. current_genericdef:=old_current_genericdef;
  1996. current_specializedef:=old_current_specializedef;
  1997. current_procinfo:=old_current_procinfo;
  1998. parse_generic:=old_parse_generic;
  1999. { Restore old state }
  2000. block_type:=old_block_type;
  2001. end;
  2002. {****************************************************************************
  2003. PROCEDURE/FUNCTION PARSING
  2004. ****************************************************************************}
  2005. procedure check_init_paras(p:TObject;arg:pointer);
  2006. begin
  2007. if tsym(p).typ<>paravarsym then
  2008. exit;
  2009. with tparavarsym(p) do
  2010. if (is_managed_type(vardef) and
  2011. (varspez in [vs_value,vs_out])) or
  2012. (is_shortstring(vardef) and
  2013. (varspez=vs_value)) then
  2014. include(current_procinfo.flags,pi_do_call);
  2015. end;
  2016. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  2017. {
  2018. Parses the procedure directives, then parses the procedure body, then
  2019. generates the code for it
  2020. }
  2021. var
  2022. oldfailtokenmode : tmodeswitches;
  2023. isnestedproc : boolean;
  2024. begin
  2025. Message1(parser_d_procedure_start,pd.fullprocname(false));
  2026. oldfailtokenmode:=[];
  2027. { create a new procedure }
  2028. current_procinfo:=cprocinfo.create(old_current_procinfo);
  2029. current_module.procinfo:=current_procinfo;
  2030. current_procinfo.procdef:=pd;
  2031. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  2032. { Insert mangledname }
  2033. pd.aliasnames.insert(pd.mangledname);
  2034. { Handle Export of this procedure }
  2035. if (po_exports in pd.procoptions) and
  2036. (target_info.system in [system_i386_os2,system_i386_emx]) then
  2037. begin
  2038. pd.aliasnames.insert(pd.procsym.realname);
  2039. if cs_link_deffile in current_settings.globalswitches then
  2040. deffile.AddExport(pd.mangledname);
  2041. end;
  2042. { Insert result variables in the localst }
  2043. insert_funcret_local(pd);
  2044. { check if there are para's which require initing -> set }
  2045. { pi_do_call (if not yet set) }
  2046. if not(pi_do_call in current_procinfo.flags) then
  2047. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  2048. { set _FAIL as keyword if constructor }
  2049. if (pd.proctypeoption=potype_constructor) then
  2050. begin
  2051. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  2052. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  2053. end;
  2054. tcgprocinfo(current_procinfo).parse_body;
  2055. { reset _FAIL as _SELF normal }
  2056. if (pd.proctypeoption=potype_constructor) then
  2057. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  2058. { When it's a nested procedure then defer the code generation,
  2059. when back at normal function level then generate the code
  2060. for all defered nested procedures and the current procedure }
  2061. if not isnestedproc then
  2062. begin
  2063. if not(df_generic in current_procinfo.procdef.defoptions) then
  2064. begin
  2065. { also generate the bodies for all previously done
  2066. specializations so that we might inline them }
  2067. generate_specialization_procs;
  2068. tcgprocinfo(current_procinfo).generate_code_tree;
  2069. end;
  2070. end;
  2071. { release procinfo }
  2072. if tprocinfo(current_module.procinfo)<>current_procinfo then
  2073. internalerror(200304274);
  2074. current_module.procinfo:=current_procinfo.parent;
  2075. { For specialization we didn't record the last semicolon. Moving this parsing
  2076. into the parse_body routine is not done because of having better file position
  2077. information available }
  2078. if not current_procinfo.procdef.is_specialization and
  2079. (
  2080. not assigned(current_procinfo.procdef.struct) or
  2081. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  2082. or not (
  2083. assigned(current_procinfo.procdef.owner) and
  2084. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  2085. )
  2086. ) then
  2087. consume(_SEMICOLON);
  2088. if not isnestedproc then
  2089. { current_procinfo is checked for nil later on }
  2090. freeandnil(current_procinfo);
  2091. end;
  2092. procedure read_proc_body(pd:tprocdef);
  2093. var
  2094. old_module_procinfo : tobject;
  2095. old_current_procinfo : tprocinfo;
  2096. begin
  2097. old_current_procinfo:=current_procinfo;
  2098. old_module_procinfo:=current_module.procinfo;
  2099. current_procinfo:=nil;
  2100. current_module.procinfo:=nil;
  2101. read_proc_body(nil,pd);
  2102. current_procinfo:=old_current_procinfo;
  2103. current_module.procinfo:=old_module_procinfo;
  2104. end;
  2105. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  2106. {
  2107. Parses the procedure directives, then parses the procedure body, then
  2108. generates the code for it
  2109. }
  2110. var
  2111. old_current_procinfo : tprocinfo;
  2112. old_current_structdef: tabstractrecorddef;
  2113. old_current_genericdef,
  2114. old_current_specializedef: tstoreddef;
  2115. pdflags : tpdflags;
  2116. pd,firstpd : tprocdef;
  2117. {$ifdef genericdef_for_nested}
  2118. def : tprocdef;
  2119. srsym : tsym;
  2120. i : longint;
  2121. {$endif genericdef_for_nested}
  2122. begin
  2123. { save old state }
  2124. old_current_procinfo:=current_procinfo;
  2125. old_current_structdef:=current_structdef;
  2126. old_current_genericdef:=current_genericdef;
  2127. old_current_specializedef:=current_specializedef;
  2128. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  2129. to another procdef }
  2130. current_procinfo:=nil;
  2131. current_structdef:=nil;
  2132. current_genericdef:=nil;
  2133. current_specializedef:=nil;
  2134. if not assigned(usefwpd) then
  2135. { parse procedure declaration }
  2136. pd:=parse_proc_dec(isclassmethod,old_current_structdef,isgeneric)
  2137. else
  2138. pd:=usefwpd;
  2139. { set the default function options }
  2140. if parse_only then
  2141. begin
  2142. pd.forwarddef:=true;
  2143. { set also the interface flag, for better error message when the
  2144. implementation doesn't match this header }
  2145. pd.interfacedef:=true;
  2146. include(pd.procoptions,po_global);
  2147. pdflags:=[pd_interface];
  2148. end
  2149. else
  2150. begin
  2151. pdflags:=[pd_body];
  2152. if (not current_module.in_interface) then
  2153. include(pdflags,pd_implemen);
  2154. if (not current_module.is_unit) or
  2155. create_smartlink_library then
  2156. include(pd.procoptions,po_global);
  2157. pd.forwarddef:=false;
  2158. end;
  2159. if not assigned(usefwpd) then
  2160. begin
  2161. { parse the directives that may follow }
  2162. parse_proc_directives(pd,pdflags);
  2163. { hint directives, these can be separated by semicolons here,
  2164. that needs to be handled here with a loop (PFV) }
  2165. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  2166. Consume(_SEMICOLON);
  2167. { Set calling convention }
  2168. if parse_only then
  2169. handle_calling_convention(pd,hcc_default_actions_intf)
  2170. else
  2171. handle_calling_convention(pd,hcc_default_actions_impl)
  2172. end;
  2173. { search for forward declarations }
  2174. if not proc_add_definition(pd) then
  2175. begin
  2176. { A method must be forward defined (in the object declaration) }
  2177. if assigned(pd.struct) and
  2178. (not assigned(old_current_structdef)) then
  2179. begin
  2180. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  2181. tprocsym(pd.procsym).write_parameter_lists(pd);
  2182. end
  2183. else
  2184. begin
  2185. { Give a better error if there is a forward def in the interface and only
  2186. a single implementation }
  2187. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  2188. if (not pd.forwarddef) and
  2189. (not pd.interfacedef) and
  2190. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  2191. firstpd.forwarddef and
  2192. firstpd.interfacedef and
  2193. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  2194. { don't give an error if it may be an overload }
  2195. not(m_fpc in current_settings.modeswitches) and
  2196. (not(po_overload in pd.procoptions) or
  2197. not(po_overload in firstpd.procoptions)) then
  2198. begin
  2199. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  2200. tprocsym(pd.procsym).write_parameter_lists(pd);
  2201. end
  2202. else
  2203. begin
  2204. if pd.is_generic and not assigned(pd.struct) then
  2205. tprocsym(pd.procsym).owner.includeoption(sto_has_generic);
  2206. end;
  2207. end;
  2208. end;
  2209. { Set mangled name }
  2210. proc_set_mangledname(pd);
  2211. { inherit generic flags from parent routine }
  2212. if assigned(old_current_procinfo) and
  2213. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2214. begin
  2215. if df_generic in old_current_procinfo.procdef.defoptions then
  2216. include(pd.defoptions,df_generic);
  2217. if df_specialization in old_current_procinfo.procdef.defoptions then
  2218. begin
  2219. include(pd.defoptions,df_specialization);
  2220. { the procdefs encountered here are nested procdefs of which
  2221. their complete definition also resides inside the current token
  2222. stream, thus access to their genericdef is not required }
  2223. {$ifdef genericdef_for_nested}
  2224. { find the corresponding routine in the generic routine }
  2225. if not assigned(old_current_procinfo.procdef.genericdef) then
  2226. internalerror(2016121701);
  2227. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(pd.procsym.name));
  2228. if not assigned(srsym) or (srsym.typ<>procsym) then
  2229. internalerror(2016121702);
  2230. { in practice the generic procdef should be at the same index
  2231. as the index of the current procdef, but as there *might* be
  2232. differences between the amount of defs generated for the
  2233. specialization and the generic search for the def using
  2234. parameter comparison }
  2235. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2236. begin
  2237. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2238. if (compare_paras(def.paras,pd.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2239. (compare_defs(def.returndef,pd.returndef,nothingn)=te_exact) then
  2240. begin
  2241. pd.genericdef:=def;
  2242. break;
  2243. end;
  2244. end;
  2245. if not assigned(pd.genericdef) then
  2246. internalerror(2016121703);
  2247. {$endif}
  2248. end;
  2249. end;
  2250. { compile procedure when a body is needed }
  2251. if (pd_body in pdflags) then
  2252. begin
  2253. read_proc_body(old_current_procinfo,pd);
  2254. end
  2255. else
  2256. begin
  2257. { Handle imports }
  2258. if (po_external in pd.procoptions) then
  2259. begin
  2260. import_external_proc(pd);
  2261. {$ifdef cpuhighleveltarget}
  2262. { it's hard to factor this out in a virtual method, because the
  2263. generic version (the one inside this ifdef) doesn't fit in
  2264. hlcgobj but in symcreat or here, while the other version
  2265. doesn't fit in symcreat (since it uses the code generator).
  2266. Maybe we need another class for this kind of code that could
  2267. either be symcreat- or hlcgobj-based
  2268. }
  2269. if (not pd.forwarddef) and
  2270. (pd.hasforward) and
  2271. (proc_get_importname(pd)<>'') then
  2272. begin
  2273. { we cannot handle the callee-side of variadic functions (and
  2274. even if we could, e.g. LLVM cannot call through to something
  2275. else in that case) }
  2276. if is_c_variadic(pd) then
  2277. Message1(parser_e_callthrough_varargs,pd.fullprocname(false));
  2278. call_through_new_name(pd,proc_get_importname(pd));
  2279. include(pd.implprocoptions,pio_thunk);
  2280. end
  2281. else
  2282. {$endif cpuhighleveltarget}
  2283. begin
  2284. create_hlcodegen;
  2285. hlcg.handle_external_proc(
  2286. current_asmdata.asmlists[al_procedures],
  2287. pd,
  2288. proc_get_importname(pd));
  2289. destroy_hlcodegen;
  2290. end
  2291. end;
  2292. end;
  2293. { always register public functions that are only declared in the
  2294. implementation section as they might be called using an external
  2295. declaration from another unit }
  2296. if (po_global in pd.procoptions) and
  2297. not pd.interfacedef and
  2298. ([df_generic,df_specialization]*pd.defoptions=[]) then
  2299. begin
  2300. pd.register_def;
  2301. pd.procsym.register_sym;
  2302. end;
  2303. { make sure that references to forward-declared functions are not }
  2304. { treated as references to external symbols, needed for darwin. }
  2305. { make sure we don't change the binding of real external symbols }
  2306. if (([po_external,po_weakexternal]*pd.procoptions)=[]) and (pocall_internproc<>pd.proccalloption) then
  2307. current_asmdata.DefineProcAsmSymbol(pd,pd.mangledname,pd.needsglobalasmsym);
  2308. current_structdef:=old_current_structdef;
  2309. current_genericdef:=old_current_genericdef;
  2310. current_specializedef:=old_current_specializedef;
  2311. current_procinfo:=old_current_procinfo;
  2312. end;
  2313. procedure import_external_proc(pd:tprocdef);
  2314. var
  2315. name : string;
  2316. begin
  2317. if not (po_external in pd.procoptions) then
  2318. internalerror(2015121101);
  2319. { Import DLL specified? }
  2320. if assigned(pd.import_dll) then
  2321. begin
  2322. if assigned (pd.import_name) then
  2323. current_module.AddExternalImport(pd.import_dll^,
  2324. pd.import_name^,proc_get_importname(pd),
  2325. pd.import_nr,false,false)
  2326. else
  2327. current_module.AddExternalImport(pd.import_dll^,
  2328. proc_get_importname(pd),proc_get_importname(pd),
  2329. pd.import_nr,false,true);
  2330. end
  2331. else
  2332. begin
  2333. name:=proc_get_importname(pd);
  2334. { add import name to external list for DLL scanning }
  2335. if tf_has_dllscanner in target_info.flags then
  2336. current_module.dllscannerinputlist.Add(name,pd);
  2337. { needed for units that use functions in packages this way }
  2338. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2339. end;
  2340. end;
  2341. {****************************************************************************
  2342. DECLARATION PARSING
  2343. ****************************************************************************}
  2344. { search in symtablestack for not complete classes }
  2345. procedure check_forward_class(p:TObject;arg:pointer);
  2346. begin
  2347. if (tsym(p).typ=typesym) and
  2348. (ttypesym(p).typedef.typ=objectdef) and
  2349. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2350. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2351. end;
  2352. {$ifdef DEBUG_NODE_XML}
  2353. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  2354. var
  2355. T: Text;
  2356. begin
  2357. Assign(T, current_module.ppxfilename);
  2358. {$push} {$I-}
  2359. Rewrite(T);
  2360. if IOResult<>0 then
  2361. begin
  2362. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2363. current_module.ppxfilefail := True;
  2364. Exit;
  2365. end;
  2366. {$pop}
  2367. { Mark the node dump file as available for writing }
  2368. current_module.ppxfilefail := False;
  2369. WriteLn(T, '<?xml version="1.0" encoding="utf-8"?>');
  2370. WriteLn(T, '<', RootName, ' name="', ModuleName, '">');
  2371. Close(T);
  2372. end;
  2373. procedure XMLFinalizeNodeFile(RootName: shortstring);
  2374. var
  2375. T: Text;
  2376. begin
  2377. if current_module.ppxfilefail then
  2378. Exit;
  2379. current_module.ppxfilefail := True; { File is now considered closed no matter what happens }
  2380. Assign(T, current_module.ppxfilename);
  2381. {$push} {$I-}
  2382. Append(T);
  2383. if IOResult<>0 then
  2384. begin
  2385. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2386. Exit;
  2387. end;
  2388. {$pop}
  2389. WriteLn(T, '</', RootName, '>');
  2390. Close(T);
  2391. end;
  2392. {$endif DEBUG_NODE_XML}
  2393. procedure read_declarations(islibrary : boolean);
  2394. var
  2395. hadgeneric : boolean;
  2396. procedure handle_unexpected_had_generic;
  2397. begin
  2398. if hadgeneric then
  2399. begin
  2400. Message(parser_e_procedure_or_function_expected);
  2401. hadgeneric:=false;
  2402. end;
  2403. end;
  2404. var
  2405. is_classdef:boolean;
  2406. begin
  2407. is_classdef:=false;
  2408. hadgeneric:=false;
  2409. repeat
  2410. if not assigned(current_procinfo) then
  2411. internalerror(200304251);
  2412. case token of
  2413. _LABEL:
  2414. begin
  2415. handle_unexpected_had_generic;
  2416. label_dec;
  2417. end;
  2418. _CONST:
  2419. begin
  2420. handle_unexpected_had_generic;
  2421. const_dec(hadgeneric);
  2422. end;
  2423. _TYPE:
  2424. begin
  2425. handle_unexpected_had_generic;
  2426. type_dec(hadgeneric);
  2427. end;
  2428. _VAR:
  2429. begin
  2430. handle_unexpected_had_generic;
  2431. var_dec(hadgeneric);
  2432. end;
  2433. _THREADVAR:
  2434. begin
  2435. handle_unexpected_had_generic;
  2436. threadvar_dec(hadgeneric);
  2437. end;
  2438. _CLASS:
  2439. begin
  2440. is_classdef:=false;
  2441. if try_to_consume(_CLASS) then
  2442. begin
  2443. { class modifier is only allowed for procedures, functions, }
  2444. { constructors, destructors }
  2445. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2446. not((token=_ID) and (idtoken=_OPERATOR)) then
  2447. Message(parser_e_procedure_or_function_expected);
  2448. if is_interface(current_structdef) then
  2449. Message(parser_e_no_static_method_in_interfaces)
  2450. else
  2451. { class methods are also allowed for Objective-C protocols }
  2452. is_classdef:=true;
  2453. end;
  2454. end;
  2455. _CONSTRUCTOR,
  2456. _DESTRUCTOR,
  2457. _FUNCTION,
  2458. _PROCEDURE,
  2459. _OPERATOR:
  2460. begin
  2461. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2462. begin
  2463. Message(parser_e_procedure_or_function_expected);
  2464. hadgeneric:=false;
  2465. end;
  2466. read_proc(is_classdef,nil,hadgeneric);
  2467. is_classdef:=false;
  2468. hadgeneric:=false;
  2469. end;
  2470. _EXPORTS:
  2471. begin
  2472. handle_unexpected_had_generic;
  2473. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2474. begin
  2475. Message(parser_e_syntax_error);
  2476. consume_all_until(_SEMICOLON);
  2477. end
  2478. else if islibrary or
  2479. (target_info.system in systems_unit_program_exports) then
  2480. read_exports
  2481. else
  2482. begin
  2483. Message(parser_w_unsupported_feature);
  2484. consume(_BEGIN);
  2485. end;
  2486. end;
  2487. _PROPERTY:
  2488. begin
  2489. handle_unexpected_had_generic;
  2490. if (m_fpc in current_settings.modeswitches) then
  2491. property_dec
  2492. else
  2493. break;
  2494. end;
  2495. else
  2496. begin
  2497. case idtoken of
  2498. _RESOURCESTRING:
  2499. begin
  2500. handle_unexpected_had_generic;
  2501. { m_class is needed, because the resourcestring
  2502. loading is in the ObjPas unit }
  2503. { if (m_class in current_settings.modeswitches) then}
  2504. resourcestring_dec(hadgeneric)
  2505. { else
  2506. break;}
  2507. end;
  2508. _OPERATOR:
  2509. begin
  2510. handle_unexpected_had_generic;
  2511. if is_classdef then
  2512. begin
  2513. read_proc(is_classdef,nil,false);
  2514. is_classdef:=false;
  2515. end
  2516. else
  2517. break;
  2518. end;
  2519. _GENERIC:
  2520. begin
  2521. handle_unexpected_had_generic;
  2522. if not (m_delphi in current_settings.modeswitches) then
  2523. begin
  2524. consume(_ID);
  2525. hadgeneric:=true;
  2526. end
  2527. else
  2528. break;
  2529. end
  2530. else
  2531. break;
  2532. end;
  2533. end;
  2534. end;
  2535. until false;
  2536. { add implementations for synthetic method declarations added by
  2537. the compiler (not for unit/program init functions, their localst
  2538. is the staticst -> would duplicate the work done in pmodules) }
  2539. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  2540. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2541. { check for incomplete class definitions, this is only required
  2542. for fpc modes }
  2543. if (m_fpc in current_settings.modeswitches) then
  2544. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2545. end;
  2546. procedure read_interface_declarations;
  2547. var
  2548. hadgeneric : boolean;
  2549. procedure handle_unexpected_had_generic;
  2550. begin
  2551. if hadgeneric then
  2552. begin
  2553. Message(parser_e_procedure_or_function_expected);
  2554. hadgeneric:=false;
  2555. end;
  2556. end;
  2557. begin
  2558. hadgeneric:=false;
  2559. repeat
  2560. case token of
  2561. _CONST :
  2562. begin
  2563. handle_unexpected_had_generic;
  2564. const_dec(hadgeneric);
  2565. end;
  2566. _TYPE :
  2567. begin
  2568. handle_unexpected_had_generic;
  2569. type_dec(hadgeneric);
  2570. end;
  2571. _VAR :
  2572. begin
  2573. handle_unexpected_had_generic;
  2574. var_dec(hadgeneric);
  2575. end;
  2576. _THREADVAR :
  2577. begin
  2578. handle_unexpected_had_generic;
  2579. threadvar_dec(hadgeneric);
  2580. end;
  2581. _FUNCTION,
  2582. _PROCEDURE,
  2583. _OPERATOR :
  2584. begin
  2585. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2586. begin
  2587. message(parser_e_procedure_or_function_expected);
  2588. hadgeneric:=false;
  2589. end;
  2590. read_proc(false,nil,hadgeneric);
  2591. hadgeneric:=false;
  2592. end;
  2593. else
  2594. begin
  2595. case idtoken of
  2596. _RESOURCESTRING :
  2597. begin
  2598. handle_unexpected_had_generic;
  2599. resourcestring_dec(hadgeneric);
  2600. end;
  2601. _PROPERTY:
  2602. begin
  2603. handle_unexpected_had_generic;
  2604. if (m_fpc in current_settings.modeswitches) then
  2605. property_dec
  2606. else
  2607. break;
  2608. end;
  2609. _GENERIC:
  2610. begin
  2611. handle_unexpected_had_generic;
  2612. if not (m_delphi in current_settings.modeswitches) then
  2613. begin
  2614. hadgeneric:=true;
  2615. consume(_ID);
  2616. end
  2617. else
  2618. break;
  2619. end
  2620. else
  2621. break;
  2622. end;
  2623. end;
  2624. end;
  2625. until false;
  2626. { check for incomplete class definitions, this is only required
  2627. for fpc modes }
  2628. if (m_fpc in current_settings.modeswitches) then
  2629. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2630. end;
  2631. end.