ngenutil.pas 62 KB

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