ngenutil.pas 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  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. addstatement(stat^,ccallnode.createintern('fpc_textinit_iso',
  430. ccallparanode.create(
  431. cordconstnode.create(tstaticvarsym(p).isoindex,uinttype,false),
  432. ccallparanode.create(
  433. cloadnode.create(tstaticvarsym(p),tstaticvarsym(p).Owner),
  434. nil))));
  435. end;
  436. end;
  437. class procedure tnodeutils.finalize_textrec(p:TObject;statn:pointer);
  438. var
  439. stat: ^tstatementnode absolute statn;
  440. begin
  441. if (tsym(p).typ=staticvarsym) and
  442. (tstaticvarsym(p).vardef.typ=filedef) and
  443. (tfiledef(tstaticvarsym(p).vardef).filetyp=ft_text) and
  444. (tstaticvarsym(p).isoindex<>0) then
  445. begin
  446. addstatement(stat^,ccallnode.createintern('fpc_textclose_iso',
  447. ccallparanode.create(
  448. cloadnode.create(tstaticvarsym(p),tstaticvarsym(p).Owner),
  449. nil)));
  450. end;
  451. end;
  452. class procedure tnodeutils.load_parentfpstruct_nested_funcret(pd: tprocdef; var stat: tstatementnode);
  453. var
  454. target: tnode;
  455. begin
  456. target:=cloadnode.create(pd.funcretsym, pd.funcretsym.owner);
  457. { ensure the target of this assignment doesn't translate the
  458. funcretsym also to its alias in the parentfpstruct }
  459. include(target.flags, nf_internal);
  460. addstatement(stat,
  461. cassignmentnode.create(
  462. target, cloadnode.create(pd.funcretsym, pd.funcretsym.owner)
  463. )
  464. );
  465. end;
  466. class function tnodeutils.wrap_proc_body(pd: tprocdef; n: tnode): tnode;
  467. var
  468. stat: tstatementnode;
  469. block: tnode;
  470. psym: tsym;
  471. begin
  472. result:=maybe_insert_trashing(pd,n);
  473. if (m_isolike_program_para in current_settings.modeswitches) and
  474. (pd.proctypeoption=potype_proginit) then
  475. begin
  476. block:=internalstatements(stat);
  477. pd.localst.SymList.ForEachCall(@initialize_textrec,@stat);
  478. addstatement(stat,result);
  479. pd.localst.SymList.ForEachCall(@finalize_textrec,@stat);
  480. result:=block;
  481. end;
  482. if target_info.system in systems_typed_constants_node_init then
  483. begin
  484. case pd.proctypeoption of
  485. potype_class_constructor:
  486. begin
  487. { even though the initialisation code for typed constants may
  488. not yet be complete at this point (there may be more inside
  489. method definitions coming after this class constructor), the
  490. ones from inside the class definition have already been parsed.
  491. in case of $j-, these are marked "final" in Java and such
  492. static fields must be initialsed in the class constructor
  493. itself -> add them here }
  494. block:=internalstatements(stat);
  495. if assigned(pd.struct.tcinitcode) then
  496. begin
  497. addstatement(stat,pd.struct.tcinitcode);
  498. pd.struct.tcinitcode:=nil;
  499. end;
  500. psym:=tsym(pd.struct.symtable.find('FPC_INIT_TYPED_CONSTS_HELPER'));
  501. if assigned(psym) then
  502. begin
  503. if (psym.typ<>procsym) or
  504. (tprocsym(psym).procdeflist.count<>1) then
  505. internalerror(2011040301);
  506. addstatement(stat,ccallnode.create(nil,tprocsym(psym),
  507. pd.struct.symtable,nil,[],nil));
  508. end;
  509. addstatement(stat,result);
  510. result:=block
  511. end;
  512. potype_unitinit:
  513. begin
  514. if assigned(current_module.tcinitcode) then
  515. begin
  516. block:=internalstatements(stat);
  517. addstatement(stat,tnode(current_module.tcinitcode));
  518. current_module.tcinitcode:=nil;
  519. addstatement(stat,result);
  520. result:=block;
  521. end;
  522. end;
  523. else case pd.synthetickind of
  524. tsk_tcinit:
  525. begin
  526. if assigned(pd.struct.tcinitcode) then
  527. begin
  528. block:=internalstatements(stat);
  529. addstatement(stat,pd.struct.tcinitcode);
  530. pd.struct.tcinitcode:=nil;
  531. addstatement(stat,result);
  532. result:=block
  533. end
  534. end;
  535. end;
  536. end;
  537. end;
  538. if target_info.system in systems_fpnestedstruct then
  539. begin
  540. if assigned(pd.funcretsym) and
  541. tabstractnormalvarsym(pd.funcretsym).inparentfpstruct then
  542. begin
  543. block:=internalstatements(stat);
  544. addstatement(stat,result);
  545. load_parentfpstruct_nested_funcret(pd,stat);
  546. result:=block;
  547. end;
  548. end;
  549. end;
  550. class function tnodeutils.maybe_insert_trashing(pd: tprocdef; n: tnode): tnode;
  551. var
  552. stat: tstatementnode;
  553. begin
  554. result:=n;
  555. if check_insert_trashing(pd) then
  556. begin
  557. result:=internalstatements(stat);
  558. pd.parast.SymList.ForEachCall(@maybe_trash_variable_callback,@stat);
  559. pd.localst.SymList.ForEachCall(@maybe_trash_variable_callback,@stat);
  560. addstatement(stat,n);
  561. end;
  562. end;
  563. class function tnodeutils.check_insert_trashing(pd: tprocdef): boolean;
  564. begin
  565. result:=
  566. (localvartrashing<>-1) and
  567. not(po_assembler in pd.procoptions);
  568. end;
  569. class function tnodeutils.trashable_sym(p: tsym): boolean;
  570. begin
  571. result:=
  572. ((p.typ=localvarsym) or
  573. ((p.typ=paravarsym) and
  574. ((vo_is_funcret in tabstractnormalvarsym(p).varoptions) or
  575. (tabstractnormalvarsym(p).varspez=vs_out)))) and
  576. not (vo_is_default_var in tabstractnormalvarsym(p).varoptions) and
  577. (not is_managed_type(tabstractnormalvarsym(p).vardef) or
  578. (is_string(tabstractnormalvarsym(p).vardef) and
  579. (vo_is_funcret in tabstractnormalvarsym(p).varoptions)
  580. )
  581. ) and
  582. not assigned(tabstractnormalvarsym(p).defaultconstsym);
  583. end;
  584. class procedure tnodeutils.maybe_trash_variable(var stat: tstatementnode; p: tabstractnormalvarsym; trashn: tnode);
  585. var
  586. size: asizeint;
  587. trashintval: int64;
  588. begin
  589. if trashable_sym(p) then
  590. begin
  591. trashintval:=trashintvalues[localvartrashing];
  592. if (p.vardef.typ=procvardef) and
  593. ([m_tp_procvar,m_mac_procvar]*current_settings.modeswitches<>[]) then
  594. begin
  595. if tprocvardef(p.vardef).is_addressonly then
  596. { in tp/delphi mode, you need @procvar to get at the contents of
  597. a procvar ... }
  598. trashn:=caddrnode.create(trashn)
  599. else
  600. { ... but if it's a procedure of object, that will only return
  601. the procedure address -> cast to tmethod instead }
  602. trashn:=ctypeconvnode.create_explicit(trashn,methodpointertype);
  603. end;
  604. if is_managed_type(p.vardef) then
  605. begin
  606. if is_string(p.vardef) then
  607. trash_small(stat,trashn,
  608. cstringconstnode.createstr(
  609. 'uninitialized function result in '+
  610. tprocdef(p.owner.defowner).customprocname([pno_proctypeoption, pno_paranames,pno_ownername, pno_noclassmarker])
  611. )
  612. )
  613. else
  614. internalerror(2016030601);
  615. end
  616. else if ((p.typ=localvarsym) and
  617. (not(vo_is_funcret in p.varoptions) or
  618. not is_shortstring(p.vardef))) or
  619. ((p.typ=paravarsym) and
  620. not is_shortstring(p.vardef)) then
  621. begin
  622. size:=p.getsize;
  623. case size of
  624. 0:
  625. begin
  626. { open array -> at least size 1. Can also be zero-sized
  627. record, so check it's actually an array }
  628. if p.vardef.typ=arraydef then
  629. trash_large(stat,trashn,caddnode.create(addn,cinlinenode.create(in_high_x,false,trashn.getcopy),genintconstnode(1)),trashintval)
  630. else
  631. trashn.free;
  632. end;
  633. 1: trash_small(stat,
  634. ctypeconvnode.create_internal(trashn,s8inttype),
  635. genintconstnode(shortint(trashintval)));
  636. 2: trash_small(stat,
  637. ctypeconvnode.create_internal(trashn,s16inttype),
  638. genintconstnode(smallint(trashintval)));
  639. 4: trash_small(stat,
  640. ctypeconvnode.create_internal(trashn,s32inttype),
  641. genintconstnode(longint(trashintval)));
  642. 8: trash_small(stat,
  643. ctypeconvnode.create_internal(trashn,s64inttype),
  644. genintconstnode(int64(trashintval)));
  645. else
  646. trash_large(stat,trashn,genintconstnode(size),trashintval);
  647. end;
  648. end
  649. else
  650. begin
  651. { may be an open string, even if is_open_string() returns false
  652. (for some helpers in the system unit) }
  653. { an open string has at least size 2 }
  654. trash_small(stat,
  655. cvecnode.create(trashn.getcopy,genintconstnode(0)),
  656. cordconstnode.create(tconstexprint(byte(trashintval)),cansichartype,false));
  657. trash_small(stat,
  658. cvecnode.create(trashn,genintconstnode(1)),
  659. cordconstnode.create(tconstexprint(byte(trashintval)),cansichartype,false));
  660. end;
  661. end
  662. else
  663. trashn.free;
  664. end;
  665. class procedure tnodeutils.maybe_trash_variable_callback(p:TObject;statn:pointer);
  666. var
  667. stat: ^tstatementnode absolute statn;
  668. begin
  669. if not(tsym(p).typ in [localvarsym,paravarsym]) then
  670. exit;
  671. maybe_trash_variable(stat^,tabstractnormalvarsym(p),cloadnode.create(tsym(p),tsym(p).owner));
  672. end;
  673. class procedure tnodeutils.trash_small(var stat: tstatementnode; trashn: tnode; trashvaln: tnode);
  674. begin
  675. addstatement(stat,cassignmentnode.create(trashn,trashvaln));
  676. end;
  677. class procedure tnodeutils.trash_large(var stat: tstatementnode; trashn, sizen: tnode; trashintval: int64);
  678. begin
  679. addstatement(stat,ccallnode.createintern('fpc_fillmem',
  680. ccallparanode.Create(cordconstnode.create(tconstexprint(byte(trashintval)),u8inttype,false),
  681. ccallparanode.Create(sizen,
  682. ccallparanode.Create(trashn,nil)))
  683. ));
  684. end;
  685. class procedure tnodeutils.insertbsssym(list: tasmlist; sym: tstaticvarsym; size: asizeint; varalign: shortint);
  686. begin
  687. if sym.globalasmsym then
  688. begin
  689. { on AIX/stabx, we cannot generate debug information that encodes
  690. the address of a global symbol, you need a symbol with the same
  691. name as the identifier -> create an extra *local* symbol.
  692. Moreover, such a local symbol will be removed if it's not
  693. referenced anywhere, so also create a reference }
  694. if (target_dbg.id=dbg_stabx) and
  695. (cs_debuginfo in current_settings.moduleswitches) and
  696. not assigned(current_asmdata.GetAsmSymbol(sym.name)) then
  697. begin
  698. list.concat(tai_symbol.Create(current_asmdata.DefineAsmSymbol(sym.name,AB_LOCAL,AT_DATA,sym.vardef),0));
  699. list.concat(tai_directive.Create(asd_reference,sym.name));
  700. end;
  701. list.concat(Tai_datablock.create_global(sym.mangledname,size,sym.vardef));
  702. end
  703. else
  704. list.concat(Tai_datablock.create(sym.mangledname,size,sym.vardef));
  705. end;
  706. class procedure tnodeutils.insertbssdata(sym: tstaticvarsym);
  707. var
  708. l : asizeint;
  709. varalign : shortint;
  710. storefilepos : tfileposinfo;
  711. list : TAsmList;
  712. sectype : TAsmSectiontype;
  713. begin
  714. storefilepos:=current_filepos;
  715. current_filepos:=sym.fileinfo;
  716. l:=sym.getsize;
  717. varalign:=sym.vardef.alignment;
  718. if (varalign=0) then
  719. varalign:=var_align_size(l)
  720. else
  721. varalign:=var_align(varalign);
  722. if tf_section_threadvars in target_info.flags then
  723. begin
  724. if (vo_is_thread_var in sym.varoptions) then
  725. begin
  726. list:=current_asmdata.asmlists[al_threadvars];
  727. sectype:=sec_threadvar;
  728. end
  729. else
  730. begin
  731. list:=current_asmdata.asmlists[al_globals];
  732. sectype:=sec_bss;
  733. end;
  734. end
  735. else
  736. begin
  737. if (vo_is_thread_var in sym.varoptions) then
  738. begin
  739. inc(l,sizeof(pint));
  740. { it doesn't help to set a higher alignment, as }
  741. { the first sizeof(pint) bytes field will offset }
  742. { everything anyway }
  743. varalign:=sizeof(pint);
  744. end;
  745. list:=current_asmdata.asmlists[al_globals];
  746. sectype:=sec_bss;
  747. end;
  748. maybe_new_object_file(list);
  749. if vo_has_section in sym.varoptions then
  750. new_section(list,sec_user,sym.section,varalign)
  751. else
  752. new_section(list,sectype,lower(sym.mangledname),varalign);
  753. insertbsssym(list,sym,l,varalign);
  754. current_filepos:=storefilepos;
  755. end;
  756. class function tnodeutils.create_main_procdef(const name: string; potype: tproctypeoption; ps: tprocsym): tdef;
  757. var
  758. pd: tprocdef;
  759. begin
  760. if potype<>potype_mainstub then
  761. pd:=cprocdef.create(main_program_level,true)
  762. else
  763. pd:=cprocdef.create(normal_function_level,true);
  764. { always register the def }
  765. pd.register_def;
  766. pd.procsym:=ps;
  767. ps.ProcdefList.Add(pd);
  768. include(pd.procoptions,po_global);
  769. { set procdef options }
  770. pd.proctypeoption:=potype;
  771. pd.proccalloption:=pocall_default;
  772. include(pd.procoptions,po_hascallingconvention);
  773. pd.forwarddef:=false;
  774. { may be required to calculate the mangled name }
  775. add_main_procdef_paras(pd);
  776. pd.setmangledname(name);
  777. { the mainstub is generated via a synthetic proc -> parsed via
  778. psub.read_proc_body() -> that one will insert the mangled name in the
  779. alias names already }
  780. if potype<>potype_mainstub then
  781. pd.aliasnames.insert(pd.mangledname);
  782. result:=pd;
  783. end;
  784. procedure AddToStructInits(p:TObject;arg:pointer);
  785. var
  786. StructList: TFPList absolute arg;
  787. begin
  788. if (tdef(p).typ in [objectdef,recorddef]) and
  789. not (df_generic in tdef(p).defoptions) then
  790. begin
  791. { first add the class... }
  792. if ([oo_has_class_constructor,oo_has_class_destructor] * tabstractrecorddef(p).objectoptions <> []) then
  793. StructList.Add(p);
  794. { ... and then also add all subclasses }
  795. tabstractrecorddef(p).symtable.deflist.foreachcall(@AddToStructInits,arg);
  796. end;
  797. end;
  798. class procedure tnodeutils.InsertInitFinalTable;
  799. var
  800. hp : tused_unit;
  801. unitinits : ttai_typedconstbuilder;
  802. count : aint;
  803. tablecountplaceholder: ttypedconstplaceholder;
  804. nameinit,namefini : TSymStr;
  805. tabledef: tdef;
  806. procedure write_struct_inits(u: tmodule);
  807. var
  808. i: integer;
  809. structlist: TFPList;
  810. pd: tprocdef;
  811. begin
  812. structlist := TFPList.Create;
  813. if assigned(u.globalsymtable) then
  814. u.globalsymtable.DefList.ForEachCall(@AddToStructInits,structlist);
  815. u.localsymtable.DefList.ForEachCall(@AddToStructInits,structlist);
  816. { write structures }
  817. for i:=0 to structlist.Count-1 do
  818. begin
  819. pd:=tabstractrecorddef(structlist[i]).find_procdef_bytype(potype_class_constructor);
  820. if assigned(pd) then
  821. begin
  822. unitinits.emit_procdef_const(pd);
  823. if u<>current_module then
  824. current_module.addimportedsym(pd.procsym);
  825. end
  826. else
  827. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  828. pd := tabstractrecorddef(structlist[i]).find_procdef_bytype(potype_class_destructor);
  829. if assigned(pd) then
  830. begin
  831. unitinits.emit_procdef_const(pd);
  832. if u<>current_module then
  833. current_module.addimportedsym(pd.procsym);
  834. end
  835. else
  836. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  837. inc(count);
  838. end;
  839. structlist.free;
  840. end;
  841. procedure add_initfinal_import(symtable:tsymtable);
  842. var
  843. i,j : longint;
  844. foundinit,foundfini : boolean;
  845. sym : TSymEntry;
  846. pd : tprocdef;
  847. begin
  848. if (nameinit='') and (namefini='') then
  849. exit;
  850. foundinit:=nameinit='';
  851. foundfini:=namefini='';
  852. for i:=0 to symtable.SymList.Count-1 do
  853. begin
  854. sym:=tsymentry(symtable.SymList[i]);
  855. if sym.typ<>procsym then
  856. continue;
  857. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  858. begin
  859. pd:=tprocdef(tprocsym(sym).procdeflist[j]);
  860. if (nameinit<>'') and not foundinit and has_alias_name(pd,nameinit) then
  861. begin
  862. current_module.addimportedsym(sym);
  863. foundinit:=true;
  864. end;
  865. if (namefini<>'') and not foundfini and has_alias_name(pd,namefini) then
  866. begin
  867. current_module.addimportedsym(sym);
  868. foundfini:=true;
  869. end;
  870. if foundinit and foundfini then
  871. break;
  872. end;
  873. if foundinit and foundfini then
  874. break;
  875. end;
  876. if not foundinit or not foundfini then
  877. internalerror(2016041401);
  878. end;
  879. begin
  880. unitinits:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  881. unitinits.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  882. targetinfos[target_info.system]^.alignment.recordalignmin,
  883. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  884. { placeholder for tablecount }
  885. tablecountplaceholder:=unitinits.emit_placeholder(aluuinttype);
  886. { initcount (initialised at run time }
  887. unitinits.emit_ord_const(0,aluuinttype);
  888. count:=0;
  889. hp:=tused_unit(usedunits.first);
  890. while assigned(hp) do
  891. begin
  892. { insert class constructors/destructors of the unit }
  893. if (hp.u.flags and uf_classinits) <> 0 then
  894. write_struct_inits(hp.u);
  895. { call the unit init code and make it external }
  896. if (hp.u.flags and (uf_init or uf_finalize))<>0 then
  897. begin
  898. if count=high(aint) then
  899. Message1(cg_f_max_units_reached,tostr(count));
  900. nameinit:='';
  901. namefini:='';
  902. if (hp.u.flags and uf_init)<>0 then
  903. begin
  904. nameinit:=make_mangledname('INIT$',hp.u.globalsymtable,'');
  905. unitinits.emit_tai(
  906. Tai_const.Createname(nameinit,AT_FUNCTION,0),
  907. voidcodepointertype);
  908. end
  909. else
  910. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  911. if (hp.u.flags and uf_finalize)<>0 then
  912. begin
  913. namefini:=make_mangledname('FINALIZE$',hp.u.globalsymtable,'');
  914. unitinits.emit_tai(
  915. Tai_const.Createname(namefini,AT_FUNCTION,0),
  916. voidcodepointertype)
  917. end
  918. else
  919. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  920. add_initfinal_import(hp.u.localsymtable);
  921. inc(count);
  922. end;
  923. hp:=tused_unit(hp.next);
  924. end;
  925. { insert class constructors/destructor of the program }
  926. if (current_module.flags and uf_classinits) <> 0 then
  927. write_struct_inits(current_module);
  928. { Insert initialization/finalization of the program }
  929. if (current_module.flags and (uf_init or uf_finalize))<>0 then
  930. begin
  931. if (current_module.flags and uf_init)<>0 then
  932. unitinits.emit_tai(
  933. Tai_const.Createname(make_mangledname('INIT$',current_module.localsymtable,''),AT_FUNCTION,0),
  934. voidcodepointertype)
  935. else
  936. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  937. if (current_module.flags and uf_finalize)<>0 then
  938. unitinits.emit_tai(
  939. Tai_const.Createname(make_mangledname('FINALIZE$',current_module.localsymtable,''),AT_FUNCTION,0),
  940. voidcodepointertype)
  941. else
  942. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  943. inc(count);
  944. end;
  945. { fill in tablecount }
  946. tablecountplaceholder.replace(tai_const.Create_aint(count),aluuinttype);
  947. tablecountplaceholder.free;
  948. { Add to data segment }
  949. tabledef:=unitinits.end_anonymous_record;
  950. current_asmdata.asmlists[al_globals].concatlist(
  951. unitinits.get_final_asmlist(
  952. current_asmdata.DefineAsmSymbol('INITFINAL',AB_GLOBAL,AT_DATA,tabledef),
  953. tabledef,
  954. sec_data,'INITFINAL',sizeof(pint)
  955. )
  956. );
  957. unitinits.free;
  958. end;
  959. class procedure tnodeutils.InsertThreadvarTablesTable;
  960. var
  961. hp : tused_unit;
  962. tcb: ttai_typedconstbuilder;
  963. count: longint;
  964. sym: tasmsymbol;
  965. placeholder: ttypedconstplaceholder;
  966. tabledef: tdef;
  967. begin
  968. if (tf_section_threadvars in target_info.flags) then
  969. exit;
  970. count:=0;
  971. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  972. tcb.begin_anonymous_record('',1,sizeof(pint),
  973. targetinfos[target_info.system]^.alignment.recordalignmin,
  974. targetinfos[target_info.system]^.alignment.maxCrecordalign
  975. );
  976. placeholder:=tcb.emit_placeholder(u32inttype);
  977. hp:=tused_unit(usedunits.first);
  978. while assigned(hp) do
  979. begin
  980. if (hp.u.flags and uf_threadvars)=uf_threadvars then
  981. begin
  982. sym:=current_asmdata.RefAsmSymbol(make_mangledname('THREADVARLIST',hp.u.globalsymtable,''),AT_DATA,true);
  983. tcb.emit_tai(
  984. tai_const.Create_sym(sym),
  985. voidpointertype);
  986. current_module.add_extern_asmsym(sym);
  987. inc(count);
  988. end;
  989. hp:=tused_unit(hp.next);
  990. end;
  991. { Add program threadvars, if any }
  992. if (current_module.flags and uf_threadvars)=uf_threadvars then
  993. begin
  994. sym:=current_asmdata.RefAsmSymbol(make_mangledname('THREADVARLIST',current_module.localsymtable,''),AT_DATA,true);
  995. tcb.emit_tai(
  996. Tai_const.Create_sym(sym),
  997. voidpointertype);
  998. inc(count);
  999. end;
  1000. { set the count at the start }
  1001. placeholder.replace(tai_const.Create_32bit(count),u32inttype);
  1002. placeholder.free;
  1003. { insert in data segment }
  1004. tabledef:=tcb.end_anonymous_record;
  1005. sym:=current_asmdata.DefineAsmSymbol('FPC_THREADVARTABLES',AB_GLOBAL,AT_DATA,tabledef);
  1006. current_asmdata.asmlists[al_globals].concatlist(
  1007. tcb.get_final_asmlist(
  1008. sym,tabledef,sec_data,'FPC_THREADVARTABLES',sizeof(pint)
  1009. )
  1010. );
  1011. tcb.free;
  1012. end;
  1013. procedure AddToThreadvarList(p:TObject;arg:pointer);
  1014. var
  1015. tcb: ttai_typedconstbuilder;
  1016. field1, field2: tsym;
  1017. begin
  1018. if (tsym(p).typ=staticvarsym) and
  1019. (vo_is_thread_var in tstaticvarsym(p).varoptions) then
  1020. begin
  1021. tcb:=ttai_typedconstbuilder(arg);
  1022. { address of threadvar }
  1023. tcb.emit_tai(tai_const.Createname(tstaticvarsym(p).mangledname,0),
  1024. cpointerdef.getreusable(
  1025. get_threadvar_record(tstaticvarsym(p).vardef,field1,field2)
  1026. )
  1027. );
  1028. { size of threadvar }
  1029. tcb.emit_ord_const(tstaticvarsym(p).getsize,u32inttype);
  1030. end;
  1031. end;
  1032. class procedure tnodeutils.InsertThreadvars;
  1033. var
  1034. s : string;
  1035. tcb: ttai_typedconstbuilder;
  1036. sym: tasmsymbol;
  1037. tabledef: trecorddef;
  1038. add : boolean;
  1039. begin
  1040. if (tf_section_threadvars in target_info.flags) then
  1041. exit;
  1042. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1043. tabledef:=tcb.begin_anonymous_record('',1,sizeof(pint),
  1044. targetinfos[target_info.system]^.alignment.recordalignmin,
  1045. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1046. if assigned(current_module.globalsymtable) then
  1047. current_module.globalsymtable.SymList.ForEachCall(@AddToThreadvarList,tcb);
  1048. current_module.localsymtable.SymList.ForEachCall(@AddToThreadvarList,tcb);
  1049. if trecordsymtable(tabledef.symtable).datasize<>0 then
  1050. { terminator }
  1051. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1052. tcb.end_anonymous_record;
  1053. add:=trecordsymtable(tabledef.symtable).datasize<>0;
  1054. if add then
  1055. begin
  1056. s:=make_mangledname('THREADVARLIST',current_module.localsymtable,'');
  1057. sym:=current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA_FORCEINDIRECT,tabledef);
  1058. current_asmdata.asmlists[al_globals].concatlist(
  1059. tcb.get_final_asmlist(sym,tabledef,sec_data,s,sizeof(pint)));
  1060. current_module.flags:=current_module.flags or uf_threadvars;
  1061. current_module.add_public_asmsym(sym);
  1062. end
  1063. else
  1064. s:='';
  1065. tcb.Free;
  1066. end;
  1067. class procedure tnodeutils.InsertRuntimeInitsTablesTable(const prefix,tablename:string;unitflag:cardinal);
  1068. var
  1069. hp: tused_unit;
  1070. tcb: ttai_typedconstbuilder;
  1071. countplaceholder: ttypedconstplaceholder;
  1072. tabledef: tdef;
  1073. count: longint;
  1074. begin
  1075. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1076. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1077. targetinfos[target_info.system]^.alignment.recordalignmin,
  1078. targetinfos[target_info.system]^.alignment.maxCrecordalign
  1079. );
  1080. { placeholder for the count }
  1081. countplaceholder:=tcb.emit_placeholder(ptruinttype);
  1082. count:=0;
  1083. hp:=tused_unit(usedunits.first);
  1084. while assigned(hp) do
  1085. begin
  1086. if (hp.u.flags and unitflag)=unitflag then
  1087. begin
  1088. tcb.emit_tai(
  1089. Tai_const.Createname(make_mangledname(prefix,hp.u.globalsymtable,''),0),
  1090. voidcodepointertype);
  1091. inc(count);
  1092. end;
  1093. hp:=tused_unit(hp.next);
  1094. end;
  1095. { Add items from program, if any }
  1096. if (current_module.flags and unitflag)=unitflag then
  1097. begin
  1098. tcb.emit_tai(
  1099. Tai_const.Createname(make_mangledname(prefix,current_module.localsymtable,''),0),
  1100. voidcodepointertype);
  1101. inc(count);
  1102. end;
  1103. { Insert TableCount at start }
  1104. countplaceholder.replace(Tai_const.Create_pint(count),ptruinttype);
  1105. countplaceholder.free;
  1106. { insert in data segment }
  1107. tabledef:=tcb.end_anonymous_record;
  1108. current_asmdata.asmlists[al_globals].concatlist(
  1109. tcb.get_final_asmlist(
  1110. current_asmdata.DefineAsmSymbol(tablename,AB_GLOBAL,AT_DATA,tabledef),
  1111. tabledef,
  1112. sec_data,tablename,sizeof(pint)
  1113. )
  1114. );
  1115. tcb.free;
  1116. end;
  1117. class procedure tnodeutils.InsertRuntimeInits(const prefix:string;list:TLinkedList;unitflag:cardinal);
  1118. var
  1119. s: string;
  1120. item: TTCInitItem;
  1121. tcb: ttai_typedconstbuilder;
  1122. rawdatadef: tdef;
  1123. begin
  1124. item:=TTCInitItem(list.First);
  1125. if item=nil then
  1126. exit;
  1127. s:=make_mangledname(prefix,current_module.localsymtable,'');
  1128. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1129. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1130. targetinfos[target_info.system]^.alignment.recordalignmin,
  1131. targetinfos[target_info.system]^.alignment.maxCrecordalign );
  1132. repeat
  1133. { optimize away unused local/static symbols }
  1134. if (item.sym.refs>0) or (item.sym.owner.symtabletype=globalsymtable) then
  1135. begin
  1136. { address to initialize }
  1137. tcb.queue_init(voidpointertype);
  1138. rawdatadef:=carraydef.getreusable(cansichartype,tstaticvarsym(item.sym).vardef.size);
  1139. tcb.queue_vecn(rawdatadef,item.offset);
  1140. tcb.queue_typeconvn(cpointerdef.getreusable(tstaticvarsym(item.sym).vardef),cpointerdef.getreusable(rawdatadef));
  1141. tcb.queue_emit_staticvar(tstaticvarsym(item.sym));
  1142. { value with which to initialize }
  1143. tcb.emit_tai(Tai_const.Create_sym(item.datalabel),item.datadef)
  1144. end;
  1145. item:=TTCInitItem(item.Next);
  1146. until item=nil;
  1147. { end-of-list marker }
  1148. tcb.emit_tai(Tai_const.Create_nil_dataptr,voidpointertype);
  1149. rawdatadef:=tcb.end_anonymous_record;
  1150. current_asmdata.asmlists[al_globals].concatList(
  1151. tcb.get_final_asmlist(
  1152. current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA,rawdatadef),
  1153. rawdatadef,sec_data,s,sizeof(pint)));
  1154. tcb.free;
  1155. current_module.flags:=current_module.flags or unitflag;
  1156. end;
  1157. class procedure tnodeutils.InsertWideInits;
  1158. begin
  1159. InsertRuntimeInits('WIDEINITS',current_asmdata.WideInits,uf_wideinits);
  1160. end;
  1161. class procedure tnodeutils.InsertResStrInits;
  1162. begin
  1163. InsertRuntimeInits('RESSTRINITS',current_asmdata.ResStrInits,uf_resstrinits);
  1164. end;
  1165. class procedure tnodeutils.InsertWideInitsTablesTable;
  1166. begin
  1167. InsertRuntimeInitsTablesTable('WIDEINITS','FPC_WIDEINITTABLES',uf_wideinits);
  1168. end;
  1169. class procedure tnodeutils.InsertResStrTablesTable;
  1170. begin
  1171. InsertRuntimeInitsTablesTable('RESSTRINITS','FPC_RESSTRINITTABLES',uf_resstrinits);
  1172. end;
  1173. class procedure tnodeutils.InsertResourceTablesTable;
  1174. var
  1175. hp : tmodule;
  1176. count : longint;
  1177. tcb : ttai_typedconstbuilder;
  1178. countplaceholder : ttypedconstplaceholder;
  1179. tabledef: tdef;
  1180. begin
  1181. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1182. count:=0;
  1183. hp:=tmodule(loaded_units.first);
  1184. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1185. targetinfos[target_info.system]^.alignment.recordalignmin,
  1186. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1187. countplaceholder:=tcb.emit_placeholder(ptruinttype);
  1188. while assigned(hp) do
  1189. begin
  1190. If (hp.flags and uf_has_resourcestrings)=uf_has_resourcestrings then
  1191. begin
  1192. tcb.emit_tai(Tai_const.Create_sym(
  1193. ctai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_start('RESSTR',hp.localsymtable,[tcdssso_register_asmsym,tcdssso_use_indirect])),
  1194. voidpointertype
  1195. );
  1196. tcb.emit_tai(Tai_const.Create_sym(
  1197. ctai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_end('RESSTR',hp.localsymtable,[tcdssso_register_asmsym,tcdssso_use_indirect])),
  1198. voidpointertype
  1199. );
  1200. inc(count);
  1201. end;
  1202. hp:=tmodule(hp.next);
  1203. end;
  1204. { Insert TableCount at start }
  1205. countplaceholder.replace(Tai_const.Create_pint(count),ptruinttype);
  1206. countplaceholder.free;
  1207. { Add to data segment }
  1208. tabledef:=tcb.end_anonymous_record;
  1209. current_asmdata.AsmLists[al_globals].concatList(
  1210. tcb.get_final_asmlist(
  1211. current_asmdata.DefineAsmSymbol('FPC_RESOURCESTRINGTABLES',AB_GLOBAL,AT_DATA,tabledef),
  1212. tabledef,sec_rodata,'FPC_RESOURCESTRINGTABLES',sizeof(pint)
  1213. )
  1214. );
  1215. tcb.free;
  1216. end;
  1217. class procedure tnodeutils.InsertResourceInfo(ResourcesUsed: boolean);
  1218. var
  1219. tcb: ttai_typedconstbuilder;
  1220. begin
  1221. if (target_res.id in [res_elf,res_macho,res_xcoff]) or
  1222. { generate the FPC_RESLOCATION symbol even when using external resources,
  1223. because in SysInit we can only reference it unconditionally }
  1224. ((target_res.id=res_ext) and (target_info.system in systems_darwin)) then
  1225. begin
  1226. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1227. if ResourcesUsed and (target_res.id<>res_ext) then
  1228. tcb.emit_tai(Tai_const.Createname('FPC_RESSYMBOL',0),voidpointertype)
  1229. else
  1230. { Nil pointer to resource information }
  1231. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1232. current_asmdata.asmlists[al_globals].concatList(
  1233. tcb.get_final_asmlist(
  1234. current_asmdata.DefineAsmSymbol('FPC_RESLOCATION',AB_GLOBAL,AT_DATA,voidpointertype),
  1235. voidpointertype,
  1236. sec_rodata,
  1237. 'FPC_RESLOCATION',
  1238. sizeof(puint)
  1239. )
  1240. );
  1241. tcb.free;
  1242. end;
  1243. end;
  1244. class procedure tnodeutils.InsertMemorySizes;
  1245. var
  1246. tcb: ttai_typedconstbuilder;
  1247. s: shortstring;
  1248. sym: tasmsymbol;
  1249. def: tdef;
  1250. begin
  1251. { Insert Ident of the compiler in the .fpc.version section }
  1252. tcb:=ctai_typedconstbuilder.create([tcalo_no_dead_strip]);
  1253. s:='FPC '+full_version_string+
  1254. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  1255. def:=carraydef.getreusable(cansichartype,length(s));
  1256. tcb.maybe_begin_aggregate(def);
  1257. tcb.emit_tai(Tai_string.Create(s),def);
  1258. tcb.maybe_end_aggregate(def);
  1259. sym:=current_asmdata.DefineAsmSymbol('__fpc_ident',AB_LOCAL,AT_DATA,def);
  1260. current_asmdata.asmlists[al_globals].concatlist(
  1261. tcb.get_final_asmlist(sym,def,sec_fpc,'version',const_align(32))
  1262. );
  1263. tcb.free;
  1264. if (tf_emit_stklen in target_info.flags) or
  1265. not(tf_no_generic_stackcheck in target_info.flags) then
  1266. begin
  1267. { stacksize can be specified and is now simulated }
  1268. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1269. tcb.emit_tai(Tai_const.Create_pint(stacksize),ptruinttype);
  1270. sym:=current_asmdata.DefineAsmSymbol('__stklen',AB_GLOBAL,AT_DATA,ptruinttype);
  1271. current_asmdata.asmlists[al_globals].concatlist(
  1272. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__stklen',sizeof(pint))
  1273. );
  1274. tcb.free;
  1275. end;
  1276. {$IFDEF POWERPC}
  1277. { AmigaOS4 "stack cookie" support }
  1278. if ( target_info.system = system_powerpc_amiga ) then
  1279. begin
  1280. { this symbol is needed to ignite powerpc amigaos' }
  1281. { stack allocation magic for us with the given stack size. }
  1282. { note: won't work for m68k amigaos or morphos. (KB) }
  1283. str(stacksize,s);
  1284. s:='$STACK: '+s+#0;
  1285. def:=carraydef.getreusable(cansichartype,length(s));
  1286. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1287. tcb.maybe_begin_aggregate(def);
  1288. tcb.emit_tai(Tai_string.Create(s),def);
  1289. tcb.maybe_end_aggregate(def);
  1290. sym:=current_asmdata.DefineAsmSymbol('__stack_cookie',AB_GLOBAL,AT_DATA,def);
  1291. current_asmdata.asmlists[al_globals].concatlist(
  1292. tcb.get_final_asmlist(sym,def,sec_data,'__stack_cookie',sizeof(pint))
  1293. );
  1294. tcb.free;
  1295. end;
  1296. {$ENDIF POWERPC}
  1297. { Initial heapsize }
  1298. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1299. tcb.emit_tai(Tai_const.Create_pint(heapsize),ptruinttype);
  1300. sym:=current_asmdata.DefineAsmSymbol('__heapsize',AB_GLOBAL,AT_DATA,ptruinttype);
  1301. current_asmdata.asmlists[al_globals].concatlist(
  1302. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__heapsize',sizeof(pint))
  1303. );
  1304. tcb.free;
  1305. { allocate an initial heap on embedded systems }
  1306. if target_info.system in systems_embedded then
  1307. begin
  1308. { tai_datablock cannot yet be handled via the high level typed const
  1309. builder, because it implies the generation of a symbol, while this
  1310. is separate in the builder }
  1311. maybe_new_object_file(current_asmdata.asmlists[al_globals]);
  1312. new_section(current_asmdata.asmlists[al_globals],sec_bss,'__fpc_initialheap',current_settings.alignment.varalignmax);
  1313. current_asmdata.asmlists[al_globals].concat(tai_datablock.Create_global('__fpc_initialheap',heapsize,carraydef.getreusable(u8inttype,heapsize)));
  1314. end;
  1315. { Valgrind usage }
  1316. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1317. tcb.emit_ord_const(byte(cs_gdb_valgrind in current_settings.globalswitches),u8inttype);
  1318. sym:=current_asmdata.DefineAsmSymbol('__fpc_valgrind',AB_GLOBAL,AT_DATA,u8inttype);
  1319. current_asmdata.asmlists[al_globals].concatlist(
  1320. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__fpc_valgrind',sizeof(pint))
  1321. );
  1322. tcb.free;
  1323. end;
  1324. class procedure tnodeutils.InsertObjectInfo;
  1325. begin
  1326. { don't do anything by default }
  1327. end;
  1328. class procedure tnodeutils.add_main_procdef_paras(pd: tdef);
  1329. var
  1330. pvs: tparavarsym;
  1331. begin
  1332. { stub for calling FPC_SYSTEMMAIN from the C main -> add argc/argv/argp }
  1333. if (tprocdef(pd).proctypeoption=potype_mainstub) and
  1334. (target_info.system in (systems_darwin+[system_powerpc_macos]+systems_aix)) then
  1335. begin
  1336. pvs:=cparavarsym.create('ARGC',1,vs_const,s32inttype,[]);
  1337. tprocdef(pd).parast.insert(pvs);
  1338. pvs:=cparavarsym.create('ARGV',2,vs_const,cpointerdef.getreusable(charpointertype),[]);
  1339. tprocdef(pd).parast.insert(pvs);
  1340. pvs:=cparavarsym.create('ARGP',3,vs_const,cpointerdef.getreusable(charpointertype),[]);
  1341. tprocdef(pd).parast.insert(pvs);
  1342. tprocdef(pd).calcparas;
  1343. end;
  1344. end;
  1345. end.