ngenutil.pas 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. {
  2. Copyright (c) 1998-2011 by Florian Klaempfl
  3. Generic version of some node tree helper routines that can be overridden
  4. by cpu-specific versions
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit ngenutil;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cclasses,globtype,
  23. aasmdata,
  24. node,nbas,symtype,symsym,symconst,symdef;
  25. type
  26. tnodeutils = class
  27. class function call_fail_node:tnode; virtual;
  28. class function initialize_data_node(p:tnode; force: boolean):tnode; virtual;
  29. class function finalize_data_node(p:tnode):tnode; virtual;
  30. strict protected
  31. class procedure sym_maybe_initialize(p: TObject; arg: pointer);
  32. { generates the code for finalisation of local variables }
  33. class procedure local_varsyms_finalize(p:TObject;arg:pointer);
  34. { generates the code for finalization of static symtable and
  35. all local (static) typed consts }
  36. class procedure static_syms_finalize(p: TObject; arg: pointer);
  37. class procedure sym_maybe_finalize(var stat: tstatementnode; sym: tsym);
  38. public
  39. class procedure procdef_block_add_implicit_initialize_nodes(pd: tprocdef; var stat: tstatementnode);
  40. class procedure procdef_block_add_implicit_finalize_nodes(pd: tprocdef; var stat: tstatementnode);
  41. { returns true if the unit requires an initialisation section (e.g.,
  42. to force class constructors for the JVM target to initialise global
  43. records/arrays) }
  44. class function force_init: boolean; virtual;
  45. { idem for finalization }
  46. class function force_final: boolean; virtual;
  47. { if the funcretsym was moved to the parentfpstruct, use this method to
  48. move its value back back into the funcretsym before the function exit, as
  49. the code generator is hardcoded to use to use the funcretsym when loading
  50. the value to be returned; replacing it with an absolutevarsym that
  51. redirects to the field in the parentfpstruct doesn't work, as the code
  52. generator cannot deal with such symbols }
  53. class procedure load_parentfpstruct_nested_funcret(pd: tprocdef; var stat: tstatementnode);
  54. { called after parsing a routine with the code of the entire routine
  55. as argument; can be used to modify the node tree. By default handles
  56. insertion of code for systems that perform the typed constant
  57. initialisation via the node tree }
  58. class function wrap_proc_body(pd: tprocdef; n: tnode): tnode; virtual;
  59. { trashes a paravarsym or localvarsym if possible (not a managed type,
  60. "out" in case of parameter, ...) }
  61. class procedure maybe_trash_variable(var stat: tstatementnode; p: tabstractnormalvarsym; trashn: tnode); virtual;
  62. strict protected
  63. { called from wrap_proc_body to insert the trashing for the wrapped
  64. routine's local variables and parameters }
  65. class function maybe_insert_trashing(pd: tprocdef; n: tnode): tnode;
  66. class function check_insert_trashing(pd: tprocdef): boolean; virtual;
  67. { callback called for every local variable and parameter by
  68. maybe_insert_trashing(), calls through to maybe_trash_variable() }
  69. class procedure maybe_trash_variable_callback(p: TObject; statn: pointer);
  70. { returns whether a particular sym can be trashed. If not,
  71. maybe_trash_variable won't do anything }
  72. class function trashable_sym(p: tsym): boolean; virtual;
  73. { trashing for 1/2/3/4/8-byte sized variables }
  74. class procedure trash_small(var stat: tstatementnode; trashn: tnode; trashvaln: tnode); virtual;
  75. { trashing for differently sized variables that those handled by
  76. trash_small() }
  77. class procedure trash_large(var stat: tstatementnode; trashn, sizen: tnode; trashintval: int64); virtual;
  78. { insert a single bss sym, called by insert bssdata (factored out
  79. non-common part for llvm) }
  80. class procedure insertbsssym(list: tasmlist; sym: tstaticvarsym; size: asizeint; varalign: shortint); virtual;
  81. { initialization of iso styled program parameters }
  82. class procedure initialize_textrec(p : TObject; statn : pointer);
  83. { finalization of iso styled program parameters }
  84. class procedure finalize_textrec(p : TObject; statn : pointer);
  85. public
  86. class procedure insertbssdata(sym : tstaticvarsym); virtual;
  87. class function create_main_procdef(const name: string; potype:tproctypeoption; ps: tprocsym):tdef; virtual;
  88. class procedure InsertInitFinalTable; virtual;
  89. protected
  90. class procedure InsertRuntimeInits(const prefix:string;list:TLinkedList;unitflag:cardinal); virtual;
  91. class procedure InsertRuntimeInitsTablesTable(const prefix,tablename:string;unitflag:cardinal); virtual;
  92. public
  93. class procedure InsertThreadvarTablesTable; virtual;
  94. class procedure InsertThreadvars; virtual;
  95. class procedure InsertWideInitsTablesTable; virtual;
  96. class procedure InsertWideInits; virtual;
  97. class procedure InsertResStrInits; virtual;
  98. class procedure InsertResStrTablesTable; virtual;
  99. class procedure InsertResourceTablesTable; virtual;
  100. class procedure InsertResourceInfo(ResourcesUsed : boolean); virtual;
  101. class procedure InsertMemorySizes; virtual;
  102. { called right before an object is assembled, can be used to insert
  103. global information into the assembler list (used by LLVM to insert type
  104. info) }
  105. class procedure InsertObjectInfo; virtual;
  106. strict protected
  107. class procedure add_main_procdef_paras(pd: tdef); virtual;
  108. end;
  109. tnodeutilsclass = class of tnodeutils;
  110. const
  111. cnodeutils: tnodeutilsclass = tnodeutils;
  112. implementation
  113. uses
  114. verbose,version,globals,cutils,constexp,
  115. scanner,systems,procinfo,fmodule,
  116. aasmbase,aasmtai,aasmcnst,
  117. symbase,symtable,defutil,symcreat,
  118. nadd,ncal,ncnv,ncon,nflw,ninl,nld,nmem,nobj,nutils,ncgutil,
  119. ppu,
  120. pass_1;
  121. class function tnodeutils.call_fail_node:tnode;
  122. var
  123. para : tcallparanode;
  124. newstatement : tstatementnode;
  125. srsym : tsym;
  126. begin
  127. result:=internalstatements(newstatement);
  128. { call fail helper and exit normal }
  129. if is_class(current_structdef) then
  130. begin
  131. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  132. if assigned(srsym) and
  133. (srsym.typ=procsym) then
  134. begin
  135. { if self<>0 and vmt<>0 then freeinstance }
  136. addstatement(newstatement,cifnode.create(
  137. caddnode.create(andn,
  138. caddnode.create(unequaln,
  139. load_self_pointer_node,
  140. cnilnode.create),
  141. caddnode.create(unequaln,
  142. load_vmt_pointer_node,
  143. cnilnode.create)),
  144. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  145. nil));
  146. end
  147. else
  148. internalerror(200305108);
  149. end
  150. else
  151. if is_object(current_structdef) then
  152. begin
  153. { parameter 3 : vmt_offset }
  154. { parameter 2 : pointer to vmt }
  155. { parameter 1 : self pointer }
  156. para:=ccallparanode.create(
  157. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  158. ccallparanode.create(
  159. ctypeconvnode.create_internal(
  160. load_vmt_pointer_node,
  161. voidpointertype),
  162. ccallparanode.create(
  163. ctypeconvnode.create_internal(
  164. load_self_pointer_node,
  165. voidpointertype),
  166. nil)));
  167. addstatement(newstatement,
  168. ccallnode.createintern('fpc_help_fail',para));
  169. end
  170. else
  171. internalerror(200305132);
  172. { self:=nil }
  173. addstatement(newstatement,cassignmentnode.create(
  174. load_self_pointer_node,
  175. cnilnode.create));
  176. { exit }
  177. addstatement(newstatement,cexitnode.create(nil));
  178. end;
  179. class function tnodeutils.initialize_data_node(p:tnode; force: boolean):tnode;
  180. begin
  181. { prevent initialisation of hidden syms that were moved to
  182. parentfpstructs: the original symbol isn't used anymore, the version
  183. in parentfpstruct will be initialised when that struct gets initialised,
  184. and references to it will actually be translated into references to the
  185. field in the parentfpstruct (so we'll initialise it twice) }
  186. if (target_info.system in systems_fpnestedstruct) and
  187. (p.nodetype=loadn) and
  188. (tloadnode(p).symtableentry.typ=localvarsym) and
  189. (tloadnode(p).symtableentry.visibility=vis_hidden) then
  190. begin
  191. p.free;
  192. result:=cnothingnode.create;
  193. end
  194. else
  195. begin
  196. if not assigned(p.resultdef) then
  197. typecheckpass(p);
  198. if is_ansistring(p.resultdef) or
  199. is_wide_or_unicode_string(p.resultdef) or
  200. is_interfacecom_or_dispinterface(p.resultdef) or
  201. is_dynamic_array(p.resultdef) then
  202. begin
  203. result:=cassignmentnode.create(
  204. ctypeconvnode.create_internal(p,voidpointertype),
  205. cnilnode.create
  206. );
  207. end
  208. else if (p.resultdef.typ=variantdef) then
  209. begin
  210. result:=ccallnode.createintern('fpc_variant_init',
  211. ccallparanode.create(
  212. ctypeconvnode.create_internal(p,search_system_type('TVARDATA').typedef),
  213. nil));
  214. end
  215. else
  216. begin
  217. result:=ccallnode.createintern('fpc_initialize',
  218. ccallparanode.create(
  219. caddrnode.create_internal(
  220. crttinode.create(
  221. tstoreddef(p.resultdef),initrtti,rdt_normal)),
  222. ccallparanode.create(
  223. caddrnode.create_internal(p),
  224. nil)));
  225. end;
  226. end;
  227. end;
  228. class function tnodeutils.finalize_data_node(p:tnode):tnode;
  229. var
  230. hs : string;
  231. begin
  232. { see comment in initialize_data_node above }
  233. if (target_info.system in systems_fpnestedstruct) and
  234. (p.nodetype=loadn) and
  235. (tloadnode(p).symtableentry.typ=localvarsym) and
  236. (tloadnode(p).symtableentry.visibility=vis_hidden) then
  237. begin
  238. p.free;
  239. result:=cnothingnode.create;
  240. end
  241. else
  242. begin
  243. if not assigned(p.resultdef) then
  244. typecheckpass(p);
  245. { 'decr_ref' suffix is somewhat misleading, all these helpers
  246. set the passed pointer to nil now }
  247. if is_ansistring(p.resultdef) then
  248. hs:='fpc_ansistr_decr_ref'
  249. else if is_widestring(p.resultdef) then
  250. hs:='fpc_widestr_decr_ref'
  251. else if is_unicodestring(p.resultdef) then
  252. hs:='fpc_unicodestr_decr_ref'
  253. else if is_interfacecom_or_dispinterface(p.resultdef) then
  254. hs:='fpc_intf_decr_ref'
  255. else
  256. hs:='';
  257. if hs<>'' then
  258. result:=ccallnode.createintern(hs,
  259. ccallparanode.create(
  260. ctypeconvnode.create_internal(p,voidpointertype),
  261. nil))
  262. else if p.resultdef.typ=variantdef then
  263. begin
  264. result:=ccallnode.createintern('fpc_variant_clear',
  265. ccallparanode.create(
  266. ctypeconvnode.create_internal(p,search_system_type('TVARDATA').typedef),
  267. nil));
  268. end
  269. else
  270. result:=ccallnode.createintern('fpc_finalize',
  271. ccallparanode.create(
  272. caddrnode.create_internal(
  273. crttinode.create(
  274. tstoreddef(p.resultdef),initrtti,rdt_normal)),
  275. ccallparanode.create(
  276. caddrnode.create_internal(p),
  277. nil)));
  278. end;
  279. end;
  280. class procedure tnodeutils.sym_maybe_initialize(p: TObject; arg: pointer);
  281. begin
  282. if (tsym(p).typ = localvarsym) and
  283. { local (procedure or unit) variables only need initialization if
  284. they are used }
  285. ((tabstractvarsym(p).refs>0) or
  286. { managed return symbols must be inited }
  287. ((tsym(p).typ=localvarsym) and (vo_is_funcret in tlocalvarsym(p).varoptions))
  288. ) and
  289. not(vo_is_typed_const in tabstractvarsym(p).varoptions) and
  290. not(vo_is_external in tabstractvarsym(p).varoptions) and
  291. not(vo_is_default_var in tabstractvarsym(p).varoptions) and
  292. (is_managed_type(tabstractvarsym(p).vardef) or
  293. ((m_iso in current_settings.modeswitches) and (tabstractvarsym(p).vardef.typ=filedef))
  294. ) then
  295. begin
  296. addstatement(tstatementnode(arg^),initialize_data_node(cloadnode.create(tsym(p),tsym(p).owner),false));
  297. end;
  298. end;
  299. class procedure tnodeutils.local_varsyms_finalize(p: TObject; arg: pointer);
  300. begin
  301. if (tsym(p).typ=localvarsym) and
  302. (tlocalvarsym(p).refs>0) and
  303. not(vo_is_external in tlocalvarsym(p).varoptions) and
  304. not(vo_is_funcret in tlocalvarsym(p).varoptions) and
  305. not(vo_is_default_var in tabstractvarsym(p).varoptions) and
  306. is_managed_type(tlocalvarsym(p).vardef) then
  307. sym_maybe_finalize(tstatementnode(arg^),tsym(p));
  308. end;
  309. class procedure tnodeutils.static_syms_finalize(p: TObject; arg: pointer);
  310. var
  311. i : longint;
  312. pd : tprocdef;
  313. begin
  314. case tsym(p).typ of
  315. staticvarsym :
  316. begin
  317. { local (procedure or unit) variables only need finalization
  318. if they are used
  319. }
  320. if ((tstaticvarsym(p).refs>0) or
  321. { global (unit) variables always need finalization, since
  322. they may also be used in another unit
  323. }
  324. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  325. (
  326. (tstaticvarsym(p).varspez<>vs_const) or
  327. (vo_force_finalize in tstaticvarsym(p).varoptions)
  328. ) and
  329. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  330. not(vo_is_external in tstaticvarsym(p).varoptions) and
  331. is_managed_type(tstaticvarsym(p).vardef) and
  332. not (
  333. assigned(tstaticvarsym(p).fieldvarsym) and
  334. assigned(tstaticvarsym(p).fieldvarsym.owner.defowner) and
  335. (df_generic in tdef(tstaticvarsym(p).fieldvarsym.owner.defowner).defoptions)
  336. )
  337. then
  338. sym_maybe_finalize(tstatementnode(arg^),tsym(p));
  339. end;
  340. procsym :
  341. begin
  342. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  343. begin
  344. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  345. if assigned(pd.localst) and
  346. (pd.procsym=tprocsym(p)) and
  347. (pd.localst.symtabletype<>staticsymtable) then
  348. pd.localst.SymList.ForEachCall(@static_syms_finalize,arg);
  349. end;
  350. end;
  351. end;
  352. end;
  353. class procedure tnodeutils.sym_maybe_finalize(var stat: tstatementnode; sym: tsym);
  354. var
  355. hp: tnode;
  356. begin
  357. include(current_procinfo.flags,pi_needs_implicit_finally);
  358. hp:=cloadnode.create(sym,sym.owner);
  359. if (sym.typ=staticvarsym) and (vo_force_finalize in tstaticvarsym(sym).varoptions) then
  360. include(tloadnode(hp).loadnodeflags,loadnf_isinternal_ignoreconst);
  361. addstatement(stat,finalize_data_node(hp));
  362. end;
  363. class procedure tnodeutils.procdef_block_add_implicit_initialize_nodes(pd: tprocdef; var stat: tstatementnode);
  364. begin
  365. { initialize local data like ansistrings }
  366. case pd.proctypeoption of
  367. potype_unitinit:
  368. begin
  369. { this is also used for initialization of variables in a
  370. program which does not have a globalsymtable }
  371. if assigned(current_module.globalsymtable) then
  372. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@sym_maybe_initialize,@stat);
  373. TSymtable(current_module.localsymtable).SymList.ForEachCall(@sym_maybe_initialize,@stat);
  374. TSymtable(current_module.localsymtable).SymList.ForEachCall(@sym_maybe_initialize,@stat);
  375. end;
  376. { units have seperate code for initilization and finalization }
  377. potype_unitfinalize: ;
  378. { program init/final is generated in separate procedure }
  379. potype_proginit:
  380. begin
  381. TSymtable(current_module.localsymtable).SymList.ForEachCall(@sym_maybe_initialize,@stat);
  382. end;
  383. else
  384. current_procinfo.procdef.localst.SymList.ForEachCall(@sym_maybe_initialize,@stat);
  385. end;
  386. end;
  387. class procedure tnodeutils.procdef_block_add_implicit_finalize_nodes(pd: tprocdef; var stat: tstatementnode);
  388. begin
  389. { no finalization in exceptfilters, they /are/ the finalization code }
  390. if current_procinfo.procdef.proctypeoption=potype_exceptfilter then
  391. exit;
  392. { finalize local data like ansistrings}
  393. case current_procinfo.procdef.proctypeoption of
  394. potype_unitfinalize:
  395. begin
  396. { this is also used for initialization of variables in a
  397. program which does not have a globalsymtable }
  398. if assigned(current_module.globalsymtable) then
  399. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@static_syms_finalize,@stat);
  400. TSymtable(current_module.localsymtable).SymList.ForEachCall(@static_syms_finalize,@stat);
  401. end;
  402. { units/progs have separate code for initialization and finalization }
  403. potype_unitinit: ;
  404. { program init/final is generated in separate procedure }
  405. potype_proginit: ;
  406. else
  407. current_procinfo.procdef.localst.SymList.ForEachCall(@local_varsyms_finalize,@stat);
  408. end;
  409. end;
  410. class function tnodeutils.force_init: boolean;
  411. begin
  412. result:=
  413. (target_info.system in systems_typed_constants_node_init) and
  414. assigned(current_module.tcinitcode);
  415. end;
  416. class function tnodeutils.force_final: boolean;
  417. begin
  418. result:=false;
  419. end;
  420. class procedure tnodeutils.initialize_textrec(p:TObject;statn:pointer);
  421. var
  422. stat: ^tstatementnode absolute statn;
  423. begin
  424. if (tsym(p).typ=staticvarsym) and
  425. (tstaticvarsym(p).vardef.typ=filedef) and
  426. (tfiledef(tstaticvarsym(p).vardef).filetyp=ft_text) and
  427. (tstaticvarsym(p).isoindex<>0) then
  428. begin
  429. if cs_transparent_file_names in current_settings.globalswitches then
  430. addstatement(stat^,ccallnode.createintern('fpc_textinit_filename_iso',
  431. ccallparanode.create(
  432. cstringconstnode.createstr(tstaticvarsym(p).Name),
  433. ccallparanode.create(
  434. cordconstnode.create(tstaticvarsym(p).isoindex,uinttype,false),
  435. ccallparanode.create(
  436. cloadnode.create(tstaticvarsym(p),tstaticvarsym(p).Owner),
  437. nil)))))
  438. else
  439. addstatement(stat^,ccallnode.createintern('fpc_textinit_iso',
  440. ccallparanode.create(
  441. cordconstnode.create(tstaticvarsym(p).isoindex,uinttype,false),
  442. ccallparanode.create(
  443. cloadnode.create(tstaticvarsym(p),tstaticvarsym(p).Owner),
  444. nil))));
  445. end;
  446. end;
  447. class procedure tnodeutils.finalize_textrec(p:TObject;statn:pointer);
  448. var
  449. stat: ^tstatementnode absolute statn;
  450. begin
  451. if (tsym(p).typ=staticvarsym) and
  452. (tstaticvarsym(p).vardef.typ=filedef) and
  453. (tfiledef(tstaticvarsym(p).vardef).filetyp=ft_text) and
  454. (tstaticvarsym(p).isoindex<>0) then
  455. begin
  456. addstatement(stat^,ccallnode.createintern('fpc_textclose_iso',
  457. ccallparanode.create(
  458. cloadnode.create(tstaticvarsym(p),tstaticvarsym(p).Owner),
  459. nil)));
  460. end;
  461. end;
  462. class procedure tnodeutils.load_parentfpstruct_nested_funcret(pd: tprocdef; var stat: tstatementnode);
  463. var
  464. target: tnode;
  465. begin
  466. target:=cloadnode.create(pd.funcretsym, pd.funcretsym.owner);
  467. { ensure the target of this assignment doesn't translate the
  468. funcretsym also to its alias in the parentfpstruct }
  469. include(target.flags, nf_internal);
  470. addstatement(stat,
  471. cassignmentnode.create(
  472. target, cloadnode.create(pd.funcretsym, pd.funcretsym.owner)
  473. )
  474. );
  475. end;
  476. class function tnodeutils.wrap_proc_body(pd: tprocdef; n: tnode): tnode;
  477. var
  478. stat: tstatementnode;
  479. block: tnode;
  480. psym: tsym;
  481. begin
  482. result:=maybe_insert_trashing(pd,n);
  483. if (m_isolike_program_para in current_settings.modeswitches) and
  484. (pd.proctypeoption=potype_proginit) then
  485. begin
  486. block:=internalstatements(stat);
  487. pd.localst.SymList.ForEachCall(@initialize_textrec,@stat);
  488. addstatement(stat,result);
  489. pd.localst.SymList.ForEachCall(@finalize_textrec,@stat);
  490. result:=block;
  491. end;
  492. if target_info.system in systems_typed_constants_node_init then
  493. begin
  494. case pd.proctypeoption of
  495. potype_class_constructor:
  496. begin
  497. { even though the initialisation code for typed constants may
  498. not yet be complete at this point (there may be more inside
  499. method definitions coming after this class constructor), the
  500. ones from inside the class definition have already been parsed.
  501. in case of $j-, these are marked "final" in Java and such
  502. static fields must be initialsed in the class constructor
  503. itself -> add them here }
  504. block:=internalstatements(stat);
  505. if assigned(pd.struct.tcinitcode) then
  506. begin
  507. addstatement(stat,pd.struct.tcinitcode);
  508. pd.struct.tcinitcode:=nil;
  509. end;
  510. psym:=tsym(pd.struct.symtable.find('FPC_INIT_TYPED_CONSTS_HELPER'));
  511. if assigned(psym) then
  512. begin
  513. if (psym.typ<>procsym) or
  514. (tprocsym(psym).procdeflist.count<>1) then
  515. internalerror(2011040301);
  516. addstatement(stat,ccallnode.create(nil,tprocsym(psym),
  517. pd.struct.symtable,nil,[],nil));
  518. end;
  519. addstatement(stat,result);
  520. result:=block
  521. end;
  522. potype_unitinit:
  523. begin
  524. if assigned(current_module.tcinitcode) then
  525. begin
  526. block:=internalstatements(stat);
  527. addstatement(stat,tnode(current_module.tcinitcode));
  528. current_module.tcinitcode:=nil;
  529. addstatement(stat,result);
  530. result:=block;
  531. end;
  532. end;
  533. else case pd.synthetickind of
  534. tsk_tcinit:
  535. begin
  536. if assigned(pd.struct.tcinitcode) then
  537. begin
  538. block:=internalstatements(stat);
  539. addstatement(stat,pd.struct.tcinitcode);
  540. pd.struct.tcinitcode:=nil;
  541. addstatement(stat,result);
  542. result:=block
  543. end
  544. end;
  545. end;
  546. end;
  547. end;
  548. if target_info.system in systems_fpnestedstruct then
  549. begin
  550. if assigned(pd.funcretsym) and
  551. tabstractnormalvarsym(pd.funcretsym).inparentfpstruct then
  552. begin
  553. block:=internalstatements(stat);
  554. addstatement(stat,result);
  555. load_parentfpstruct_nested_funcret(pd,stat);
  556. result:=block;
  557. end;
  558. end;
  559. end;
  560. class function tnodeutils.maybe_insert_trashing(pd: tprocdef; n: tnode): tnode;
  561. var
  562. stat: tstatementnode;
  563. begin
  564. result:=n;
  565. if check_insert_trashing(pd) then
  566. begin
  567. result:=internalstatements(stat);
  568. pd.parast.SymList.ForEachCall(@maybe_trash_variable_callback,@stat);
  569. pd.localst.SymList.ForEachCall(@maybe_trash_variable_callback,@stat);
  570. addstatement(stat,n);
  571. end;
  572. end;
  573. class function tnodeutils.check_insert_trashing(pd: tprocdef): boolean;
  574. begin
  575. result:=
  576. (localvartrashing<>-1) and
  577. not(po_assembler in pd.procoptions);
  578. end;
  579. class function tnodeutils.trashable_sym(p: tsym): boolean;
  580. begin
  581. result:=
  582. ((p.typ=localvarsym) or
  583. ((p.typ=paravarsym) and
  584. ((vo_is_funcret in tabstractnormalvarsym(p).varoptions) or
  585. (tabstractnormalvarsym(p).varspez=vs_out)))) and
  586. not (vo_is_default_var in tabstractnormalvarsym(p).varoptions) and
  587. (not is_managed_type(tabstractnormalvarsym(p).vardef) or
  588. (is_string(tabstractnormalvarsym(p).vardef) and
  589. (vo_is_funcret in tabstractnormalvarsym(p).varoptions)
  590. )
  591. ) and
  592. not assigned(tabstractnormalvarsym(p).defaultconstsym);
  593. end;
  594. class procedure tnodeutils.maybe_trash_variable(var stat: tstatementnode; p: tabstractnormalvarsym; trashn: tnode);
  595. var
  596. size: asizeint;
  597. trashintval: int64;
  598. begin
  599. if trashable_sym(p) then
  600. begin
  601. trashintval:=trashintvalues[localvartrashing];
  602. if (p.vardef.typ=procvardef) and
  603. ([m_tp_procvar,m_mac_procvar]*current_settings.modeswitches<>[]) then
  604. begin
  605. if tprocvardef(p.vardef).is_addressonly then
  606. { in tp/delphi mode, you need @procvar to get at the contents of
  607. a procvar ... }
  608. trashn:=caddrnode.create(trashn)
  609. else
  610. { ... but if it's a procedure of object, that will only return
  611. the procedure address -> cast to tmethod instead }
  612. trashn:=ctypeconvnode.create_explicit(trashn,methodpointertype);
  613. end;
  614. if is_managed_type(p.vardef) then
  615. begin
  616. if is_string(p.vardef) then
  617. trash_small(stat,trashn,
  618. cstringconstnode.createstr(
  619. 'uninitialized function result in '+
  620. tprocdef(p.owner.defowner).customprocname([pno_proctypeoption, pno_paranames,pno_ownername, pno_noclassmarker])
  621. )
  622. )
  623. else
  624. internalerror(2016030601);
  625. end
  626. else if ((p.typ=localvarsym) and
  627. (not(vo_is_funcret in p.varoptions) or
  628. not is_shortstring(p.vardef))) or
  629. ((p.typ=paravarsym) and
  630. not is_shortstring(p.vardef)) then
  631. begin
  632. size:=p.getsize;
  633. case size of
  634. 0:
  635. begin
  636. { open array -> at least size 1. Can also be zero-sized
  637. record, so check it's actually an array }
  638. if p.vardef.typ=arraydef then
  639. trash_large(stat,trashn,caddnode.create(addn,cinlinenode.create(in_high_x,false,trashn.getcopy),genintconstnode(1)),trashintval)
  640. else
  641. trashn.free;
  642. end;
  643. 1: trash_small(stat,
  644. ctypeconvnode.create_internal(trashn,s8inttype),
  645. genintconstnode(shortint(trashintval)));
  646. 2: trash_small(stat,
  647. ctypeconvnode.create_internal(trashn,s16inttype),
  648. genintconstnode(smallint(trashintval)));
  649. 4: trash_small(stat,
  650. ctypeconvnode.create_internal(trashn,s32inttype),
  651. genintconstnode(longint(trashintval)));
  652. 8: trash_small(stat,
  653. ctypeconvnode.create_internal(trashn,s64inttype),
  654. genintconstnode(int64(trashintval)));
  655. else
  656. trash_large(stat,trashn,genintconstnode(size),trashintval);
  657. end;
  658. end
  659. else
  660. begin
  661. { may be an open string, even if is_open_string() returns false
  662. (for some helpers in the system unit) }
  663. { an open string has at least size 2 }
  664. trash_small(stat,
  665. cvecnode.create(trashn.getcopy,genintconstnode(0)),
  666. cordconstnode.create(tconstexprint(byte(trashintval)),cansichartype,false));
  667. trash_small(stat,
  668. cvecnode.create(trashn,genintconstnode(1)),
  669. cordconstnode.create(tconstexprint(byte(trashintval)),cansichartype,false));
  670. end;
  671. end
  672. else
  673. trashn.free;
  674. end;
  675. class procedure tnodeutils.maybe_trash_variable_callback(p:TObject;statn:pointer);
  676. var
  677. stat: ^tstatementnode absolute statn;
  678. begin
  679. if not(tsym(p).typ in [localvarsym,paravarsym]) then
  680. exit;
  681. maybe_trash_variable(stat^,tabstractnormalvarsym(p),cloadnode.create(tsym(p),tsym(p).owner));
  682. end;
  683. class procedure tnodeutils.trash_small(var stat: tstatementnode; trashn: tnode; trashvaln: tnode);
  684. begin
  685. addstatement(stat,cassignmentnode.create(trashn,trashvaln));
  686. end;
  687. class procedure tnodeutils.trash_large(var stat: tstatementnode; trashn, sizen: tnode; trashintval: int64);
  688. begin
  689. addstatement(stat,ccallnode.createintern('fpc_fillmem',
  690. ccallparanode.Create(cordconstnode.create(tconstexprint(byte(trashintval)),u8inttype,false),
  691. ccallparanode.Create(sizen,
  692. ccallparanode.Create(trashn,nil)))
  693. ));
  694. end;
  695. class procedure tnodeutils.insertbsssym(list: tasmlist; sym: tstaticvarsym; size: asizeint; varalign: shortint);
  696. begin
  697. if sym.globalasmsym then
  698. begin
  699. { on AIX/stabx, we cannot generate debug information that encodes
  700. the address of a global symbol, you need a symbol with the same
  701. name as the identifier -> create an extra *local* symbol.
  702. Moreover, such a local symbol will be removed if it's not
  703. referenced anywhere, so also create a reference }
  704. if (target_dbg.id=dbg_stabx) and
  705. (cs_debuginfo in current_settings.moduleswitches) and
  706. not assigned(current_asmdata.GetAsmSymbol(sym.name)) then
  707. begin
  708. list.concat(tai_symbol.Create(current_asmdata.DefineAsmSymbol(sym.name,AB_LOCAL,AT_DATA,sym.vardef),0));
  709. list.concat(tai_directive.Create(asd_reference,sym.name));
  710. end;
  711. list.concat(Tai_datablock.create_global(sym.mangledname,size,sym.vardef));
  712. end
  713. else
  714. list.concat(Tai_datablock.create(sym.mangledname,size,sym.vardef));
  715. end;
  716. class procedure tnodeutils.insertbssdata(sym: tstaticvarsym);
  717. var
  718. l : asizeint;
  719. varalign : shortint;
  720. storefilepos : tfileposinfo;
  721. list : TAsmList;
  722. sectype : TAsmSectiontype;
  723. begin
  724. storefilepos:=current_filepos;
  725. current_filepos:=sym.fileinfo;
  726. l:=sym.getsize;
  727. varalign:=sym.vardef.alignment;
  728. if (varalign=0) then
  729. varalign:=var_align_size(l)
  730. else
  731. varalign:=var_align(varalign);
  732. if tf_section_threadvars in target_info.flags then
  733. begin
  734. if (vo_is_thread_var in sym.varoptions) then
  735. begin
  736. list:=current_asmdata.asmlists[al_threadvars];
  737. sectype:=sec_threadvar;
  738. end
  739. else
  740. begin
  741. list:=current_asmdata.asmlists[al_globals];
  742. sectype:=sec_bss;
  743. end;
  744. end
  745. else
  746. begin
  747. if (vo_is_thread_var in sym.varoptions) then
  748. begin
  749. inc(l,sizeof(pint));
  750. { it doesn't help to set a higher alignment, as }
  751. { the first sizeof(pint) bytes field will offset }
  752. { everything anyway }
  753. varalign:=sizeof(pint);
  754. end;
  755. list:=current_asmdata.asmlists[al_globals];
  756. sectype:=sec_bss;
  757. end;
  758. maybe_new_object_file(list);
  759. if vo_has_section in sym.varoptions then
  760. new_section(list,sec_user,sym.section,varalign)
  761. else
  762. new_section(list,sectype,lower(sym.mangledname),varalign);
  763. insertbsssym(list,sym,l,varalign);
  764. current_filepos:=storefilepos;
  765. end;
  766. class function tnodeutils.create_main_procdef(const name: string; potype: tproctypeoption; ps: tprocsym): tdef;
  767. var
  768. pd: tprocdef;
  769. begin
  770. if potype<>potype_mainstub then
  771. pd:=cprocdef.create(main_program_level,true)
  772. else
  773. pd:=cprocdef.create(normal_function_level,true);
  774. { always register the def }
  775. pd.register_def;
  776. pd.procsym:=ps;
  777. ps.ProcdefList.Add(pd);
  778. include(pd.procoptions,po_global);
  779. { set procdef options }
  780. pd.proctypeoption:=potype;
  781. pd.proccalloption:=pocall_default;
  782. include(pd.procoptions,po_hascallingconvention);
  783. pd.forwarddef:=false;
  784. { may be required to calculate the mangled name }
  785. add_main_procdef_paras(pd);
  786. pd.setmangledname(name);
  787. { the mainstub is generated via a synthetic proc -> parsed via
  788. psub.read_proc_body() -> that one will insert the mangled name in the
  789. alias names already }
  790. if potype<>potype_mainstub then
  791. pd.aliasnames.insert(pd.mangledname);
  792. result:=pd;
  793. end;
  794. procedure AddToStructInits(p:TObject;arg:pointer);
  795. var
  796. StructList: TFPList absolute arg;
  797. begin
  798. if (tdef(p).typ in [objectdef,recorddef]) and
  799. not (df_generic in tdef(p).defoptions) then
  800. begin
  801. { first add the class... }
  802. if ([oo_has_class_constructor,oo_has_class_destructor] * tabstractrecorddef(p).objectoptions <> []) then
  803. StructList.Add(p);
  804. { ... and then also add all subclasses }
  805. tabstractrecorddef(p).symtable.deflist.foreachcall(@AddToStructInits,arg);
  806. end;
  807. end;
  808. class procedure tnodeutils.InsertInitFinalTable;
  809. var
  810. hp : tused_unit;
  811. unitinits : ttai_typedconstbuilder;
  812. count : aint;
  813. tablecountplaceholder: ttypedconstplaceholder;
  814. nameinit,namefini : TSymStr;
  815. tabledef: tdef;
  816. procedure write_struct_inits(u: tmodule);
  817. var
  818. i: integer;
  819. structlist: TFPList;
  820. pd: tprocdef;
  821. begin
  822. structlist := TFPList.Create;
  823. if assigned(u.globalsymtable) then
  824. u.globalsymtable.DefList.ForEachCall(@AddToStructInits,structlist);
  825. u.localsymtable.DefList.ForEachCall(@AddToStructInits,structlist);
  826. { write structures }
  827. for i:=0 to structlist.Count-1 do
  828. begin
  829. pd:=tabstractrecorddef(structlist[i]).find_procdef_bytype(potype_class_constructor);
  830. if assigned(pd) then
  831. begin
  832. unitinits.emit_procdef_const(pd);
  833. if u<>current_module then
  834. current_module.addimportedsym(pd.procsym);
  835. end
  836. else
  837. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  838. pd := tabstractrecorddef(structlist[i]).find_procdef_bytype(potype_class_destructor);
  839. if assigned(pd) then
  840. begin
  841. unitinits.emit_procdef_const(pd);
  842. if u<>current_module then
  843. current_module.addimportedsym(pd.procsym);
  844. end
  845. else
  846. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  847. inc(count);
  848. end;
  849. structlist.free;
  850. end;
  851. procedure add_initfinal_import(symtable:tsymtable);
  852. var
  853. i,j : longint;
  854. foundinit,foundfini : boolean;
  855. sym : TSymEntry;
  856. pd : tprocdef;
  857. begin
  858. if (nameinit='') and (namefini='') then
  859. exit;
  860. foundinit:=nameinit='';
  861. foundfini:=namefini='';
  862. for i:=0 to symtable.SymList.Count-1 do
  863. begin
  864. sym:=tsymentry(symtable.SymList[i]);
  865. if sym.typ<>procsym then
  866. continue;
  867. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  868. begin
  869. pd:=tprocdef(tprocsym(sym).procdeflist[j]);
  870. if (nameinit<>'') and not foundinit and pd.has_alias_name(nameinit) then
  871. begin
  872. current_module.addimportedsym(sym);
  873. foundinit:=true;
  874. end;
  875. if (namefini<>'') and not foundfini and pd.has_alias_name(namefini) then
  876. begin
  877. current_module.addimportedsym(sym);
  878. foundfini:=true;
  879. end;
  880. if foundinit and foundfini then
  881. break;
  882. end;
  883. if foundinit and foundfini then
  884. break;
  885. end;
  886. if not foundinit or not foundfini then
  887. internalerror(2016041401);
  888. end;
  889. begin
  890. unitinits:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  891. unitinits.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  892. targetinfos[target_info.system]^.alignment.recordalignmin,
  893. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  894. { placeholder for tablecount }
  895. tablecountplaceholder:=unitinits.emit_placeholder(aluuinttype);
  896. { initcount (initialised at run time }
  897. unitinits.emit_ord_const(0,aluuinttype);
  898. count:=0;
  899. hp:=tused_unit(usedunits.first);
  900. while assigned(hp) do
  901. begin
  902. { insert class constructors/destructors of the unit }
  903. if (hp.u.flags and uf_classinits) <> 0 then
  904. write_struct_inits(hp.u);
  905. { call the unit init code and make it external }
  906. if (hp.u.flags and (uf_init or uf_finalize))<>0 then
  907. begin
  908. if count=high(aint) then
  909. Message1(cg_f_max_units_reached,tostr(count));
  910. nameinit:='';
  911. namefini:='';
  912. if (hp.u.flags and uf_init)<>0 then
  913. begin
  914. nameinit:=make_mangledname('INIT$',hp.u.globalsymtable,'');
  915. unitinits.emit_tai(
  916. Tai_const.Createname(nameinit,AT_FUNCTION,0),
  917. voidcodepointertype);
  918. end
  919. else
  920. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  921. if (hp.u.flags and uf_finalize)<>0 then
  922. begin
  923. namefini:=make_mangledname('FINALIZE$',hp.u.globalsymtable,'');
  924. unitinits.emit_tai(
  925. Tai_const.Createname(namefini,AT_FUNCTION,0),
  926. voidcodepointertype)
  927. end
  928. else
  929. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  930. add_initfinal_import(hp.u.localsymtable);
  931. inc(count);
  932. end;
  933. hp:=tused_unit(hp.next);
  934. end;
  935. { insert class constructors/destructor of the program }
  936. if (current_module.flags and uf_classinits) <> 0 then
  937. write_struct_inits(current_module);
  938. { Insert initialization/finalization of the program }
  939. if (current_module.flags and (uf_init or uf_finalize))<>0 then
  940. begin
  941. if (current_module.flags and uf_init)<>0 then
  942. unitinits.emit_tai(
  943. Tai_const.Createname(make_mangledname('INIT$',current_module.localsymtable,''),AT_FUNCTION,0),
  944. voidcodepointertype)
  945. else
  946. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  947. if (current_module.flags and uf_finalize)<>0 then
  948. unitinits.emit_tai(
  949. Tai_const.Createname(make_mangledname('FINALIZE$',current_module.localsymtable,''),AT_FUNCTION,0),
  950. voidcodepointertype)
  951. else
  952. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  953. inc(count);
  954. end;
  955. { fill in tablecount }
  956. tablecountplaceholder.replace(tai_const.Create_aint(count),aluuinttype);
  957. tablecountplaceholder.free;
  958. { Add to data segment }
  959. tabledef:=unitinits.end_anonymous_record;
  960. current_asmdata.asmlists[al_globals].concatlist(
  961. unitinits.get_final_asmlist(
  962. current_asmdata.DefineAsmSymbol('INITFINAL',AB_GLOBAL,AT_DATA,tabledef),
  963. tabledef,
  964. sec_data,'INITFINAL',sizeof(pint)
  965. )
  966. );
  967. unitinits.free;
  968. end;
  969. class procedure tnodeutils.InsertThreadvarTablesTable;
  970. var
  971. hp : tused_unit;
  972. tcb: ttai_typedconstbuilder;
  973. count: longint;
  974. sym: tasmsymbol;
  975. placeholder: ttypedconstplaceholder;
  976. tabledef: tdef;
  977. begin
  978. if (tf_section_threadvars in target_info.flags) then
  979. exit;
  980. count:=0;
  981. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  982. tcb.begin_anonymous_record('',1,sizeof(pint),
  983. targetinfos[target_info.system]^.alignment.recordalignmin,
  984. targetinfos[target_info.system]^.alignment.maxCrecordalign
  985. );
  986. placeholder:=tcb.emit_placeholder(u32inttype);
  987. hp:=tused_unit(usedunits.first);
  988. while assigned(hp) do
  989. begin
  990. if (hp.u.flags and uf_threadvars)=uf_threadvars then
  991. begin
  992. sym:=current_asmdata.RefAsmSymbol(make_mangledname('THREADVARLIST',hp.u.globalsymtable,''),AT_DATA,true);
  993. tcb.emit_tai(
  994. tai_const.Create_sym(sym),
  995. voidpointertype);
  996. current_module.add_extern_asmsym(sym);
  997. inc(count);
  998. end;
  999. hp:=tused_unit(hp.next);
  1000. end;
  1001. { Add program threadvars, if any }
  1002. if (current_module.flags and uf_threadvars)=uf_threadvars then
  1003. begin
  1004. sym:=current_asmdata.RefAsmSymbol(make_mangledname('THREADVARLIST',current_module.localsymtable,''),AT_DATA,true);
  1005. tcb.emit_tai(
  1006. Tai_const.Create_sym(sym),
  1007. voidpointertype);
  1008. inc(count);
  1009. end;
  1010. { set the count at the start }
  1011. placeholder.replace(tai_const.Create_32bit(count),u32inttype);
  1012. placeholder.free;
  1013. { insert in data segment }
  1014. tabledef:=tcb.end_anonymous_record;
  1015. sym:=current_asmdata.DefineAsmSymbol('FPC_THREADVARTABLES',AB_GLOBAL,AT_DATA,tabledef);
  1016. current_asmdata.asmlists[al_globals].concatlist(
  1017. tcb.get_final_asmlist(
  1018. sym,tabledef,sec_data,'FPC_THREADVARTABLES',sizeof(pint)
  1019. )
  1020. );
  1021. tcb.free;
  1022. end;
  1023. procedure AddToThreadvarList(p:TObject;arg:pointer);
  1024. var
  1025. tcb: ttai_typedconstbuilder;
  1026. field1, field2: tsym;
  1027. begin
  1028. if (tsym(p).typ=staticvarsym) and
  1029. (vo_is_thread_var in tstaticvarsym(p).varoptions) then
  1030. begin
  1031. tcb:=ttai_typedconstbuilder(arg);
  1032. { address of threadvar }
  1033. tcb.emit_tai(tai_const.Createname(tstaticvarsym(p).mangledname,0),
  1034. cpointerdef.getreusable(
  1035. get_threadvar_record(tstaticvarsym(p).vardef,field1,field2)
  1036. )
  1037. );
  1038. { size of threadvar }
  1039. tcb.emit_ord_const(tstaticvarsym(p).getsize,u32inttype);
  1040. end;
  1041. end;
  1042. class procedure tnodeutils.InsertThreadvars;
  1043. var
  1044. s : string;
  1045. tcb: ttai_typedconstbuilder;
  1046. sym: tasmsymbol;
  1047. tabledef: trecorddef;
  1048. add : boolean;
  1049. begin
  1050. if (tf_section_threadvars in target_info.flags) then
  1051. exit;
  1052. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1053. tabledef:=tcb.begin_anonymous_record('',1,sizeof(pint),
  1054. targetinfos[target_info.system]^.alignment.recordalignmin,
  1055. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1056. if assigned(current_module.globalsymtable) then
  1057. current_module.globalsymtable.SymList.ForEachCall(@AddToThreadvarList,tcb);
  1058. current_module.localsymtable.SymList.ForEachCall(@AddToThreadvarList,tcb);
  1059. if trecordsymtable(tabledef.symtable).datasize<>0 then
  1060. { terminator }
  1061. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1062. tcb.end_anonymous_record;
  1063. add:=trecordsymtable(tabledef.symtable).datasize<>0;
  1064. if add then
  1065. begin
  1066. s:=make_mangledname('THREADVARLIST',current_module.localsymtable,'');
  1067. sym:=current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA_FORCEINDIRECT,tabledef);
  1068. current_asmdata.asmlists[al_globals].concatlist(
  1069. tcb.get_final_asmlist(sym,tabledef,sec_data,s,sizeof(pint)));
  1070. current_module.flags:=current_module.flags or uf_threadvars;
  1071. current_module.add_public_asmsym(sym);
  1072. end
  1073. else
  1074. s:='';
  1075. tcb.Free;
  1076. end;
  1077. class procedure tnodeutils.InsertRuntimeInitsTablesTable(const prefix,tablename:string;unitflag:cardinal);
  1078. var
  1079. hp: tused_unit;
  1080. tcb: ttai_typedconstbuilder;
  1081. countplaceholder: ttypedconstplaceholder;
  1082. tabledef: tdef;
  1083. count: longint;
  1084. begin
  1085. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1086. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1087. targetinfos[target_info.system]^.alignment.recordalignmin,
  1088. targetinfos[target_info.system]^.alignment.maxCrecordalign
  1089. );
  1090. { placeholder for the count }
  1091. countplaceholder:=tcb.emit_placeholder(sizesinttype);
  1092. count:=0;
  1093. hp:=tused_unit(usedunits.first);
  1094. while assigned(hp) do
  1095. begin
  1096. if (hp.u.flags and unitflag)=unitflag then
  1097. begin
  1098. tcb.emit_tai(
  1099. Tai_const.Createname(make_mangledname(prefix,hp.u.globalsymtable,''),0),
  1100. voidcodepointertype);
  1101. inc(count);
  1102. end;
  1103. hp:=tused_unit(hp.next);
  1104. end;
  1105. { Add items from program, if any }
  1106. if (current_module.flags and unitflag)=unitflag then
  1107. begin
  1108. tcb.emit_tai(
  1109. Tai_const.Createname(make_mangledname(prefix,current_module.localsymtable,''),0),
  1110. voidcodepointertype);
  1111. inc(count);
  1112. end;
  1113. { Insert TableCount at start }
  1114. countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
  1115. countplaceholder.free;
  1116. { insert in data segment }
  1117. tabledef:=tcb.end_anonymous_record;
  1118. current_asmdata.asmlists[al_globals].concatlist(
  1119. tcb.get_final_asmlist(
  1120. current_asmdata.DefineAsmSymbol(tablename,AB_GLOBAL,AT_DATA,tabledef),
  1121. tabledef,
  1122. sec_data,tablename,sizeof(pint)
  1123. )
  1124. );
  1125. tcb.free;
  1126. end;
  1127. class procedure tnodeutils.InsertRuntimeInits(const prefix:string;list:TLinkedList;unitflag:cardinal);
  1128. var
  1129. s: string;
  1130. item: TTCInitItem;
  1131. tcb: ttai_typedconstbuilder;
  1132. rawdatadef: tdef;
  1133. begin
  1134. item:=TTCInitItem(list.First);
  1135. if item=nil then
  1136. exit;
  1137. s:=make_mangledname(prefix,current_module.localsymtable,'');
  1138. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1139. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1140. targetinfos[target_info.system]^.alignment.recordalignmin,
  1141. targetinfos[target_info.system]^.alignment.maxCrecordalign );
  1142. repeat
  1143. { optimize away unused local/static symbols }
  1144. if (item.sym.refs>0) or (item.sym.owner.symtabletype=globalsymtable) then
  1145. begin
  1146. { address to initialize }
  1147. tcb.queue_init(voidpointertype);
  1148. rawdatadef:=carraydef.getreusable(cansichartype,tstaticvarsym(item.sym).vardef.size);
  1149. tcb.queue_vecn(rawdatadef,item.offset);
  1150. tcb.queue_typeconvn(cpointerdef.getreusable(tstaticvarsym(item.sym).vardef),cpointerdef.getreusable(rawdatadef));
  1151. tcb.queue_emit_staticvar(tstaticvarsym(item.sym));
  1152. { value with which to initialize }
  1153. tcb.emit_tai(Tai_const.Create_sym(item.datalabel),item.datadef)
  1154. end;
  1155. item:=TTCInitItem(item.Next);
  1156. until item=nil;
  1157. { end-of-list marker }
  1158. tcb.emit_tai(Tai_const.Create_nil_dataptr,voidpointertype);
  1159. rawdatadef:=tcb.end_anonymous_record;
  1160. current_asmdata.asmlists[al_globals].concatList(
  1161. tcb.get_final_asmlist(
  1162. current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA,rawdatadef),
  1163. rawdatadef,sec_data,s,sizeof(pint)));
  1164. tcb.free;
  1165. current_module.flags:=current_module.flags or unitflag;
  1166. end;
  1167. class procedure tnodeutils.InsertWideInits;
  1168. begin
  1169. InsertRuntimeInits('WIDEINITS',current_asmdata.WideInits,uf_wideinits);
  1170. end;
  1171. class procedure tnodeutils.InsertResStrInits;
  1172. begin
  1173. InsertRuntimeInits('RESSTRINITS',current_asmdata.ResStrInits,uf_resstrinits);
  1174. end;
  1175. class procedure tnodeutils.InsertWideInitsTablesTable;
  1176. begin
  1177. InsertRuntimeInitsTablesTable('WIDEINITS','FPC_WIDEINITTABLES',uf_wideinits);
  1178. end;
  1179. class procedure tnodeutils.InsertResStrTablesTable;
  1180. begin
  1181. InsertRuntimeInitsTablesTable('RESSTRINITS','FPC_RESSTRINITTABLES',uf_resstrinits);
  1182. end;
  1183. class procedure tnodeutils.InsertResourceTablesTable;
  1184. var
  1185. hp : tmodule;
  1186. count : longint;
  1187. tcb : ttai_typedconstbuilder;
  1188. countplaceholder : ttypedconstplaceholder;
  1189. tabledef: tdef;
  1190. begin
  1191. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1192. count:=0;
  1193. hp:=tmodule(loaded_units.first);
  1194. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1195. targetinfos[target_info.system]^.alignment.recordalignmin,
  1196. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1197. countplaceholder:=tcb.emit_placeholder(sizesinttype);
  1198. while assigned(hp) do
  1199. begin
  1200. If (hp.flags and uf_has_resourcestrings)=uf_has_resourcestrings then
  1201. begin
  1202. tcb.emit_tai(Tai_const.Create_sym(
  1203. ctai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_start('RESSTR',hp.localsymtable,[tcdssso_register_asmsym,tcdssso_use_indirect])),
  1204. voidpointertype
  1205. );
  1206. tcb.emit_tai(Tai_const.Create_sym(
  1207. ctai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_end('RESSTR',hp.localsymtable,[tcdssso_register_asmsym,tcdssso_use_indirect])),
  1208. voidpointertype
  1209. );
  1210. inc(count);
  1211. end;
  1212. hp:=tmodule(hp.next);
  1213. end;
  1214. { Insert TableCount at start }
  1215. countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
  1216. countplaceholder.free;
  1217. { Add to data segment }
  1218. tabledef:=tcb.end_anonymous_record;
  1219. current_asmdata.AsmLists[al_globals].concatList(
  1220. tcb.get_final_asmlist(
  1221. current_asmdata.DefineAsmSymbol('FPC_RESOURCESTRINGTABLES',AB_GLOBAL,AT_DATA,tabledef),
  1222. tabledef,sec_rodata,'FPC_RESOURCESTRINGTABLES',sizeof(pint)
  1223. )
  1224. );
  1225. tcb.free;
  1226. end;
  1227. class procedure tnodeutils.InsertResourceInfo(ResourcesUsed: boolean);
  1228. var
  1229. tcb: ttai_typedconstbuilder;
  1230. begin
  1231. if (target_res.id in [res_elf,res_macho,res_xcoff]) or
  1232. { generate the FPC_RESLOCATION symbol even when using external resources,
  1233. because in SysInit we can only reference it unconditionally }
  1234. ((target_res.id=res_ext) and (target_info.system in systems_darwin)) then
  1235. begin
  1236. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1237. if ResourcesUsed and (target_res.id<>res_ext) then
  1238. tcb.emit_tai(Tai_const.Createname('FPC_RESSYMBOL',0),voidpointertype)
  1239. else
  1240. { Nil pointer to resource information }
  1241. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1242. current_asmdata.asmlists[al_globals].concatList(
  1243. tcb.get_final_asmlist(
  1244. current_asmdata.DefineAsmSymbol('FPC_RESLOCATION',AB_GLOBAL,AT_DATA,voidpointertype),
  1245. voidpointertype,
  1246. sec_rodata,
  1247. 'FPC_RESLOCATION',
  1248. sizeof(puint)
  1249. )
  1250. );
  1251. tcb.free;
  1252. end;
  1253. end;
  1254. class procedure tnodeutils.InsertMemorySizes;
  1255. var
  1256. tcb: ttai_typedconstbuilder;
  1257. s: shortstring;
  1258. sym: tasmsymbol;
  1259. def: tdef;
  1260. begin
  1261. { Insert Ident of the compiler in the .fpc.version section }
  1262. tcb:=ctai_typedconstbuilder.create([tcalo_no_dead_strip]);
  1263. s:='FPC '+full_version_string+
  1264. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  1265. def:=carraydef.getreusable(cansichartype,length(s));
  1266. tcb.maybe_begin_aggregate(def);
  1267. tcb.emit_tai(Tai_string.Create(s),def);
  1268. tcb.maybe_end_aggregate(def);
  1269. sym:=current_asmdata.DefineAsmSymbol('__fpc_ident',AB_LOCAL,AT_DATA,def);
  1270. current_asmdata.asmlists[al_globals].concatlist(
  1271. tcb.get_final_asmlist(sym,def,sec_fpc,'version',const_align(32))
  1272. );
  1273. tcb.free;
  1274. if (tf_emit_stklen in target_info.flags) or
  1275. not(tf_no_generic_stackcheck in target_info.flags) then
  1276. begin
  1277. { stacksize can be specified and is now simulated }
  1278. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1279. tcb.emit_tai(Tai_const.Create_int_dataptr(stacksize),ptruinttype);
  1280. sym:=current_asmdata.DefineAsmSymbol('__stklen',AB_GLOBAL,AT_DATA,ptruinttype);
  1281. current_asmdata.asmlists[al_globals].concatlist(
  1282. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__stklen',sizeof(pint))
  1283. );
  1284. tcb.free;
  1285. end;
  1286. {$IFDEF POWERPC}
  1287. { AmigaOS4 "stack cookie" support }
  1288. if ( target_info.system = system_powerpc_amiga ) then
  1289. begin
  1290. { this symbol is needed to ignite powerpc amigaos' }
  1291. { stack allocation magic for us with the given stack size. }
  1292. { note: won't work for m68k amigaos or morphos. (KB) }
  1293. str(stacksize,s);
  1294. s:='$STACK: '+s+#0;
  1295. def:=carraydef.getreusable(cansichartype,length(s));
  1296. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1297. tcb.maybe_begin_aggregate(def);
  1298. tcb.emit_tai(Tai_string.Create(s),def);
  1299. tcb.maybe_end_aggregate(def);
  1300. sym:=current_asmdata.DefineAsmSymbol('__stack_cookie',AB_GLOBAL,AT_DATA,def);
  1301. current_asmdata.asmlists[al_globals].concatlist(
  1302. tcb.get_final_asmlist(sym,def,sec_data,'__stack_cookie',sizeof(pint))
  1303. );
  1304. tcb.free;
  1305. end;
  1306. {$ENDIF POWERPC}
  1307. { Initial heapsize }
  1308. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1309. tcb.emit_tai(Tai_const.Create_int_dataptr(heapsize),ptruinttype);
  1310. sym:=current_asmdata.DefineAsmSymbol('__heapsize',AB_GLOBAL,AT_DATA,ptruinttype);
  1311. current_asmdata.asmlists[al_globals].concatlist(
  1312. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__heapsize',sizeof(pint))
  1313. );
  1314. tcb.free;
  1315. { allocate an initial heap on embedded systems }
  1316. if target_info.system in systems_embedded then
  1317. begin
  1318. { tai_datablock cannot yet be handled via the high level typed const
  1319. builder, because it implies the generation of a symbol, while this
  1320. is separate in the builder }
  1321. maybe_new_object_file(current_asmdata.asmlists[al_globals]);
  1322. new_section(current_asmdata.asmlists[al_globals],sec_bss,'__fpc_initialheap',current_settings.alignment.varalignmax);
  1323. current_asmdata.asmlists[al_globals].concat(tai_datablock.Create_global('__fpc_initialheap',heapsize,carraydef.getreusable(u8inttype,heapsize)));
  1324. end;
  1325. { Valgrind usage }
  1326. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1327. tcb.emit_ord_const(byte(cs_gdb_valgrind in current_settings.globalswitches),u8inttype);
  1328. sym:=current_asmdata.DefineAsmSymbol('__fpc_valgrind',AB_GLOBAL,AT_DATA,u8inttype);
  1329. current_asmdata.asmlists[al_globals].concatlist(
  1330. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__fpc_valgrind',sizeof(pint))
  1331. );
  1332. tcb.free;
  1333. end;
  1334. class procedure tnodeutils.InsertObjectInfo;
  1335. begin
  1336. { don't do anything by default }
  1337. end;
  1338. class procedure tnodeutils.add_main_procdef_paras(pd: tdef);
  1339. var
  1340. pvs: tparavarsym;
  1341. begin
  1342. { stub for calling FPC_SYSTEMMAIN from the C main -> add argc/argv/argp }
  1343. if (tprocdef(pd).proctypeoption=potype_mainstub) and
  1344. (target_info.system in (systems_darwin+[system_powerpc_macos]+systems_aix)) then
  1345. begin
  1346. pvs:=cparavarsym.create('ARGC',1,vs_const,s32inttype,[]);
  1347. tprocdef(pd).parast.insert(pvs);
  1348. pvs:=cparavarsym.create('ARGV',2,vs_const,cpointerdef.getreusable(charpointertype),[]);
  1349. tprocdef(pd).parast.insert(pvs);
  1350. pvs:=cparavarsym.create('ARGP',3,vs_const,cpointerdef.getreusable(charpointertype),[]);
  1351. tprocdef(pd).parast.insert(pvs);
  1352. tprocdef(pd).calcparas;
  1353. end;
  1354. end;
  1355. end.