ngenutil.pas 61 KB

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