psub.pas 108 KB

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