ngenutil.pas 60 KB

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