ngenutil.pas 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  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. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  991. { tablecount }
  992. unitinits.emit_ord_const(entries.count,aluuinttype);
  993. { initcount (initialised at run time }
  994. unitinits.emit_ord_const(0,aluuinttype);
  995. for i:=0 to entries.count-1 do
  996. begin
  997. entry:=pinitfinalentry(entries[i]);
  998. if assigned(entry^.initpd) or assigned(entry^.finipd) then
  999. begin
  1000. if assigned(entry^.initpd) then
  1001. begin
  1002. unitinits.emit_procdef_const(entry^.initpd);
  1003. if entry^.module<>current_module then
  1004. current_module.addimportedsym(entry^.initpd.procsym);
  1005. end
  1006. else
  1007. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  1008. if assigned(entry^.finipd) then
  1009. begin
  1010. unitinits.emit_procdef_const(entry^.finipd);
  1011. if entry^.module<>current_module then
  1012. current_module.addimportedsym(entry^.finipd.procsym);
  1013. end
  1014. else
  1015. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  1016. end
  1017. else
  1018. begin
  1019. nameinit:='';
  1020. namefini:='';
  1021. if entry^.initfunc<>'' then
  1022. begin
  1023. nameinit:=entry^.initfunc;
  1024. unitinits.emit_tai(
  1025. Tai_const.Createname(nameinit,AT_FUNCTION,0),
  1026. voidcodepointertype);
  1027. end
  1028. else
  1029. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  1030. if entry^.finifunc<>'' then
  1031. begin
  1032. namefini:=entry^.finifunc;
  1033. unitinits.emit_tai(
  1034. Tai_const.Createname(namefini,AT_FUNCTION,0),
  1035. voidcodepointertype);
  1036. end
  1037. else
  1038. unitinits.emit_tai(Tai_const.Create_nil_codeptr,voidcodepointertype);
  1039. if entry^.module<>current_module then
  1040. add_initfinal_import(entry^.module.localsymtable);
  1041. end;
  1042. end;
  1043. { Add to data segment }
  1044. tabledef:=unitinits.end_anonymous_record;
  1045. current_asmdata.asmlists[al_globals].concatlist(
  1046. unitinits.get_final_asmlist(
  1047. current_asmdata.DefineAsmSymbol('INITFINAL',AB_GLOBAL,AT_DATA,tabledef),
  1048. tabledef,
  1049. sec_data,'INITFINAL',sizeof(pint)
  1050. )
  1051. );
  1052. unitinits.free;
  1053. end;
  1054. class procedure tnodeutils.InsertThreadvarTablesTable;
  1055. var
  1056. hp : tused_unit;
  1057. tcb: ttai_typedconstbuilder;
  1058. count: longint;
  1059. sym: tasmsymbol;
  1060. placeholder: ttypedconstplaceholder;
  1061. tabledef: tdef;
  1062. begin
  1063. if (tf_section_threadvars in target_info.flags) then
  1064. exit;
  1065. count:=0;
  1066. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1067. tcb.begin_anonymous_record('',1,sizeof(pint),
  1068. targetinfos[target_info.system]^.alignment.recordalignmin,
  1069. targetinfos[target_info.system]^.alignment.maxCrecordalign
  1070. );
  1071. placeholder:=tcb.emit_placeholder(u32inttype);
  1072. hp:=tused_unit(usedunits.first);
  1073. while assigned(hp) do
  1074. begin
  1075. if mf_threadvars in hp.u.moduleflags then
  1076. begin
  1077. sym:=current_asmdata.RefAsmSymbol(make_mangledname('THREADVARLIST',hp.u.globalsymtable,''),AT_DATA,true);
  1078. tcb.emit_tai(
  1079. tai_const.Create_sym(sym),
  1080. voidpointertype);
  1081. current_module.add_extern_asmsym(sym);
  1082. inc(count);
  1083. end;
  1084. hp:=tused_unit(hp.next);
  1085. end;
  1086. { Add program threadvars, if any }
  1087. if mf_threadvars in current_module.moduleflags then
  1088. begin
  1089. sym:=current_asmdata.RefAsmSymbol(make_mangledname('THREADVARLIST',current_module.localsymtable,''),AT_DATA,true);
  1090. tcb.emit_tai(
  1091. Tai_const.Create_sym(sym),
  1092. voidpointertype);
  1093. inc(count);
  1094. end;
  1095. { set the count at the start }
  1096. placeholder.replace(tai_const.Create_32bit(count),u32inttype);
  1097. placeholder.free;
  1098. { insert in data segment }
  1099. tabledef:=tcb.end_anonymous_record;
  1100. sym:=current_asmdata.DefineAsmSymbol('FPC_THREADVARTABLES',AB_GLOBAL,AT_DATA,tabledef);
  1101. current_asmdata.asmlists[al_globals].concatlist(
  1102. tcb.get_final_asmlist(
  1103. sym,tabledef,sec_data,'FPC_THREADVARTABLES',sizeof(pint)
  1104. )
  1105. );
  1106. tcb.free;
  1107. end;
  1108. procedure AddToThreadvarList(p:TObject;arg:pointer);
  1109. var
  1110. tcb: ttai_typedconstbuilder;
  1111. field1, field2: tsym;
  1112. begin
  1113. if (tsym(p).typ=staticvarsym) and
  1114. (vo_is_thread_var in tstaticvarsym(p).varoptions) then
  1115. begin
  1116. tcb:=ttai_typedconstbuilder(arg);
  1117. { address of threadvar }
  1118. tcb.emit_tai(tai_const.Createname(tstaticvarsym(p).mangledname,0),
  1119. cpointerdef.getreusable(
  1120. get_threadvar_record(tstaticvarsym(p).vardef,field1,field2)
  1121. )
  1122. );
  1123. { size of threadvar }
  1124. tcb.emit_ord_const(tstaticvarsym(p).getsize,u32inttype);
  1125. end;
  1126. end;
  1127. class procedure tnodeutils.InsertThreadvars;
  1128. var
  1129. s : string;
  1130. tcb: ttai_typedconstbuilder;
  1131. sym: tasmsymbol;
  1132. tabledef: trecorddef;
  1133. add : boolean;
  1134. begin
  1135. if (tf_section_threadvars in target_info.flags) then
  1136. exit;
  1137. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1138. tabledef:=tcb.begin_anonymous_record('',1,sizeof(pint),
  1139. targetinfos[target_info.system]^.alignment.recordalignmin,
  1140. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1141. if assigned(current_module.globalsymtable) then
  1142. current_module.globalsymtable.SymList.ForEachCall(@AddToThreadvarList,tcb);
  1143. current_module.localsymtable.SymList.ForEachCall(@AddToThreadvarList,tcb);
  1144. if trecordsymtable(tabledef.symtable).datasize<>0 then
  1145. { terminator }
  1146. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1147. tcb.end_anonymous_record;
  1148. add:=trecordsymtable(tabledef.symtable).datasize<>0;
  1149. if add then
  1150. begin
  1151. s:=make_mangledname('THREADVARLIST',current_module.localsymtable,'');
  1152. sym:=current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA_FORCEINDIRECT,tabledef);
  1153. current_asmdata.asmlists[al_globals].concatlist(
  1154. tcb.get_final_asmlist(sym,tabledef,sec_data,s,sizeof(pint)));
  1155. include(current_module.moduleflags,mf_threadvars);
  1156. current_module.add_public_asmsym(sym);
  1157. end
  1158. else
  1159. s:='';
  1160. tcb.Free;
  1161. end;
  1162. class procedure tnodeutils.InsertRuntimeInitsTablesTable(const prefix,tablename:string;unitflag:tmoduleflag);
  1163. var
  1164. hp: tused_unit;
  1165. tcb: ttai_typedconstbuilder;
  1166. countplaceholder: ttypedconstplaceholder;
  1167. tabledef: tdef;
  1168. count: longint;
  1169. begin
  1170. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1171. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1172. targetinfos[target_info.system]^.alignment.recordalignmin,
  1173. targetinfos[target_info.system]^.alignment.maxCrecordalign
  1174. );
  1175. { placeholder for the count }
  1176. countplaceholder:=tcb.emit_placeholder(sizesinttype);
  1177. count:=0;
  1178. hp:=tused_unit(usedunits.first);
  1179. while assigned(hp) do
  1180. begin
  1181. if unitflag in hp.u.moduleflags then
  1182. begin
  1183. tcb.emit_tai(
  1184. Tai_const.Createname(make_mangledname(prefix,hp.u.globalsymtable,''),0),
  1185. voidcodepointertype);
  1186. inc(count);
  1187. end;
  1188. hp:=tused_unit(hp.next);
  1189. end;
  1190. { Add items from program, if any }
  1191. if unitflag in current_module.moduleflags then
  1192. begin
  1193. tcb.emit_tai(
  1194. Tai_const.Createname(make_mangledname(prefix,current_module.localsymtable,''),0),
  1195. voidcodepointertype);
  1196. inc(count);
  1197. end;
  1198. { Insert TableCount at start }
  1199. countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
  1200. countplaceholder.free;
  1201. { insert in data segment }
  1202. tabledef:=tcb.end_anonymous_record;
  1203. current_asmdata.asmlists[al_globals].concatlist(
  1204. tcb.get_final_asmlist(
  1205. current_asmdata.DefineAsmSymbol(tablename,AB_GLOBAL,AT_DATA,tabledef),
  1206. tabledef,
  1207. sec_data,tablename,sizeof(pint)
  1208. )
  1209. );
  1210. tcb.free;
  1211. end;
  1212. class procedure tnodeutils.InsertRuntimeInits(const prefix:string;list:TLinkedList;unitflag:tmoduleflag);
  1213. var
  1214. s: string;
  1215. item: TTCInitItem;
  1216. tcb: ttai_typedconstbuilder;
  1217. rawdatadef: tdef;
  1218. begin
  1219. item:=TTCInitItem(list.First);
  1220. if item=nil then
  1221. exit;
  1222. s:=make_mangledname(prefix,current_module.localsymtable,'');
  1223. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1224. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1225. targetinfos[target_info.system]^.alignment.recordalignmin,
  1226. targetinfos[target_info.system]^.alignment.maxCrecordalign );
  1227. repeat
  1228. { optimize away unused local/static symbols }
  1229. if (item.sym.refs>0) or (item.sym.owner.symtabletype=globalsymtable) then
  1230. begin
  1231. { address to initialize }
  1232. tcb.queue_init(voidpointertype);
  1233. rawdatadef:=carraydef.getreusable(cansichartype,tstaticvarsym(item.sym).vardef.size);
  1234. tcb.queue_vecn(rawdatadef,item.offset);
  1235. tcb.queue_typeconvn(cpointerdef.getreusable(tstaticvarsym(item.sym).vardef),cpointerdef.getreusable(rawdatadef));
  1236. tcb.queue_emit_staticvar(tstaticvarsym(item.sym));
  1237. { value with which to initialize }
  1238. tcb.emit_tai(Tai_const.Create_sym(item.datalabel),item.datadef)
  1239. end;
  1240. item:=TTCInitItem(item.Next);
  1241. until item=nil;
  1242. { end-of-list marker }
  1243. tcb.emit_tai(Tai_const.Create_nil_dataptr,voidpointertype);
  1244. rawdatadef:=tcb.end_anonymous_record;
  1245. current_asmdata.asmlists[al_globals].concatList(
  1246. tcb.get_final_asmlist(
  1247. current_asmdata.DefineAsmSymbol(s,AB_GLOBAL,AT_DATA,rawdatadef),
  1248. rawdatadef,sec_data,s,sizeof(pint)));
  1249. tcb.free;
  1250. include(current_module.moduleflags,unitflag);
  1251. end;
  1252. class procedure tnodeutils.InsertWideInits;
  1253. begin
  1254. InsertRuntimeInits('WIDEINITS',current_asmdata.WideInits,mf_wideinits);
  1255. end;
  1256. class procedure tnodeutils.InsertResStrInits;
  1257. begin
  1258. InsertRuntimeInits('RESSTRINITS',current_asmdata.ResStrInits,mf_resstrinits);
  1259. end;
  1260. class procedure tnodeutils.InsertWideInitsTablesTable;
  1261. begin
  1262. InsertRuntimeInitsTablesTable('WIDEINITS','FPC_WIDEINITTABLES',mf_wideinits);
  1263. end;
  1264. class procedure tnodeutils.InsertResStrTablesTable;
  1265. begin
  1266. InsertRuntimeInitsTablesTable('RESSTRINITS','FPC_RESSTRINITTABLES',mf_resstrinits);
  1267. end;
  1268. class procedure tnodeutils.InsertResourceTablesTable;
  1269. var
  1270. hp : tmodule;
  1271. count : longint;
  1272. tcb : ttai_typedconstbuilder;
  1273. countplaceholder : ttypedconstplaceholder;
  1274. tabledef: tdef;
  1275. begin
  1276. tcb:=ctai_typedconstbuilder.create([tcalo_make_dead_strippable,tcalo_new_section]);
  1277. count:=0;
  1278. hp:=tmodule(loaded_units.first);
  1279. tcb.begin_anonymous_record('',default_settings.packrecords,sizeof(pint),
  1280. targetinfos[target_info.system]^.alignment.recordalignmin,
  1281. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1282. countplaceholder:=tcb.emit_placeholder(sizesinttype);
  1283. while assigned(hp) do
  1284. begin
  1285. if mf_has_resourcestrings in hp.moduleflags then
  1286. begin
  1287. tcb.emit_tai(Tai_const.Create_sym(
  1288. ctai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_start('RESSTR',hp.localsymtable,[tcdssso_register_asmsym,tcdssso_use_indirect])),
  1289. voidpointertype
  1290. );
  1291. tcb.emit_tai(Tai_const.Create_sym(
  1292. ctai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_end('RESSTR',hp.localsymtable,[tcdssso_register_asmsym,tcdssso_use_indirect])),
  1293. voidpointertype
  1294. );
  1295. inc(count);
  1296. end;
  1297. hp:=tmodule(hp.next);
  1298. end;
  1299. { Insert TableCount at start }
  1300. countplaceholder.replace(Tai_const.Create_sizeint(count),sizesinttype);
  1301. countplaceholder.free;
  1302. { Add to data segment }
  1303. tabledef:=tcb.end_anonymous_record;
  1304. current_asmdata.AsmLists[al_globals].concatList(
  1305. tcb.get_final_asmlist(
  1306. current_asmdata.DefineAsmSymbol('FPC_RESOURCESTRINGTABLES',AB_GLOBAL,AT_DATA,tabledef),
  1307. tabledef,sec_rodata,'FPC_RESOURCESTRINGTABLES',sizeof(pint)
  1308. )
  1309. );
  1310. tcb.free;
  1311. end;
  1312. class procedure tnodeutils.InsertResourceInfo(ResourcesUsed: boolean);
  1313. var
  1314. tcb: ttai_typedconstbuilder;
  1315. begin
  1316. if (target_res.id in [res_elf,res_macho,res_xcoff]) or
  1317. { generate the FPC_RESLOCATION symbol even when using external resources,
  1318. because in SysInit we can only reference it unconditionally }
  1319. ((target_res.id=res_ext) and (target_info.system in systems_darwin)) then
  1320. begin
  1321. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1322. if ResourcesUsed and (target_res.id<>res_ext) then
  1323. tcb.emit_tai(Tai_const.Createname('FPC_RESSYMBOL',0),voidpointertype)
  1324. else
  1325. { Nil pointer to resource information }
  1326. tcb.emit_tai(tai_const.Create_nil_dataptr,voidpointertype);
  1327. current_asmdata.asmlists[al_globals].concatList(
  1328. tcb.get_final_asmlist(
  1329. current_asmdata.DefineAsmSymbol('FPC_RESLOCATION',AB_GLOBAL,AT_DATA,voidpointertype),
  1330. voidpointertype,
  1331. sec_rodata,
  1332. 'FPC_RESLOCATION',
  1333. sizeof(puint)
  1334. )
  1335. );
  1336. tcb.free;
  1337. end;
  1338. end;
  1339. class procedure tnodeutils.InsertMemorySizes;
  1340. var
  1341. tcb: ttai_typedconstbuilder;
  1342. s: shortstring;
  1343. sym: tasmsymbol;
  1344. def: tdef;
  1345. begin
  1346. { Insert Ident of the compiler in the .fpc.version section }
  1347. tcb:=ctai_typedconstbuilder.create([tcalo_no_dead_strip]);
  1348. s:='FPC '+full_version_string+
  1349. ' ['+date_string+'] for '+target_cpu_string+' - '+target_info.shortname;
  1350. {$ifdef m68k}
  1351. { Ensure that the size of s is multiple of 2 to avoid problems
  1352. like on m68k-amiga which has a .balignw just after,
  1353. causes an assembler error }
  1354. while (length(s) mod 2) <> 0 do
  1355. s:=s+' ';
  1356. {$endif m68k}
  1357. def:=carraydef.getreusable(cansichartype,length(s));
  1358. tcb.maybe_begin_aggregate(def);
  1359. tcb.emit_tai(Tai_string.Create(s),def);
  1360. tcb.maybe_end_aggregate(def);
  1361. sym:=current_asmdata.DefineAsmSymbol('__fpc_ident',AB_LOCAL,AT_DATA,def);
  1362. current_asmdata.asmlists[al_globals].concatlist(
  1363. tcb.get_final_asmlist(sym,def,sec_fpc,'version',const_align(32))
  1364. );
  1365. tcb.free;
  1366. if (tf_emit_stklen in target_info.flags) or
  1367. not(tf_no_generic_stackcheck in target_info.flags) then
  1368. begin
  1369. { stacksize can be specified and is now simulated }
  1370. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1371. tcb.emit_tai(Tai_const.Create_int_dataptr(stacksize),ptruinttype);
  1372. sym:=current_asmdata.DefineAsmSymbol('__stklen',AB_GLOBAL,AT_DATA,ptruinttype);
  1373. current_asmdata.asmlists[al_globals].concatlist(
  1374. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__stklen',sizeof(pint))
  1375. );
  1376. tcb.free;
  1377. end;
  1378. {$IFDEF POWERPC}
  1379. { AmigaOS4 "stack cookie" support }
  1380. if ( target_info.system = system_powerpc_amiga ) then
  1381. begin
  1382. { this symbol is needed to ignite powerpc amigaos' }
  1383. { stack allocation magic for us with the given stack size. }
  1384. { note: won't work for m68k amigaos or morphos. (KB) }
  1385. str(stacksize,s);
  1386. s:='$STACK: '+s+#0;
  1387. def:=carraydef.getreusable(cansichartype,length(s));
  1388. tcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  1389. tcb.maybe_begin_aggregate(def);
  1390. tcb.emit_tai(Tai_string.Create(s),def);
  1391. tcb.maybe_end_aggregate(def);
  1392. sym:=current_asmdata.DefineAsmSymbol('__stack_cookie',AB_GLOBAL,AT_DATA,def);
  1393. current_asmdata.asmlists[al_globals].concatlist(
  1394. tcb.get_final_asmlist(sym,def,sec_data,'__stack_cookie',sizeof(pint))
  1395. );
  1396. tcb.free;
  1397. end;
  1398. {$ENDIF POWERPC}
  1399. { Initial heapsize }
  1400. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1401. tcb.emit_tai(Tai_const.Create_int_dataptr(heapsize),ptruinttype);
  1402. sym:=current_asmdata.DefineAsmSymbol('__heapsize',AB_GLOBAL,AT_DATA,ptruinttype);
  1403. current_asmdata.asmlists[al_globals].concatlist(
  1404. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__heapsize',sizeof(pint))
  1405. );
  1406. tcb.free;
  1407. { allocate an initial heap on embedded systems }
  1408. if target_info.system in systems_embedded then
  1409. begin
  1410. { tai_datablock cannot yet be handled via the high level typed const
  1411. builder, because it implies the generation of a symbol, while this
  1412. is separate in the builder }
  1413. maybe_new_object_file(current_asmdata.asmlists[al_globals]);
  1414. new_section(current_asmdata.asmlists[al_globals],sec_bss,'__fpc_initialheap',current_settings.alignment.varalignmax);
  1415. current_asmdata.asmlists[al_globals].concat(tai_datablock.Create_global('__fpc_initialheap',heapsize,carraydef.getreusable(u8inttype,heapsize)));
  1416. end;
  1417. { Valgrind usage }
  1418. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_make_dead_strippable]);
  1419. tcb.emit_ord_const(byte(cs_gdb_valgrind in current_settings.globalswitches),u8inttype);
  1420. sym:=current_asmdata.DefineAsmSymbol('__fpc_valgrind',AB_GLOBAL,AT_DATA,u8inttype);
  1421. current_asmdata.asmlists[al_globals].concatlist(
  1422. tcb.get_final_asmlist(sym,ptruinttype,sec_data,'__fpc_valgrind',sizeof(pint))
  1423. );
  1424. tcb.free;
  1425. end;
  1426. class procedure tnodeutils.InsertObjectInfo;
  1427. begin
  1428. { don't do anything by default }
  1429. end;
  1430. class procedure tnodeutils.RegisterUsedAsmSym(sym: TAsmSymbol; def: tdef; compileronly: boolean);
  1431. begin
  1432. { don't do anything by default }
  1433. end;
  1434. class procedure tnodeutils.RegisterModuleInitFunction(pd: tprocdef);
  1435. begin
  1436. { setinitname may generate a new section -> don't add to the
  1437. current list, because we assume this remains a text section }
  1438. exportlib.setinitname(current_asmdata.AsmLists[al_pure_assembler],pd.mangledname);
  1439. end;
  1440. class procedure tnodeutils.RegisterModuleFiniFunction(pd: tprocdef);
  1441. begin
  1442. exportlib.setfininame(current_asmdata.AsmLists[al_pure_assembler],pd.mangledname);
  1443. end;
  1444. class procedure tnodeutils.GenerateObjCImageInfo;
  1445. var
  1446. tcb: ttai_typedconstbuilder;
  1447. begin
  1448. { first 4 bytes contain version information about this section (currently version 0),
  1449. next 4 bytes contain flags (currently only regarding whether the code in the object
  1450. file supports or requires garbage collection)
  1451. }
  1452. tcb:=ctai_typedconstbuilder.create([tcalo_new_section,tcalo_no_dead_strip]);
  1453. tcb.emit_ord_const(0,u64inttype);
  1454. current_asmdata.asmlists[al_objc_data].concatList(
  1455. tcb.get_final_asmlist(
  1456. current_asmdata.DefineAsmSymbol(target_asm.labelprefix+'_OBJC_IMAGE_INFO',AB_LOCAL,AT_DATA,u64inttype),
  1457. u64inttype,sec_objc_image_info,'_OBJC_IMAGE_INFO',sizeof(pint)
  1458. )
  1459. );
  1460. tcb.free;
  1461. end;
  1462. class procedure tnodeutils.add_main_procdef_paras(pd: tdef);
  1463. var
  1464. pvs: tparavarsym;
  1465. begin
  1466. { stub for calling FPC_SYSTEMMAIN from the C main -> add argc/argv/argp }
  1467. if (tprocdef(pd).proctypeoption=potype_mainstub) and
  1468. (target_info.system in (systems_darwin+[system_powerpc_macos]+systems_aix)) then
  1469. begin
  1470. pvs:=cparavarsym.create('ARGC',1,vs_const,s32inttype,[]);
  1471. tprocdef(pd).parast.insert(pvs);
  1472. pvs:=cparavarsym.create('ARGV',2,vs_const,cpointerdef.getreusable(charpointertype),[]);
  1473. tprocdef(pd).parast.insert(pvs);
  1474. pvs:=cparavarsym.create('ARGP',3,vs_const,cpointerdef.getreusable(charpointertype),[]);
  1475. tprocdef(pd).parast.insert(pvs);
  1476. tprocdef(pd).calcparas;
  1477. end
  1478. { package stub for Windows is a DLLMain }
  1479. else if (tprocdef(pd).proctypeoption=potype_pkgstub) and
  1480. (target_info.system in systems_all_windows+systems_nativent) then
  1481. begin
  1482. pvs:=cparavarsym.create('HINSTANCE',1,vs_const,uinttype,[]);
  1483. tprocdef(pd).parast.insert(pvs);
  1484. pvs:=cparavarsym.create('DLLREASON',2,vs_const,u32inttype,[]);
  1485. tprocdef(pd).parast.insert(pvs);
  1486. pvs:=cparavarsym.create('DLLPARAM',3,vs_const,voidpointertype,[]);
  1487. tprocdef(pd).parast.insert(pvs);
  1488. tprocdef(pd).returndef:=bool32type;
  1489. insert_funcret_para(tprocdef(pd));
  1490. tprocdef(pd).calcparas;
  1491. end;
  1492. end;
  1493. end.