aasmcnst.pas 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  1. {
  2. Copyright (c) 2014 by Jonas Maebe, member of the Free Pascal development
  3. team
  4. This unit implements typed constant data elements at the assembler level
  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 aasmcnst;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cclasses,globtype,constexp,
  23. aasmbase,aasmdata,aasmtai,
  24. symconst,symbase,symtype,symdef,symsym;
  25. type
  26. { typed const: integer/floating point/string/pointer/... const along with
  27. tdef info }
  28. ttypedconstkind = (tck_simple, tck_array, tck_record);
  29. { the type of the element and its def }
  30. tai_abstracttypedconst = class abstract (tai)
  31. private
  32. procedure setdef(def: tdef);
  33. protected
  34. fadetyp: ttypedconstkind;
  35. { the def of this element }
  36. fdef: tdef;
  37. public
  38. constructor create(_adetyp: ttypedconstkind; _def: tdef);
  39. property adetyp: ttypedconstkind read fadetyp;
  40. property def: tdef read fdef write setdef;
  41. end;
  42. { a simple data element; the value is stored as a tai }
  43. tai_simpletypedconst = class(tai_abstracttypedconst)
  44. private
  45. procedure setval(AValue: tai);
  46. protected
  47. fval: tai;
  48. public
  49. constructor create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  50. property val: tai read fval write setval;
  51. end;
  52. { an aggregate data element (record or array). Values are stored as an
  53. array of tsimpledataelement. }
  54. tai_aggregatetypedconst = class(tai_abstracttypedconst)
  55. public type
  56. { iterator to walk over all individual items in the aggregate }
  57. tadeenumerator = class(tobject)
  58. private
  59. fvalues: tfplist;
  60. fvaluespos: longint;
  61. function getcurrent: tai_abstracttypedconst;
  62. public
  63. constructor create(data: tai_aggregatetypedconst);
  64. function movenext: boolean;
  65. procedure reset;
  66. property current: tai_abstracttypedconst read getcurrent;
  67. end;
  68. protected
  69. fvalues: tfplist;
  70. fisstring: boolean;
  71. { converts the existing data to a single tai_string }
  72. procedure convert_to_string;
  73. procedure add_to_string(strtai: tai_string; othertai: tai);
  74. public
  75. constructor create(_adetyp: ttypedconstkind; _fdef: tdef);
  76. function getenumerator: tadeenumerator;
  77. procedure addvalue(val: tai_abstracttypedconst);
  78. function valuecount: longint;
  79. procedure insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  80. function replacevalueatpos(val: tai_abstracttypedconst; pos: longint): tai_abstracttypedconst;
  81. { change the type to a record, regardless of how the aggregate was created;
  82. the size of the original type and the record must match }
  83. procedure changetorecord(_def: trecorddef);
  84. procedure finish;
  85. destructor destroy; override;
  86. end;
  87. tasmlabofs = record
  88. lab: tasmlabel;
  89. ofs: asizeint;
  90. end;
  91. { flags for the finalisation of the typed const builder asmlist }
  92. ttcasmlistoption = (
  93. { the tasmsymbol is a tasmlabel }
  94. tcalo_is_lab,
  95. { start a new section (e.g., because we don't know the current section
  96. type) }
  97. tcalo_new_section,
  98. { this symbol is the start of a block of data that should be
  99. dead-stripable/smartlinkable; may imply starting a new section, but
  100. not necessarily (depends on what the platform requirements are) }
  101. tcalo_make_dead_strippable,
  102. { this symbol should never be removed by the linker }
  103. tcalo_no_dead_strip,
  104. { start of a vectorized but individually dead strippable list of elements,
  105. like the resource strings of a unit: they have to stay in this order,
  106. but individual elements can be removed }
  107. tcalo_vectorized_dead_strip_start,
  108. { item in the above list }
  109. tcalo_vectorized_dead_strip_item,
  110. { end of the above list }
  111. tcalo_vectorized_dead_strip_end,
  112. { symbol should be weakly defined }
  113. tcalo_weak,
  114. { symbol should be registered with the unit's public assembler symbols }
  115. tcalo_is_public_asm,
  116. { symbol should be declared with AT_DATA_FORCEINDIRECT }
  117. tcalo_data_force_indirect,
  118. { apply const_align() to the alignment, for user-defined data }
  119. tcalo_apply_constalign
  120. );
  121. ttcasmlistoptions = set of ttcasmlistoption;
  122. ttcdeadstripsectionsymboloption = (
  123. { define the symbol }
  124. tcdssso_define,
  125. { register the assembler symbol either with the public or extern assembler
  126. symbols of the unit }
  127. tcdssso_register_asmsym,
  128. { use the indirect symbol }
  129. tcdssso_use_indirect
  130. );
  131. ttcdeadstripsectionsymboloptions = set of ttcdeadstripsectionsymboloption;
  132. { information about aggregates we are parsing }
  133. taggregateinformation = class
  134. private
  135. fnextfieldname: TIDString;
  136. function getcuroffset: asizeint;
  137. procedure setnextfieldname(AValue: TIDString);
  138. protected
  139. { type of the aggregate }
  140. fdef: tdef;
  141. { type of the aggregate }
  142. ftyp: ttypedconstkind;
  143. { symtable entry of the previously emitted field in case of a
  144. record/object (nil if none emitted yet), used to insert alignment bytes
  145. if necessary for variant records and objects }
  146. fcurfield,
  147. { field corresponding to the data that will be emitted next in case of a
  148. record/object (nil if not set), used to handle variant records and
  149. objects }
  150. fnextfield: tfieldvarsym;
  151. { similar as the fcurfield/fnextfield above, but instead of fieldvarsyms
  152. these are indices in the symlist of a recorddef that correspond to
  153. fieldvarsyms. These are used only for non-variant records, simply
  154. traversing the fields in order. We could use the above method here as
  155. well, but to find the next field we'd always have to use
  156. symlist.indexof(fcurfield), which would be quite slow. These have -1 as
  157. value if they're not set }
  158. fcurindex,
  159. fnextindex: longint;
  160. { anonymous record that is being built as we add constant data }
  161. fanonrecord: boolean;
  162. property curindex: longint read fcurindex write fcurindex;
  163. property nextindex: longint read fnextindex write fnextindex;
  164. public
  165. constructor create(_def: tdef; _typ: ttypedconstkind); virtual;
  166. { calculated padding bytes for alignment if needed, and add the def of the
  167. next field in case we are constructing an anonymous record }
  168. function prepare_next_field(nextfielddef: tdef): asizeint; virtual;
  169. property def: tdef read fdef;
  170. property typ: ttypedconstkind read ftyp;
  171. property curfield: tfieldvarsym read fcurfield write fcurfield;
  172. property nextfield: tfieldvarsym read fnextfield write fnextfield;
  173. property nextfieldname: TIDString write setnextfieldname;
  174. property curoffset: asizeint read getcuroffset;
  175. property anonrecord: boolean read fanonrecord write fanonrecord;
  176. end;
  177. taggregateinformationclass = class of taggregateinformation;
  178. { information about a placeholder element that has been added, and which has
  179. to be replaced later with a real data element }
  180. ttypedconstplaceholder = class abstract
  181. def: tdef;
  182. constructor create(d: tdef);
  183. { same usage as ttai_typedconstbuilder.emit_tai }
  184. procedure replace(ai: tai; d: tdef); virtual; abstract;
  185. end;
  186. { Warning: never directly create a ttai_typedconstbuilder instance,
  187. instead create a cai_typedconstbuilder (this class can be overridden) }
  188. ttai_typedconstbuilder = class abstract
  189. { class type to use when creating new aggregate information instances }
  190. protected class var
  191. caggregateinformation: taggregateinformationclass;
  192. private
  193. function getcurragginfo: taggregateinformation;
  194. procedure set_next_field(AValue: tfieldvarsym);
  195. procedure set_next_field_name(AValue: TIDString);
  196. protected
  197. { temporary list in which all data is collected }
  198. fasmlist: tasmlist;
  199. { options for the final asmlist }
  200. foptions: ttcasmlistoptions;
  201. { while queueing elements of a compound expression, this is the current
  202. offset in the top-level array/record }
  203. fqueue_offset: asizeint;
  204. fqueued_def: tdef;
  205. { array of caggregateinformation instances }
  206. faggregateinformation: tfpobjectlist;
  207. { Support for generating data that is only referenced from the typed
  208. constant data that we are currently generated. Such data can all be put
  209. in the same dead-strippable unit, as it's either all included or none of
  210. it is included. This data can be spread over multiple kinds of sections
  211. though (e.g. rodata and rodata_no_rel), so per section keep track whether
  212. we already started a dead-strippable unit and if so, what the section
  213. name was (so that on platforms that perform the dead stripping based on
  214. sections, we put all data for one typed constant into a single section
  215. with the same name) }
  216. protected type
  217. tinternal_data_section_info = record
  218. secname: TSymStr;
  219. sectype: TAsmSectiontype;
  220. end;
  221. protected var
  222. { all internally generated data must be stored in the same list, as it must
  223. be consecutive (if it's spread over multiple lists, we don't know in
  224. which order they'll be concatenated) -> keep track of this list }
  225. finternal_data_asmlist: tasmlist;
  226. { kind of the last section we started in the finternal_data_asmlist, to
  227. avoid creating unnecessary section statements }
  228. finternal_data_current_section: TAsmSectiontype;
  229. { info about in which kinds of sections we have already emitted internal
  230. data, and what their names were }
  231. finternal_data_section_info: array of tinternal_data_section_info;
  232. { ensure that finalize_asmlist is called only once }
  233. fasmlist_finalized: boolean;
  234. { ensure that if it's vectorized dead strippable data, we called
  235. finalize_vectorized_dead_strip_asmlist instead of finalize_asmlist }
  236. fvectorized_finalize_called: boolean;
  237. { returns whether def must be handled as an aggregate on the current
  238. platform }
  239. function aggregate_kind(def: tdef): ttypedconstkind; virtual;
  240. { finalize the asmlist: add the necessary symbols etc }
  241. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); virtual;
  242. procedure finalize_asmlist_add_indirect_sym(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); virtual;
  243. { functionality of the above for vectorized dead strippable sections }
  244. procedure finalize_vectorized_dead_strip_asmlist(def: tdef; const basename, itemname: TSymStr; st: tsymtable; alignment: shortint; options: ttcasmlistoptions); virtual;
  245. { called by the public emit_tai() routines to actually add the typed
  246. constant data; the public ones also take care of adding extra padding
  247. bytes etc (by calling this one) }
  248. procedure do_emit_tai(p: tai; def: tdef); virtual;
  249. { calls prepare_next_field() and adds the padding bytes in the current
  250. location }
  251. procedure pad_next_field(nextfielddef: tdef);
  252. { returns the index in finternal_data_section_info of the info for the
  253. section of type typ. Returns -1 if there is no such info yet }
  254. function get_internal_data_section_index(typ: TAsmSectiontype): longint;
  255. { get a start label for an internal data section (at the start of a
  256. potentially dead-strippable part) }
  257. function get_internal_data_section_start_label: tasmlabel; virtual;
  258. { get a label in the middle of an internal data section (no dead
  259. stripping) }
  260. function get_internal_data_section_internal_label: tasmlabel; virtual;
  261. { easy access to the top level aggregate information instance }
  262. property curagginfo: taggregateinformation read getcurragginfo;
  263. public
  264. constructor create(const options: ttcasmlistoptions); virtual;
  265. destructor destroy; override;
  266. public
  267. { returns a builder for generating data that is only referrenced by the
  268. typed constant date we are currently generating (e.g. string data for a
  269. pchar constant). Also returns the label that will be placed at the start
  270. of that data. list is the tasmlist to which the data will be added.
  271. secname can be empty to use a default }
  272. procedure start_internal_data_builder(list: tasmlist; sectype: TAsmSectiontype; const secname: TSymStr; out tcb: ttai_typedconstbuilder; out l: tasmlabel);
  273. { finish a previously started internal data builder, including
  274. concatenating all generated data to the provided list and freeing the
  275. builder }
  276. procedure finish_internal_data_builder(var tcb: ttai_typedconstbuilder; l: tasmlabel; def: tdef; alignment: longint);
  277. { add a simple constant data element (p) to the typed constant.
  278. def is the type of the added value }
  279. procedure emit_tai(p: tai; def: tdef); virtual;
  280. { same as above, for a special case: when the def is a procvardef and we
  281. want to use it explicitly as a procdef (i.e., not as a record with a
  282. code and data pointer in case of a complex procvardef) }
  283. procedure emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef); virtual;
  284. protected
  285. procedure maybe_emit_tail_padding(def: tdef); virtual;
  286. function emit_string_const_common(stringtype: tstringtype; len: asizeint; encoding: tstringencoding; var startlab: tasmlabel):tasmlabofs;
  287. function get_dynstring_def_for_type(stringtype: tstringtype; winlikewidestring: boolean): tstringdef;
  288. procedure begin_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  289. procedure end_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  290. { when building an anonymous record, we cannot immediately insert the
  291. alignment before it in case it's nested, since we only know the required
  292. alignment once all fields have been inserted -> mark the location before
  293. the anonymous record, and insert the alignment once it's finished }
  294. procedure mark_anon_aggregate_alignment; virtual; abstract;
  295. procedure insert_marked_aggregate_alignment(def: tdef); virtual; abstract;
  296. class function get_vectorized_dead_strip_section_symbol(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions; start: boolean): tasmsymbol; virtual;
  297. public
  298. class function get_vectorized_dead_strip_custom_section_name(const basename: TSymStr; st: tsymtable; out secname: TSymStr): boolean; virtual;
  299. { get the start/end symbol for a dead stripable vectorized section, such
  300. as the resourcestring data of a unit }
  301. class function get_vectorized_dead_strip_section_symbol_start(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol; virtual;
  302. class function get_vectorized_dead_strip_section_symbol_end(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol; virtual;
  303. class function get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): TSymStr;
  304. class function get_dynstring_rec(typ: tstringtype; winlike: boolean; len: asizeint): trecorddef;
  305. { the datalist parameter specifies where the data for the string constant
  306. will be emitted (via an internal data builder) }
  307. function emit_ansistring_const(datalist: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding): tasmlabofs;
  308. function emit_unicodestring_const(datalist: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  309. { emits a tasmlabofs as returned by emit_*string_const }
  310. procedure emit_string_offset(const ll: tasmlabofs; const strlength: longint; const st: tstringtype; const winlikewidestring: boolean; const charptrdef: tdef);virtual;
  311. { emit a shortstring constant, and return its def }
  312. function emit_shortstring_const(const str: shortstring): tdef;
  313. { emit a pchar string constant (the characters, not a pointer to them), and return its def }
  314. function emit_pchar_const(str: pchar; len: pint; copypchar: boolean): tdef;
  315. { emit a guid constant }
  316. procedure emit_guid_const(const guid: tguid);
  317. { emit a procdef constant }
  318. procedure emit_procdef_const(pd: tprocdef);
  319. { emit an ordinal constant }
  320. procedure emit_ord_const(value: int64; def: tdef);
  321. { begin a potential aggregate type. Must be called for any type
  322. that consists of multiple tai constant data entries, or that
  323. represents an aggregate at the Pascal level (a record, a non-dynamic
  324. array, ... }
  325. procedure maybe_begin_aggregate(def: tdef);
  326. { end a potential aggregate type. Must be paired with every
  327. maybe_begin_aggregate }
  328. procedure maybe_end_aggregate(def: tdef);
  329. { similar as above, but in case
  330. a) it's definitely a record
  331. b) the def of the record should be automatically constructed based on
  332. the types of the emitted fields
  333. packrecords: same as "pacrecords x"
  334. recordalign: specify the (minimum) alignment of the start of the record
  335. (no equivalent in source code), used as an alternative for explicit
  336. align statements. Use "1" if it should be calculated based on the
  337. fields
  338. recordalignmin: same as "codealign recordmin=x"
  339. maxcrecordalign: specify maximum C record alignment (no equivalent in
  340. source code)
  341. }
  342. function begin_anonymous_record(const optionalname: string; packrecords, recordalign, recordalignmin, maxcrecordalign: shortint): trecorddef; virtual;
  343. function end_anonymous_record: trecorddef; virtual;
  344. { add a placeholder element at the current position that later can be
  345. filled in with the actual data (via ttypedconstplaceholder.replace)
  346. useful in case you have table preceded by the number of elements, and
  347. you count the elements while building the table }
  348. function emit_placeholder(def: tdef): ttypedconstplaceholder; virtual; abstract;
  349. protected
  350. { common code to check whether a placeholder can be added at the current
  351. position }
  352. procedure check_add_placeholder(def: tdef);
  353. public
  354. { The next group of routines are for constructing complex expressions.
  355. While parsing a typed constant these operators are encountered from
  356. outer to inner, so that is also the order in which they should be
  357. added to the queue. Only one queue can be active at a time. }
  358. { Init the queue. Gives an internalerror if a queue was already active }
  359. procedure queue_init(todef: tdef); virtual;
  360. { queue an array/string indexing operation (performs all range checking,
  361. so it doesn't have to be duplicated in all descendents). }
  362. procedure queue_vecn(def: tdef; const index: tconstexprint); virtual;
  363. { queue a subscripting operation }
  364. procedure queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym); virtual;
  365. { queue indexing a record recursively via several field names. The fields
  366. are specified in the inner to outer order (i.e., def.field1.field2) }
  367. function queue_subscriptn_multiple_by_name(def: tabstractrecorddef; const fields: array of TIDString): tdef;
  368. { queue a type conversion operation }
  369. procedure queue_typeconvn(fromdef, todef: tdef); virtual;
  370. { finalise the queue (so a new one can be created) and flush the
  371. previously queued operations, applying them in reverse order on a...}
  372. { ... procdef }
  373. procedure queue_emit_proc(pd: tprocdef); virtual;
  374. { ... staticvarsym }
  375. procedure queue_emit_staticvar(vs: tstaticvarsym); virtual;
  376. { ... labelsym }
  377. procedure queue_emit_label(l: tlabelsym); virtual;
  378. { ... constsym }
  379. procedure queue_emit_const(cs: tconstsym); virtual;
  380. { ... asmsym/asmlabel }
  381. procedure queue_emit_asmsym(sym: tasmsymbol; def: tdef); virtual;
  382. { ... an ordinal constant }
  383. procedure queue_emit_ordconst(value: int64; def: tdef); virtual;
  384. protected
  385. { returns whether queue_init has been called without a corresponding
  386. queue_emit_* to finish it }
  387. function queue_is_active: boolean;
  388. public
  389. { finalize the internal asmlist (if necessary) and return it.
  390. This asmlist will be freed when the builder is destroyed, so add its
  391. contents to another list first. This property should only be accessed
  392. once all data has been added. }
  393. function get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint): tasmlist;
  394. function get_final_asmlist_vectorized_dead_strip(def: tdef; const basename, itemname: TSymStr; st: TSymtable; alignment: longint): tasmlist;
  395. { returns the offset of the string data relative to ansi/unicode/widestring
  396. constant labels. On most platforms, this is 0 (with the header at a
  397. negative offset), but on some platforms such negative offsets are not
  398. supported this is equal to the header size }
  399. class function get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint; virtual;
  400. { set the fieldvarsym whose data we will emit next; needed
  401. in case of variant records, so we know which part of the variant gets
  402. initialised. Also in case of objects, because the fieldvarsyms are spread
  403. over the symtables of the entire inheritance tree }
  404. property next_field: tfieldvarsym write set_next_field;
  405. { set the name of the next field that will be emitted for an anonymous
  406. record (also if that field is a nested anonymous record) }
  407. property next_field_name: TIDString write set_next_field_name;
  408. protected
  409. { this one always return the actual offset, called by the above (and
  410. overridden versions) }
  411. class function get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  412. end;
  413. ttai_typedconstbuilderclass = class of ttai_typedconstbuilder;
  414. tlowlevelaggregateinformation = class(taggregateinformation)
  415. protected
  416. fanonrecmarker: tai;
  417. public
  418. property anonrecmarker: tai read fanonrecmarker write fanonrecmarker;
  419. end;
  420. tlowleveltypedconstplaceholder = class(ttypedconstplaceholder)
  421. list: tasmlist;
  422. insertpos: tai;
  423. constructor create(l: tasmlist; pos: tai; d: tdef);
  424. procedure replace(ai: tai; d: tdef); override;
  425. end;
  426. ttai_lowleveltypedconstbuilder = class(ttai_typedconstbuilder)
  427. protected
  428. procedure mark_anon_aggregate_alignment; override;
  429. procedure insert_marked_aggregate_alignment(def: tdef); override;
  430. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); override;
  431. public
  432. { set the default value for caggregateinformation (= tlowlevelaggregateinformation) }
  433. class constructor classcreate;
  434. function emit_placeholder(def: tdef): ttypedconstplaceholder; override;
  435. end;
  436. var
  437. ctai_typedconstbuilder: ttai_typedconstbuilderclass;
  438. implementation
  439. uses
  440. cutils,
  441. verbose,globals,systems,widestr,
  442. fmodule,
  443. symtable,defutil;
  444. {****************************************************************************
  445. taggregateinformation
  446. ****************************************************************************}
  447. function taggregateinformation.getcuroffset: asizeint;
  448. var
  449. field: tfieldvarsym;
  450. begin
  451. if assigned(curfield) then
  452. result:=curfield.fieldoffset+curfield.vardef.size
  453. else if curindex<>-1 then
  454. begin
  455. field:=tfieldvarsym(tabstractrecorddef(def).symtable.symlist[curindex]);
  456. result:=field.fieldoffset+field.vardef.size
  457. end
  458. else
  459. result:=0
  460. end;
  461. procedure taggregateinformation.setnextfieldname(AValue: TIDString);
  462. begin
  463. if (fnextfieldname<>'') or
  464. not anonrecord then
  465. internalerror(2015071503);
  466. fnextfieldname:=AValue;
  467. end;
  468. constructor taggregateinformation.create(_def: tdef; _typ: ttypedconstkind);
  469. begin
  470. fdef:=_def;
  471. ftyp:=_typ;
  472. fcurindex:=-1;
  473. fnextindex:=-1;
  474. end;
  475. function taggregateinformation.prepare_next_field(nextfielddef: tdef): asizeint;
  476. var
  477. sym: tsym;
  478. currentoffset,nextoffset: asizeint;
  479. i: longint;
  480. begin
  481. { get the next field and its offset, and make that next field the current
  482. one }
  483. if assigned(nextfield) then
  484. begin
  485. nextoffset:=nextfield.fieldoffset;
  486. currentoffset:=curoffset;
  487. curfield:=nextfield;
  488. end
  489. else
  490. begin
  491. { must set nextfield for unions and objects, as we cannot
  492. automatically detect the "next" field in that case }
  493. if ((def.typ=recorddef) and
  494. trecorddef(def).isunion) or
  495. is_object(def) then
  496. internalerror(2014091202);
  497. { if we are constructing this record as data gets emitted, add a field
  498. for this data }
  499. if anonrecord then
  500. begin
  501. trecorddef(def).add_field_by_def(fnextfieldname,nextfielddef);
  502. fnextfieldname:='';
  503. end
  504. else if fnextfieldname<>'' then
  505. internalerror(2015071501);
  506. currentoffset:=curoffset;
  507. { find next field }
  508. i:=curindex;
  509. repeat
  510. inc(i);
  511. sym:=tsym(tabstractrecorddef(def).symtable.symlist[i]);
  512. until (sym.typ=fieldvarsym) and
  513. not(sp_static in sym.symoptions);
  514. curfield:=tfieldvarsym(sym);
  515. nextoffset:=curfield.fieldoffset;
  516. curindex:=i;
  517. end;
  518. { need padding? }
  519. result:=nextoffset-currentoffset;
  520. end;
  521. {****************************************************************************
  522. ttypedconstplaceholder
  523. ****************************************************************************}
  524. constructor ttypedconstplaceholder.create(d: tdef);
  525. begin
  526. def:=d;
  527. end;
  528. {****************************************************************************
  529. tai_abstracttypedconst
  530. ****************************************************************************}
  531. procedure tai_abstracttypedconst.setdef(def: tdef);
  532. begin
  533. { should not be changed, rewrite the calling code if this happens }
  534. if assigned(fdef) then
  535. Internalerror(2014080203);
  536. fdef:=def;
  537. end;
  538. constructor tai_abstracttypedconst.create(_adetyp: ttypedconstkind; _def: tdef);
  539. begin
  540. inherited create;
  541. typ:=ait_typedconst;
  542. fadetyp:=_adetyp;
  543. fdef:=_def;
  544. end;
  545. {****************************************************************************
  546. tai_simpletypedconst
  547. ****************************************************************************}
  548. procedure tai_simpletypedconst.setval(AValue: tai);
  549. begin
  550. fval:=AValue;
  551. end;
  552. constructor tai_simpletypedconst.create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  553. begin
  554. inherited create(_adetyp,_def);
  555. fval:=_val;
  556. end;
  557. {****************************************************************************
  558. tai_aggregatetypedconst.tadeenumerator
  559. ****************************************************************************}
  560. constructor tai_aggregatetypedconst.tadeenumerator.create(data: tai_aggregatetypedconst);
  561. begin
  562. fvalues:=data.fvalues;
  563. fvaluespos:=-1;
  564. end;
  565. function tai_aggregatetypedconst.tadeenumerator.getcurrent: tai_abstracttypedconst;
  566. begin
  567. result:=tai_abstracttypedconst(fvalues[fvaluespos]);
  568. end;
  569. function tai_aggregatetypedconst.tadeenumerator.movenext: boolean;
  570. begin
  571. if fvaluespos<pred(fvalues.count) then
  572. begin
  573. inc(fvaluespos);
  574. result:=true
  575. end
  576. else
  577. result:=false;
  578. end;
  579. procedure tai_aggregatetypedconst.tadeenumerator.reset;
  580. begin
  581. fvaluespos:=0
  582. end;
  583. {****************************************************************************
  584. tai_aggregatetypedconst
  585. ****************************************************************************}
  586. procedure tai_aggregatetypedconst.convert_to_string;
  587. var
  588. ai: tai_abstracttypedconst;
  589. newstr: tai_string;
  590. begin
  591. newstr:=tai_string.Create('');
  592. for ai in self do
  593. begin
  594. if ai.adetyp<>tck_simple then
  595. internalerror(2014070103);
  596. add_to_string(newstr,tai_simpletypedconst(ai).val);
  597. ai.free;
  598. end;
  599. fvalues.count:=0;
  600. { the "nil" def will be replaced with an array def of the appropriate
  601. size once we're finished adding data, so we don't create intermediate
  602. arraydefs all the time }
  603. fvalues.add(tai_simpletypedconst.create(tck_simple,nil,newstr));
  604. end;
  605. procedure tai_aggregatetypedconst.add_to_string(strtai: tai_string; othertai: tai);
  606. begin
  607. case othertai.typ of
  608. ait_string:
  609. begin
  610. strtai.str:=reallocmem(strtai.str,strtai.len+tai_string(othertai).len+1);
  611. { also copy null terminator }
  612. move(tai_string(othertai).str[0],strtai.str[strtai.len],tai_string(othertai).len+1);
  613. { the null terminator is not part of the string data }
  614. strtai.len:=strtai.len+tai_string(othertai).len;
  615. end;
  616. ait_const:
  617. begin
  618. if tai_const(othertai).size<>1 then
  619. internalerror(2014070101);
  620. { it was already len+1 to hold the #0 -> realloc to len+2 }
  621. strtai.str:=reallocmem(strtai.str,strtai.len+2);
  622. strtai.str[strtai.len]:=ansichar(tai_const(othertai).value);
  623. strtai.str[strtai.len+1]:=#0;
  624. inc(strtai.len);
  625. end;
  626. else
  627. internalerror(2014070102);
  628. end;
  629. end;
  630. constructor tai_aggregatetypedconst.create(_adetyp: ttypedconstkind; _fdef: tdef);
  631. begin
  632. inherited;
  633. fisstring:=false;
  634. fvalues:=tfplist.create;
  635. end;
  636. function tai_aggregatetypedconst.getenumerator: tadeenumerator;
  637. begin
  638. result:=tadeenumerator.create(self);
  639. end;
  640. procedure tai_aggregatetypedconst.addvalue(val: tai_abstracttypedconst);
  641. begin
  642. { merge string constants and ordinal constants added in an array of
  643. char, to unify the length and the string data }
  644. if fisstring or
  645. ((val.adetyp=tck_simple) and
  646. (tai_simpletypedconst(val).val.typ=ait_string)) then
  647. begin
  648. if not fisstring and
  649. (fvalues.count>0) then
  650. convert_to_string;
  651. fisstring:=true;
  652. case fvalues.count of
  653. 0: fvalues.add(val);
  654. 1:
  655. begin
  656. add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
  657. val.free
  658. end
  659. else
  660. internalerror(2014070104);
  661. end;
  662. end
  663. else
  664. fvalues.add(val);
  665. end;
  666. function tai_aggregatetypedconst.valuecount: longint;
  667. begin
  668. result:=fvalues.count;
  669. end;
  670. procedure tai_aggregatetypedconst.insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  671. begin
  672. fvalues.insert(pos,val);
  673. end;
  674. function tai_aggregatetypedconst.replacevalueatpos(val: tai_abstracttypedconst; pos: longint): tai_abstracttypedconst;
  675. begin
  676. result:=tai_abstracttypedconst(fvalues[pos]);
  677. fvalues[pos]:=val;
  678. end;
  679. procedure tai_aggregatetypedconst.changetorecord(_def: trecorddef);
  680. begin
  681. { must be a record of the same size as the current data }
  682. if assigned(fdef) and
  683. (fdef.size<>_def.size) then
  684. internalerror(2015122402);
  685. fdef:=_def;
  686. fadetyp:=tck_record;
  687. end;
  688. procedure tai_aggregatetypedconst.finish;
  689. begin
  690. if fisstring then
  691. begin
  692. { set the def: an array of char with the same length as the string
  693. data }
  694. if fvalues.count<>1 then
  695. internalerror(2014070105);
  696. tai_simpletypedconst(fvalues[0]).fdef:=
  697. carraydef.getreusable(cansichartype,
  698. tai_string(tai_simpletypedconst(fvalues[0]).val).len);
  699. end;
  700. end;
  701. destructor tai_aggregatetypedconst.destroy;
  702. begin
  703. fvalues.free;
  704. inherited destroy;
  705. end;
  706. {*****************************************************************************
  707. ttai_typedconstbuilder
  708. *****************************************************************************}
  709. function ttai_typedconstbuilder.getcurragginfo: taggregateinformation;
  710. begin
  711. if assigned(faggregateinformation) and
  712. (faggregateinformation.count>0) then
  713. result:=taggregateinformation(faggregateinformation[faggregateinformation.count-1])
  714. else
  715. result:=nil;
  716. end;
  717. procedure ttai_typedconstbuilder.set_next_field(AValue: tfieldvarsym);
  718. var
  719. info: taggregateinformation;
  720. begin
  721. info:=curagginfo;
  722. if not assigned(info) then
  723. internalerror(2014091206);
  724. info.nextfield:=AValue;
  725. end;
  726. procedure ttai_typedconstbuilder.set_next_field_name(AValue: TIDString);
  727. var
  728. info: taggregateinformation;
  729. begin
  730. info:=curagginfo;
  731. if not assigned(info) then
  732. internalerror(2015071502);
  733. info.nextfieldname:='$'+AValue;
  734. end;
  735. procedure ttai_typedconstbuilder.pad_next_field(nextfielddef: tdef);
  736. var
  737. fillbytes: asizeint;
  738. begin
  739. fillbytes:=curagginfo.prepare_next_field(nextfielddef);
  740. while fillbytes>0 do
  741. begin
  742. do_emit_tai(tai_const.create_8bit(0),u8inttype);
  743. dec(fillbytes);
  744. end;
  745. end;
  746. function ttai_typedconstbuilder.get_internal_data_section_index(typ: TAsmSectiontype): longint;
  747. begin
  748. { avoid wrong warning by -Oodfa }
  749. result:=-1;
  750. for result:=low(finternal_data_section_info) to high(finternal_data_section_info) do
  751. if finternal_data_section_info[result].sectype=typ then
  752. exit;
  753. result:=-1;
  754. end;
  755. function ttai_typedconstbuilder.get_internal_data_section_start_label: tasmlabel;
  756. begin
  757. { on Darwin, dead code/data stripping happens based on non-temporary
  758. labels (any label that doesn't start with "L" -- it doesn't have
  759. to be global) }
  760. if target_info.system in systems_darwin then
  761. current_asmdata.getstaticdatalabel(result)
  762. else if create_smartlink_library then
  763. current_asmdata.getglobaldatalabel(result)
  764. else
  765. current_asmdata.getlocaldatalabel(result);
  766. end;
  767. function ttai_typedconstbuilder.get_internal_data_section_internal_label: tasmlabel;
  768. begin
  769. if create_smartlink_library then
  770. { all labels need to be global in case they're in another object }
  771. current_asmdata.getglobaldatalabel(result)
  772. else
  773. { no special requirement for the label -> just get a local one }
  774. current_asmdata.getlocaldatalabel(result);
  775. end;
  776. function ttai_typedconstbuilder.aggregate_kind(def: tdef): ttypedconstkind;
  777. begin
  778. if (def.typ in [recorddef,filedef,variantdef]) or
  779. is_object(def) or
  780. ((def.typ=procvardef) and
  781. not tprocvardef(def).is_addressonly and
  782. not is_block(def)) then
  783. result:=tck_record
  784. else if ((def.typ=arraydef) and
  785. not is_dynamic_array(def)) or
  786. ((def.typ=setdef) and
  787. not is_smallset(def)) or
  788. is_shortstring(def) then
  789. result:=tck_array
  790. else
  791. result:=tck_simple;
  792. end;
  793. procedure ttai_typedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  794. var
  795. prelist: tasmlist;
  796. begin
  797. if tcalo_apply_constalign in options then
  798. alignment:=const_align(alignment);
  799. { have we finished all aggregates? }
  800. if (getcurragginfo<>nil) and
  801. { in case of syntax errors, the aggregate may not have been finished }
  802. (ErrorCount=0) then
  803. internalerror(2015072301);
  804. { must call finalize_vectorized_dead_strip_asmlist() instead }
  805. if (([tcalo_vectorized_dead_strip_start,
  806. tcalo_vectorized_dead_strip_item,
  807. tcalo_vectorized_dead_strip_end]*options)<>[]) and
  808. not fvectorized_finalize_called then
  809. internalerror(2015110602);
  810. prelist:=tasmlist.create;
  811. { only now add items based on the symbolname, because it may be
  812. modified by the "section" specifier in case of a typed constant }
  813. { both in case the data should be dead strippable and never dead
  814. stripped, it should be in a separate section (so this property doesn't
  815. affect other data) }
  816. if ([tcalo_no_dead_strip,tcalo_make_dead_strippable]*options)<>[] then
  817. begin
  818. maybe_new_object_file(prelist);
  819. { we always need a new section here, since if we started a new
  820. object file then we have to say what the section is, and otherwise
  821. we need a new section because that's how the dead stripping works }
  822. new_section(prelist,section,secname,alignment);
  823. end
  824. else if tcalo_new_section in options then
  825. new_section(prelist,section,secname,alignment)
  826. else
  827. prelist.concat(cai_align.Create(alignment));
  828. { On Darwin, use .reference to ensure the data doesn't get dead stripped.
  829. On other platforms, the data must be in the .fpc section (which is
  830. kept via the linker script) }
  831. if tcalo_no_dead_strip in options then
  832. begin
  833. if (target_info.system in systems_darwin) then
  834. begin
  835. { Objective-C section declarations contain "no_dead_strip"
  836. attributes if none of their symbols need to be stripped -> don't
  837. add extra ".reference" statement for their symbols (gcc/clang
  838. don't either) }
  839. if not(section in [low(TObjCAsmSectionType)..high(TObjCAsmSectionType)]) then
  840. prelist.concat(tai_directive.Create(asd_reference,sym.name))
  841. end
  842. else if section<>sec_fpc then
  843. internalerror(2015101402);
  844. end;
  845. if not(tcalo_is_lab in options) then
  846. if sym.bind=AB_LOCAL then
  847. prelist.concat(tai_symbol.Create(sym,0))
  848. else
  849. prelist.concat(tai_symbol.Create_Global(sym,0))
  850. else
  851. prelist.concat(tai_label.Create(tasmlabel(sym)));
  852. if tcalo_weak in options then
  853. prelist.concat(tai_directive.Create(asd_weak_definition,sym.name));
  854. { insert the symbol information before the data }
  855. fasmlist.insertlist(prelist);
  856. { end of the symbol }
  857. fasmlist.concat(tai_symbol_end.Createname(sym.name));
  858. { free the temporary list }
  859. prelist.free;
  860. end;
  861. procedure ttai_typedconstbuilder.finalize_asmlist_add_indirect_sym(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  862. var
  863. ptrdef : tdef;
  864. symind : tasmsymbol;
  865. indtcb : ttai_typedconstbuilder;
  866. indsecname : tsymstr;
  867. begin
  868. if (tcalo_data_force_indirect in options) and
  869. (sym.bind in [AB_GLOBAL,AB_COMMON]) and
  870. (sym.typ=AT_DATA) then
  871. begin
  872. ptrdef:=cpointerdef.getreusable(def);
  873. symind:=current_asmdata.DefineAsmSymbol(sym.name,AB_INDIRECT,AT_DATA,ptrdef);
  874. { reuse the section if possible }
  875. if section=sec_rodata then
  876. indsecname:=secname
  877. else
  878. indsecname:=lower(symind.name);
  879. indtcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  880. indtcb.emit_tai(tai_const.create_sym_offset(sym,0),ptrdef);
  881. current_asmdata.asmlists[al_indirectglobals].concatlist(indtcb.get_final_asmlist(
  882. symind,
  883. ptrdef,
  884. sec_rodata,
  885. indsecname,
  886. ptrdef.alignment));
  887. indtcb.free;
  888. if not (target_info.system in systems_indirect_var_imports) then
  889. current_module.add_public_asmsym(symind.name,AB_INDIRECT,AT_DATA);
  890. end;
  891. end;
  892. procedure ttai_typedconstbuilder.finalize_vectorized_dead_strip_asmlist(def: tdef; const basename, itemname: TSymStr; st: tsymtable; alignment: shortint; options: ttcasmlistoptions);
  893. var
  894. sym: tasmsymbol;
  895. secname: TSymStr;
  896. sectype: TAsmSectiontype;
  897. asmtype : TAsmsymtype;
  898. customsecname: boolean;
  899. dsopts : ttcdeadstripsectionsymboloptions;
  900. begin
  901. fvectorized_finalize_called:=true;
  902. sym:=nil;
  903. customsecname:=get_vectorized_dead_strip_custom_section_name(basename,st,secname);
  904. if customsecname then
  905. sectype:=sec_user
  906. else
  907. sectype:=sec_data;
  908. dsopts:=[tcdssso_define];
  909. if tcalo_is_public_asm in options then
  910. include(dsopts,tcdssso_register_asmsym);
  911. if tcalo_data_force_indirect in options then
  912. include(dsopts,tcdssso_use_indirect);
  913. if tcalo_vectorized_dead_strip_start in options then
  914. begin
  915. { the start and end names are predefined }
  916. if itemname<>'' then
  917. internalerror(2015110801);
  918. sym:=get_vectorized_dead_strip_section_symbol_start(basename,st,dsopts);
  919. if not customsecname then
  920. secname:=make_mangledname(basename,st,'1_START');
  921. end
  922. else if tcalo_vectorized_dead_strip_end in options then
  923. begin
  924. { the start and end names are predefined }
  925. if itemname<>'' then
  926. internalerror(2015110802);
  927. sym:=get_vectorized_dead_strip_section_symbol_end(basename,st,dsopts);
  928. if not customsecname then
  929. secname:=make_mangledname(basename,st,'3_END');
  930. end
  931. else if tcalo_vectorized_dead_strip_item in options then
  932. begin
  933. if tcalo_data_force_indirect in options then
  934. asmtype:=AT_DATA_FORCEINDIRECT
  935. else
  936. asmtype:=AT_DATA;
  937. sym:=current_asmdata.DefineAsmSymbol(make_mangledname(basename,st,itemname),AB_GLOBAL,asmtype,def);
  938. if tcalo_is_public_asm in options then
  939. current_module.add_public_asmsym(sym);
  940. if not customsecname then
  941. secname:=make_mangledname(basename,st,'2_'+itemname);
  942. exclude(options,tcalo_vectorized_dead_strip_item);
  943. end;
  944. finalize_asmlist(sym,def,sectype,secname,alignment,options);
  945. end;
  946. procedure ttai_typedconstbuilder.do_emit_tai(p: tai; def: tdef);
  947. begin
  948. { by default we don't care about the type }
  949. fasmlist.concat(p);
  950. end;
  951. function ttai_typedconstbuilder.get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint): tasmlist;
  952. begin
  953. if not fasmlist_finalized then
  954. begin
  955. finalize_asmlist(sym,def,section,secname,alignment,foptions);
  956. finalize_asmlist_add_indirect_sym(sym,def,section,secname,alignment,foptions);
  957. fasmlist_finalized:=true;
  958. end;
  959. result:=fasmlist;
  960. end;
  961. function ttai_typedconstbuilder.get_final_asmlist_vectorized_dead_strip(def: tdef; const basename, itemname: TSymStr; st: TSymtable; alignment: longint): tasmlist;
  962. begin
  963. if not fasmlist_finalized then
  964. begin
  965. finalize_vectorized_dead_strip_asmlist(def,basename,itemname,st,alignment,foptions);
  966. fasmlist_finalized:=true;
  967. end;
  968. result:=fasmlist;
  969. end;
  970. class function ttai_typedconstbuilder.get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint;
  971. begin
  972. { darwin's linker does not support negative offsets }
  973. if not(target_info.system in systems_darwin) then
  974. result:=0
  975. else
  976. result:=get_string_header_size(typ,winlikewidestring);
  977. end;
  978. class function ttai_typedconstbuilder.get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  979. var
  980. ansistring_header_size: pint;
  981. unicodestring_header_size: pint;
  982. begin
  983. ansistring_header_size:=
  984. { encoding }
  985. 2 +
  986. { elesize }
  987. 2 +
  988. {$ifdef cpu64bitaddr}
  989. { alignment }
  990. 4 +
  991. {$endif cpu64bitaddr}
  992. { reference count }
  993. sizesinttype.size +
  994. { length }
  995. sizesinttype.size;
  996. unicodestring_header_size:=ansistring_header_size;
  997. case typ of
  998. st_ansistring:
  999. result:=ansistring_header_size;
  1000. st_unicodestring:
  1001. result:=unicodestring_header_size;
  1002. st_widestring:
  1003. if winlikewidestring then
  1004. result:=0
  1005. else
  1006. result:=unicodestring_header_size;
  1007. else
  1008. result:=0;
  1009. end;
  1010. end;
  1011. constructor ttai_typedconstbuilder.create(const options: ttcasmlistoptions);
  1012. begin
  1013. inherited create;
  1014. fasmlist:=tasmlist.create;
  1015. foptions:=options;
  1016. { queue is empty }
  1017. fqueue_offset:=low(fqueue_offset);
  1018. finternal_data_current_section:=sec_none;
  1019. end;
  1020. destructor ttai_typedconstbuilder.destroy;
  1021. begin
  1022. { the queue should have been flushed if it was used }
  1023. if fqueue_offset<>low(fqueue_offset) then
  1024. internalerror(2014062901);
  1025. faggregateinformation.free;
  1026. fasmlist.free;
  1027. inherited destroy;
  1028. end;
  1029. procedure ttai_typedconstbuilder.start_internal_data_builder(list: tasmlist; sectype: TAsmSectiontype; const secname: TSymStr; out tcb: ttai_typedconstbuilder; out l: tasmlabel);
  1030. var
  1031. options: ttcasmlistoptions;
  1032. foundsec: longint;
  1033. begin
  1034. { you can't start multiple concurrent internal data builders for the
  1035. same tcb, finish the first before starting another }
  1036. if finternal_data_current_section<>sec_none then
  1037. internalerror(2016082801);
  1038. { we don't know what was previously added to this list, so always add
  1039. a section header. We'll use the same section name in case multiple
  1040. items are added to the same kind of section (rodata, rodata_no_rel,
  1041. ...), so that everything will still end up in the same section even if
  1042. there are multiple section headers }
  1043. options:=[tcalo_is_lab,tcalo_new_section];
  1044. finternal_data_current_section:=sectype;
  1045. l:=nil;
  1046. { did we already create a section of this type for the internal data of
  1047. this builder? }
  1048. foundsec:=get_internal_data_section_index(sectype);
  1049. if foundsec=-1 then
  1050. begin
  1051. { we only need to start a dead-strippable section of data at the
  1052. start of the first subsection of this kind for this block.
  1053. exception: if dead stripping happens based on objects/libraries,
  1054. then we only have to create a new object file for the first
  1055. internal data section of any kind (all the rest will simply be put
  1056. in the same object file) }
  1057. if create_smartlink then
  1058. begin
  1059. if not create_smartlink_library or
  1060. (length(finternal_data_section_info)=0) then
  1061. include(options,tcalo_make_dead_strippable);
  1062. { on Darwin, dead code/data stripping happens based on non-
  1063. temporary labels (any label that doesn't start with "L" -- it
  1064. doesn't have to be global) -> add a non-temporary lobel at the
  1065. start of every kind of subsection created in this builder }
  1066. if target_info.system in systems_darwin then
  1067. l:=get_internal_data_section_start_label;
  1068. end;
  1069. foundsec:=length(finternal_data_section_info);
  1070. setlength(finternal_data_section_info,foundsec+1);
  1071. finternal_data_section_info[foundsec].sectype:=sectype;
  1072. end;
  1073. if not assigned(finternal_data_asmlist) and
  1074. (cs_create_smart in current_settings.moduleswitches) then
  1075. begin
  1076. l:=get_internal_data_section_start_label;
  1077. { the internal data list should only be assigned by this routine,
  1078. the first time that an internal data block is started }
  1079. if not assigned(list) or
  1080. assigned(finternal_data_asmlist) then
  1081. internalerror(2015032101);
  1082. finternal_data_asmlist:=list;
  1083. end
  1084. { all internal data for this tcb must go to the same list (otherwise all
  1085. data we want to add to the dead-strippable block is not guaranteed to
  1086. be sequential and e.g. in the same object file in case of library-based
  1087. dead stripping) }
  1088. else if (assigned(finternal_data_asmlist) and
  1089. (list<>finternal_data_asmlist)) or
  1090. not assigned(list) then
  1091. internalerror(2015032101);
  1092. finternal_data_asmlist:=list;
  1093. if not assigned(l) then
  1094. l:=get_internal_data_section_internal_label;
  1095. { first section of this kind -> set name }
  1096. if finternal_data_section_info[foundsec].secname='' then
  1097. if secname='' then
  1098. finternal_data_section_info[foundsec].secname:=l.Name
  1099. else
  1100. finternal_data_section_info[foundsec].secname:=secname
  1101. { if the name is specified multiple times, it must match }
  1102. else if (secname<>'') and
  1103. (finternal_data_section_info[foundsec].secname<>secname) then
  1104. internalerror(2015032401);
  1105. tcb:=ttai_typedconstbuilderclass(classtype).create(options);
  1106. end;
  1107. procedure ttai_typedconstbuilder.finish_internal_data_builder(var tcb: ttai_typedconstbuilder; l: tasmlabel; def: tdef; alignment: longint);
  1108. begin
  1109. finternal_data_asmlist.concatList(tcb.get_final_asmlist(l,def,
  1110. finternal_data_current_section,
  1111. finternal_data_section_info[get_internal_data_section_index(finternal_data_current_section)].secname,
  1112. alignment));
  1113. tcb.free;
  1114. tcb:=nil;
  1115. finternal_data_current_section:=sec_none;
  1116. end;
  1117. procedure ttai_typedconstbuilder.emit_tai(p: tai; def: tdef);
  1118. var
  1119. kind: ttypedconstkind;
  1120. info: taggregateinformation;
  1121. begin
  1122. { these elements can be aggregates themselves, e.g. a shortstring can
  1123. be emitted as a series of bytes and char arrays }
  1124. kind:=aggregate_kind(def);
  1125. info:=curagginfo;
  1126. if (kind<>tck_simple) and
  1127. (not assigned(info) or
  1128. (info.typ<>kind)) then
  1129. internalerror(2014091001);
  1130. { if we're emitting a record, handle the padding bytes, and in case of
  1131. an anonymous record also add the next field }
  1132. if assigned(info) then
  1133. begin
  1134. { queue_init already adds padding }
  1135. if not queue_is_active and
  1136. (is_record(info.def) or
  1137. is_object(info.def)) and
  1138. { may add support for these later }
  1139. not is_packed_record_or_object(info.def) then
  1140. pad_next_field(def);
  1141. end;
  1142. { emit the data }
  1143. do_emit_tai(p,def);
  1144. end;
  1145. procedure ttai_typedconstbuilder.emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef);
  1146. begin
  1147. { nothing special by default, since we don't care about the type }
  1148. emit_tai(p,pvdef);
  1149. end;
  1150. procedure ttai_typedconstbuilder.maybe_emit_tail_padding(def: tdef);
  1151. var
  1152. info: taggregateinformation;
  1153. fillbytes: asizeint;
  1154. begin
  1155. info:=curagginfo;
  1156. if not assigned(info) then
  1157. internalerror(2014091002);
  1158. if def<>info.def then
  1159. internalerror(2014091205);
  1160. if (is_record(def) or
  1161. is_object(def)) and
  1162. not is_packed_record_or_object(def) then
  1163. begin
  1164. fillbytes:=def.size-info.curoffset;
  1165. while fillbytes>0 do
  1166. begin
  1167. do_emit_tai(Tai_const.Create_8bit(0),u8inttype);
  1168. dec(fillbytes)
  1169. end;
  1170. end;
  1171. end;
  1172. function ttai_typedconstbuilder.emit_string_const_common(stringtype: tstringtype; len: asizeint; encoding: tstringencoding; var startlab: tasmlabel): tasmlabofs;
  1173. var
  1174. string_symofs: asizeint;
  1175. charptrdef: tdef;
  1176. elesize: word;
  1177. begin
  1178. result.lab:=startlab;
  1179. result.ofs:=0;
  1180. { pack the data, so that we don't add unnecessary null bytes after the
  1181. constant string }
  1182. begin_anonymous_record('$'+get_dynstring_rec_name(stringtype,false,len),1,sizeof(TConstPtrUInt),1,1);
  1183. string_symofs:=get_string_symofs(stringtype,false);
  1184. { encoding }
  1185. emit_tai(tai_const.create_16bit(encoding),u16inttype);
  1186. inc(result.ofs,2);
  1187. { element size }
  1188. case stringtype of
  1189. st_ansistring:
  1190. begin
  1191. elesize:=1;
  1192. charptrdef:=charpointertype;
  1193. end;
  1194. st_unicodestring:
  1195. begin
  1196. elesize:=2;
  1197. charptrdef:=widecharpointertype;
  1198. end
  1199. else
  1200. internalerror(2014080401);
  1201. end;
  1202. emit_tai(tai_const.create_16bit(elesize),u16inttype);
  1203. inc(result.ofs,2);
  1204. {$ifdef cpu64bitaddr}
  1205. { dummy for alignment }
  1206. emit_tai(tai_const.create_32bit(0),u32inttype);
  1207. inc(result.ofs,4);
  1208. {$endif cpu64bitaddr}
  1209. emit_tai(tai_const.create_sizeint(-1),sizesinttype);
  1210. inc(result.ofs,sizesinttype.size);
  1211. emit_tai(tai_const.create_sizeint(len),sizesinttype);
  1212. inc(result.ofs,sizesinttype.size);
  1213. if string_symofs=0 then
  1214. begin
  1215. { results in slightly more efficient code }
  1216. emit_tai(tai_label.create(result.lab),charptrdef);
  1217. result.ofs:=0;
  1218. { create new label of the same kind (including whether or not the
  1219. name starts with target_asm.labelprefix in case it's AB_LOCAL,
  1220. so we keep the difference depending on whether the original was
  1221. allocated via getstatic/getlocal/getglobal datalabel) }
  1222. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$strlab',startlab.bind,startlab.typ);
  1223. end;
  1224. { sanity check }
  1225. if result.ofs<>string_symofs then
  1226. internalerror(2012051701);
  1227. end;
  1228. function ttai_typedconstbuilder.get_dynstring_def_for_type(stringtype: tstringtype; winlikewidestring: boolean): tstringdef;
  1229. begin
  1230. if stringtype=st_ansistring then
  1231. result:=tstringdef(cansistringtype)
  1232. else if (stringtype=st_unicodestring) or
  1233. ((stringtype=st_widestring) and
  1234. not winlikewidestring) then
  1235. result:=tstringdef(cunicodestringtype)
  1236. else if stringtype=st_widestring then
  1237. result:=tstringdef(cwidestringtype)
  1238. else
  1239. internalerror(2015122101);
  1240. end;
  1241. procedure ttai_typedconstbuilder.begin_aggregate_internal(def: tdef; anonymous: boolean);
  1242. var
  1243. info: taggregateinformation;
  1244. tck: ttypedconstkind;
  1245. begin
  1246. tck:=aggregate_kind(def);
  1247. if tck=tck_simple then
  1248. exit;
  1249. if not assigned(faggregateinformation) then
  1250. faggregateinformation:=tfpobjectlist.create
  1251. { if we're starting an anonymous record, we can't align it yet because
  1252. the alignment depends on the fields that will be added -> we'll do
  1253. it at the end }
  1254. else if not anonymous or
  1255. ((def.typ<>recorddef) and
  1256. not is_object(def)) then
  1257. begin
  1258. { add padding if necessary, and update the current field/offset }
  1259. info:=curagginfo;
  1260. if (is_record(curagginfo.def) or
  1261. is_object(curagginfo.def)) and
  1262. not is_packed_record_or_object(curagginfo.def) then
  1263. begin
  1264. if queue_is_active then
  1265. internalerror(2015073001);
  1266. pad_next_field(def);
  1267. end;
  1268. end
  1269. { if this is the outer record, no padding is required; the alignment
  1270. has to be specified explicitly in that case via get_final_asmlist() }
  1271. else if assigned(curagginfo) and
  1272. (curagginfo.def.typ=recorddef) then
  1273. { mark where we'll have to insert the padding bytes at the end }
  1274. mark_anon_aggregate_alignment;
  1275. info:=caggregateinformation.create(def,aggregate_kind(def));
  1276. faggregateinformation.add(info);
  1277. end;
  1278. procedure ttai_typedconstbuilder.end_aggregate_internal(def: tdef; anonymous: boolean);
  1279. var
  1280. info: taggregateinformation;
  1281. tck: ttypedconstkind;
  1282. begin
  1283. tck:=aggregate_kind(def);
  1284. if tck=tck_simple then
  1285. exit;
  1286. { add tail padding if necessary }
  1287. maybe_emit_tail_padding(def);
  1288. { pop and free the information }
  1289. info:=curagginfo;
  1290. faggregateinformation.count:=faggregateinformation.count-1;
  1291. info.free;
  1292. end;
  1293. class function ttai_typedconstbuilder.get_vectorized_dead_strip_section_symbol(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions; start: boolean): tasmsymbol;
  1294. var
  1295. name: TSymStr;
  1296. asmtype : TAsmsymtype;
  1297. begin
  1298. if start then
  1299. name:=make_mangledname(basename,st,'START')
  1300. else
  1301. name:=make_mangledname(basename,st,'END');
  1302. if tcdssso_define in options then
  1303. begin
  1304. if tcdssso_use_indirect in options then
  1305. asmtype:=AT_DATA_FORCEINDIRECT
  1306. else
  1307. asmtype:=AT_DATA;
  1308. result:=current_asmdata.DefineAsmSymbol(name,AB_GLOBAL,asmtype,voidpointertype);
  1309. if tcdssso_register_asmsym in options then
  1310. current_module.add_public_asmsym(result);
  1311. end
  1312. else
  1313. begin
  1314. result:=current_asmdata.RefAsmSymbol(name,AT_DATA,tcdssso_use_indirect in options);
  1315. if tcdssso_register_asmsym in options then
  1316. current_module.add_extern_asmsym(result);
  1317. end;
  1318. end;
  1319. class function ttai_typedconstbuilder.get_vectorized_dead_strip_custom_section_name(const basename: TSymStr; st: tsymtable; out secname: TSymStr): boolean;
  1320. begin
  1321. result:=false;
  1322. end;
  1323. class function ttai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_start(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol;
  1324. begin
  1325. result:=get_vectorized_dead_strip_section_symbol(basename,st,options,true);
  1326. end;
  1327. class function ttai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_end(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol;
  1328. begin
  1329. result:=get_vectorized_dead_strip_section_symbol(basename,st,options,false);
  1330. end;
  1331. class function ttai_typedconstbuilder.get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): TSymStr;
  1332. begin
  1333. case typ of
  1334. st_ansistring:
  1335. result:='ansistrrec';
  1336. st_unicodestring,
  1337. st_widestring:
  1338. if (typ=st_unicodestring) or
  1339. not winlike then
  1340. result:='unicodestrrec'
  1341. else
  1342. result:='widestrrec';
  1343. else
  1344. internalerror(2014080402);
  1345. end;
  1346. result:=result+tostr(len);
  1347. end;
  1348. class function ttai_typedconstbuilder.get_dynstring_rec(typ: tstringtype; winlike: boolean; len: asizeint): trecorddef;
  1349. var
  1350. name: TSymStr;
  1351. streledef: tdef;
  1352. strtypesym: ttypesym;
  1353. srsym: tsym;
  1354. srsymtable: tsymtable;
  1355. begin
  1356. name:=get_dynstring_rec_name(typ,winlike,len);
  1357. { search in the interface of all units for the type to reuse it }
  1358. if searchsym_type(name,srsym,srsymtable) then
  1359. begin
  1360. result:=trecorddef(ttypesym(srsym).typedef);
  1361. exit;
  1362. end
  1363. else
  1364. begin
  1365. { also search the implementation of the current unit }
  1366. strtypesym:=try_search_current_module_type(name);
  1367. if assigned(strtypesym) then
  1368. begin
  1369. result:=trecorddef(strtypesym.typedef);
  1370. exit;
  1371. end;
  1372. end;
  1373. if (typ<>st_widestring) or
  1374. not winlike then
  1375. begin
  1376. result:=crecorddef.create_global_internal('$'+name,1,1,1);
  1377. { encoding }
  1378. result.add_field_by_def('',u16inttype);
  1379. { element size }
  1380. result.add_field_by_def('',u16inttype);
  1381. { elements }
  1382. case typ of
  1383. st_ansistring:
  1384. streledef:=cansichartype;
  1385. st_unicodestring:
  1386. streledef:=cwidechartype;
  1387. else
  1388. internalerror(2016082301);
  1389. end;
  1390. {$ifdef cpu64bitaddr}
  1391. { dummy for alignment }
  1392. result.add_field_by_def('',u32inttype);
  1393. {$endif cpu64bitaddr}
  1394. { reference count }
  1395. result.add_field_by_def('',sizesinttype);
  1396. { length in elements }
  1397. result.add_field_by_def('',sizesinttype);
  1398. end
  1399. else
  1400. begin
  1401. result:=crecorddef.create_global_internal('$'+name,4,
  1402. targetinfos[target_info.system]^.alignment.recordalignmin,
  1403. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1404. { length in bytes }
  1405. result.add_field_by_def('',s32inttype);
  1406. streledef:=cwidechartype;
  1407. end;
  1408. { data (include zero terminator) }
  1409. result.add_field_by_def('',carraydef.getreusable(streledef,len+1));
  1410. trecordsymtable(trecorddef(result).symtable).addalignmentpadding;
  1411. end;
  1412. function ttai_typedconstbuilder.emit_ansistring_const(datalist: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding): tasmlabofs;
  1413. var
  1414. s: PChar;
  1415. startlab: tasmlabel;
  1416. ansistrrecdef: trecorddef;
  1417. datadef: tdef;
  1418. datatcb: ttai_typedconstbuilder;
  1419. begin
  1420. start_internal_data_builder(datalist,sec_rodata_norel,'',datatcb,startlab);
  1421. result:=datatcb.emit_string_const_common(st_ansistring,len,encoding,startlab);
  1422. getmem(s,len+1);
  1423. move(data^,s^,len);
  1424. s[len]:=#0;
  1425. { terminating zero included }
  1426. datadef:=carraydef.getreusable(cansichartype,len+1);
  1427. datatcb.maybe_begin_aggregate(datadef);
  1428. datatcb.emit_tai(tai_string.create_pchar(s,len+1),datadef);
  1429. datatcb.maybe_end_aggregate(datadef);
  1430. ansistrrecdef:=datatcb.end_anonymous_record;
  1431. finish_internal_data_builder(datatcb,startlab,ansistrrecdef,const_align(sizeof(pointer)));
  1432. end;
  1433. function ttai_typedconstbuilder.emit_unicodestring_const(datalist: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  1434. var
  1435. i, strlength: longint;
  1436. string_symofs: asizeint;
  1437. startlab: tasmlabel;
  1438. datadef: tdef;
  1439. datatcb: ttai_typedconstbuilder;
  1440. unicodestrrecdef: trecorddef;
  1441. begin
  1442. start_internal_data_builder(datalist,sec_rodata_norel,'',datatcb,startlab);
  1443. strlength:=getlengthwidestring(pcompilerwidestring(data));
  1444. if winlike then
  1445. begin
  1446. result.lab:=startlab;
  1447. datatcb.begin_anonymous_record('$'+get_dynstring_rec_name(st_widestring,true,strlength),
  1448. 4,4,
  1449. targetinfos[target_info.system]^.alignment.recordalignmin,
  1450. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1451. datatcb.emit_tai(Tai_const.Create_32bit(strlength*cwidechartype.size),s32inttype);
  1452. { can we optimise by placing the string constant label at the
  1453. required offset? }
  1454. string_symofs:=get_string_symofs(st_widestring,true);
  1455. if string_symofs=0 then
  1456. begin
  1457. { yes }
  1458. datatcb.emit_tai(Tai_label.Create(result.lab),widecharpointertype);
  1459. { allocate a separate label for the start of the data (see
  1460. emit_string_const_common() for explanation) }
  1461. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$strlab',startlab.bind,startlab.typ);
  1462. end
  1463. else
  1464. internalerror(2015031502);
  1465. result.ofs:=string_symofs;
  1466. end
  1467. else
  1468. begin
  1469. result:=datatcb.emit_string_const_common(st_unicodestring,strlength,encoding,startlab);
  1470. end;
  1471. if cwidechartype.size = 2 then
  1472. begin
  1473. datadef:=carraydef.getreusable(cwidechartype,strlength+1);
  1474. datatcb.maybe_begin_aggregate(datadef);
  1475. for i:=0 to strlength-1 do
  1476. datatcb.emit_tai(Tai_const.Create_16bit(pcompilerwidestring(data)^.data[i]),cwidechartype);
  1477. { ending #0 }
  1478. datatcb.emit_tai(Tai_const.Create_16bit(0),cwidechartype);
  1479. datatcb.maybe_end_aggregate(datadef);
  1480. unicodestrrecdef:=datatcb.end_anonymous_record;
  1481. end
  1482. else
  1483. { code generation for other sizes must be written }
  1484. internalerror(200904271);
  1485. finish_internal_data_builder(datatcb,startlab,unicodestrrecdef,const_align(sizeof(pint)));
  1486. end;
  1487. procedure ttai_typedconstbuilder.emit_string_offset(const ll: tasmlabofs; const strlength: longint; const st: tstringtype; const winlikewidestring: boolean; const charptrdef: tdef);
  1488. begin
  1489. emit_tai(Tai_const.Create_sym_offset(ll.lab,ll.ofs),get_dynstring_def_for_type(st,winlikewidestring));
  1490. end;
  1491. function ttai_typedconstbuilder.emit_shortstring_const(const str: shortstring): tdef;
  1492. begin
  1493. { we use an arraydef instead of a shortstringdef, because we don't have
  1494. functionality in place yet to reuse shortstringdefs of the same length
  1495. and neither the lowlevel nor the llvm typedconst builder cares about
  1496. this difference }
  1497. result:=carraydef.getreusable(cansichartype,length(str)+1);
  1498. maybe_begin_aggregate(result);
  1499. emit_tai(Tai_const.Create_8bit(length(str)),u8inttype);
  1500. if str<>'' then
  1501. emit_tai(Tai_string.Create(str),carraydef.getreusable(cansichartype,length(str)));
  1502. maybe_end_aggregate(result);
  1503. end;
  1504. function ttai_typedconstbuilder.emit_pchar_const(str: pchar; len: pint; copypchar: boolean): tdef;
  1505. var
  1506. newstr: pchar;
  1507. begin
  1508. result:=carraydef.getreusable(cansichartype,len+1);
  1509. maybe_begin_aggregate(result);
  1510. if (len=0) and
  1511. (not assigned(str) or
  1512. copypchar) then
  1513. emit_tai(Tai_const.Create_8bit(0),cansichartype)
  1514. else
  1515. begin
  1516. if copypchar then
  1517. begin
  1518. getmem(newstr,len+1);
  1519. move(str^,newstr^,len+1);
  1520. str:=newstr;
  1521. end;
  1522. emit_tai(Tai_string.Create_pchar(str,len+1),result);
  1523. end;
  1524. maybe_end_aggregate(result);
  1525. end;
  1526. procedure ttai_typedconstbuilder.emit_guid_const(const guid: tguid);
  1527. var
  1528. i: longint;
  1529. field: tfieldvarsym;
  1530. begin
  1531. maybe_begin_aggregate(rec_tguid);
  1532. { variant record -> must specify which fields get initialised }
  1533. next_field:=tfieldvarsym(rec_tguid.symtable.Find('DATA1'));
  1534. emit_tai(Tai_const.Create_32bit(longint(guid.D1)),u32inttype);
  1535. next_field:=tfieldvarsym(rec_tguid.symtable.Find('DATA2'));
  1536. emit_tai(Tai_const.Create_16bit(guid.D2),u16inttype);
  1537. next_field:=tfieldvarsym(rec_tguid.symtable.Find('DATA3'));
  1538. emit_tai(Tai_const.Create_16bit(guid.D3),u16inttype);
  1539. field:=tfieldvarsym(rec_tguid.symtable.Find('DATA4'));
  1540. next_field:=field;
  1541. { the array }
  1542. maybe_begin_aggregate(field.vardef);
  1543. for i:=Low(guid.D4) to High(guid.D4) do
  1544. emit_tai(Tai_const.Create_8bit(guid.D4[i]),u8inttype);
  1545. maybe_end_aggregate(field.vardef);
  1546. maybe_end_aggregate(rec_tguid);
  1547. end;
  1548. procedure ttai_typedconstbuilder.emit_procdef_const(pd: tprocdef);
  1549. begin
  1550. emit_tai(Tai_const.Createname(pd.mangledname,AT_FUNCTION,0),cprocvardef.getreusableprocaddr(pd));
  1551. end;
  1552. procedure ttai_typedconstbuilder.emit_ord_const(value: int64; def: tdef);
  1553. begin
  1554. case def.size of
  1555. 1:
  1556. emit_tai(Tai_const.Create_8bit(byte(value)),def);
  1557. 2:
  1558. emit_tai(Tai_const.Create_16bit(word(value)),def);
  1559. 4:
  1560. emit_tai(Tai_const.Create_32bit(longint(value)),def);
  1561. 8:
  1562. emit_tai(Tai_const.Create_64bit(value),def);
  1563. else
  1564. internalerror(2014100501);
  1565. end;
  1566. end;
  1567. procedure ttai_typedconstbuilder.maybe_begin_aggregate(def: tdef);
  1568. begin
  1569. begin_aggregate_internal(def,false);
  1570. end;
  1571. procedure ttai_typedconstbuilder.maybe_end_aggregate(def: tdef);
  1572. begin
  1573. end_aggregate_internal(def,false);
  1574. end;
  1575. function ttai_typedconstbuilder.begin_anonymous_record(const optionalname: string; packrecords, recordalign, recordalignmin, maxcrecordalign: shortint): trecorddef;
  1576. var
  1577. anonrecorddef: trecorddef;
  1578. typesym: ttypesym;
  1579. begin
  1580. { if the name is specified, we create a typesym with that name in order
  1581. to ensure we can find it again later with that name -> reuse here as
  1582. well if possible (and that also avoids duplicate type name issues) }
  1583. if optionalname<>'' then
  1584. begin
  1585. typesym:=try_search_current_module_type(optionalname);
  1586. if assigned(typesym) then
  1587. begin
  1588. if typesym.typedef.typ<>recorddef then
  1589. internalerror(2015071401);
  1590. result:=trecorddef(typesym.typedef);
  1591. maybe_begin_aggregate(result);
  1592. exit;
  1593. end;
  1594. end;
  1595. { create skeleton def }
  1596. anonrecorddef:=crecorddef.create_global_internal(optionalname,packrecords,recordalignmin,maxcrecordalign);
  1597. trecordsymtable(anonrecorddef.symtable).recordalignment:=recordalign;
  1598. { generic aggregate housekeeping }
  1599. begin_aggregate_internal(anonrecorddef,true);
  1600. { mark as anonymous record }
  1601. curagginfo.anonrecord:=true;
  1602. { in case a descendent wants to do something with the anonrecorddef too }
  1603. result:=anonrecorddef;
  1604. end;
  1605. function ttai_typedconstbuilder.end_anonymous_record: trecorddef;
  1606. var
  1607. info: taggregateinformation;
  1608. anonrecord: boolean;
  1609. begin
  1610. info:=curagginfo;
  1611. if not assigned(info) or
  1612. (info.def.typ<>recorddef) then
  1613. internalerror(2014080201);
  1614. result:=trecorddef(info.def);
  1615. { make a copy, as we need it after info has been freed by
  1616. maybe_end_aggregate(result) }
  1617. anonrecord:=info.anonrecord;
  1618. { finalise the record skeleton (all fields have been added already by
  1619. emit_tai()) -- anonrecord may not be set in case we reused an earlier
  1620. constructed def }
  1621. if anonrecord then
  1622. trecordsymtable(result.symtable).addalignmentpadding;
  1623. end_aggregate_internal(result,true);
  1624. if anonrecord and
  1625. assigned(curagginfo) and
  1626. (curagginfo.def.typ=recorddef) then
  1627. insert_marked_aggregate_alignment(result);
  1628. end;
  1629. procedure ttai_typedconstbuilder.check_add_placeholder(def: tdef);
  1630. begin
  1631. { it only makes sense to add a placeholder inside an aggregate
  1632. (otherwise there can be but one element)
  1633. we cannot add a placeholder in the middle of a queued expression
  1634. either
  1635. the placeholder cannot be an aggregate }
  1636. if not assigned(curagginfo) or
  1637. queue_is_active or
  1638. (aggregate_kind(def)<>tck_simple) then
  1639. internalerror(2015091001);
  1640. end;
  1641. procedure ttai_typedconstbuilder.queue_init(todef: tdef);
  1642. var
  1643. info: taggregateinformation;
  1644. begin
  1645. { nested call to init? }
  1646. if fqueue_offset<>low(fqueue_offset) then
  1647. internalerror(2014062101);
  1648. { insert padding bytes before starting the queue, so that the first
  1649. padding byte won't be interpreted as the emitted value for this queue }
  1650. info:=curagginfo;
  1651. if assigned(info) then
  1652. begin
  1653. if ((info.def.typ=recorddef) or
  1654. is_object(info.def)) and
  1655. { may add support for these later }
  1656. not is_packed_record_or_object(info.def) then
  1657. pad_next_field(todef);
  1658. end;
  1659. fqueue_offset:=0;
  1660. fqueued_def:=todef;
  1661. end;
  1662. procedure ttai_typedconstbuilder.queue_vecn(def: tdef; const index: tconstexprint);
  1663. var
  1664. elelen,
  1665. vecbase: asizeint;
  1666. v: tconstexprint;
  1667. begin
  1668. elelen:=1;
  1669. vecbase:=0;
  1670. case def.typ of
  1671. stringdef :
  1672. ;
  1673. arraydef :
  1674. begin
  1675. if not is_packed_array(def) then
  1676. begin
  1677. elelen:=tarraydef(def).elesize;
  1678. vecbase:=tarraydef(def).lowrange;
  1679. end
  1680. else
  1681. Message(parser_e_packed_dynamic_open_array);
  1682. end;
  1683. else
  1684. Message(parser_e_illegal_expression);
  1685. end;
  1686. { Prevent overflow }
  1687. v:=index-vecbase;
  1688. if (v<int64(low(fqueue_offset))) or (v>int64(high(fqueue_offset))) then
  1689. message3(type_e_range_check_error_bounds,tostr(v),tostr(low(fqueue_offset)),tostr(high(fqueue_offset)));
  1690. if high(fqueue_offset)-fqueue_offset div elelen>v then
  1691. inc(fqueue_offset,elelen*v.svalue)
  1692. else
  1693. message3(type_e_range_check_error_bounds,tostr(index),tostr(vecbase),tostr(high(fqueue_offset)-fqueue_offset div elelen+vecbase))
  1694. end;
  1695. procedure ttai_typedconstbuilder.queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym);
  1696. begin
  1697. inc(fqueue_offset,vs.fieldoffset);
  1698. end;
  1699. function ttai_typedconstbuilder.queue_subscriptn_multiple_by_name(def: tabstractrecorddef; const fields: array of TIDString): tdef;
  1700. var
  1701. syms,
  1702. parentdefs: tfplist;
  1703. sym: tsym;
  1704. curdef: tdef;
  1705. i: longint;
  1706. begin
  1707. result:=nil;
  1708. if length(fields)=0 then
  1709. internalerror(2015071601);
  1710. syms:=tfplist.Create;
  1711. syms.count:=length(fields);
  1712. parentdefs:=tfplist.create;
  1713. parentdefs.Count:=length(fields);
  1714. curdef:=def;
  1715. for i:=low(fields) to high(fields) do
  1716. begin
  1717. sym:=search_struct_member_no_helper(tabstractrecorddef(curdef),fields[i]);
  1718. if not assigned(sym) or
  1719. (sym.typ<>fieldvarsym) or
  1720. ((i<>high(fields)) and
  1721. not(tfieldvarsym(sym).vardef.typ in [objectdef,recorddef])) then
  1722. internalerror(2015071505);
  1723. syms[i]:=sym;
  1724. parentdefs[i]:=curdef;
  1725. curdef:=tfieldvarsym(sym).vardef;
  1726. result:=curdef;
  1727. end;
  1728. for i:=high(fields) downto low(fields) do
  1729. queue_subscriptn(tabstractrecorddef(parentdefs[i]),tfieldvarsym(syms[i]));
  1730. syms.free;
  1731. parentdefs.free;
  1732. end;
  1733. procedure ttai_typedconstbuilder.queue_typeconvn(fromdef, todef: tdef);
  1734. begin
  1735. { do nothing }
  1736. end;
  1737. procedure ttai_typedconstbuilder.queue_emit_proc(pd: tprocdef);
  1738. begin
  1739. if fqueue_offset<>0 then
  1740. internalerror(2014092101);
  1741. emit_procdef_const(pd);
  1742. fqueue_offset:=low(fqueue_offset);
  1743. end;
  1744. procedure ttai_typedconstbuilder.queue_emit_staticvar(vs: tstaticvarsym);
  1745. begin
  1746. { pointerdef because we are emitting a pointer to the staticvarsym
  1747. data, not the data itself }
  1748. emit_tai(Tai_const.Createname(vs.mangledname,AT_DATA,fqueue_offset),cpointerdef.getreusable(vs.vardef));
  1749. fqueue_offset:=low(fqueue_offset);
  1750. end;
  1751. procedure ttai_typedconstbuilder.queue_emit_label(l: tlabelsym);
  1752. begin
  1753. emit_tai(Tai_const.Createname(l.mangledname,fqueue_offset),voidcodepointertype);
  1754. fqueue_offset:=low(fqueue_offset);
  1755. end;
  1756. procedure ttai_typedconstbuilder.queue_emit_const(cs: tconstsym);
  1757. var
  1758. resourcestrrec: trecorddef;
  1759. begin
  1760. if cs.consttyp<>constresourcestring then
  1761. internalerror(2014062102);
  1762. if fqueue_offset<>0 then
  1763. internalerror(2014062103);
  1764. { warning: update if/when the type of resource strings changes }
  1765. case cs.consttyp of
  1766. constresourcestring:
  1767. begin
  1768. resourcestrrec:=trecorddef(search_system_type('TRESOURCESTRINGRECORD').typedef);
  1769. queue_subscriptn_multiple_by_name(resourcestrrec,['CURRENTVALUE']);
  1770. queue_emit_asmsym(current_asmdata.RefAsmSymbol(
  1771. make_mangledname('RESSTR',cs.owner,cs.name),AT_DATA),resourcestrrec
  1772. );
  1773. end;
  1774. { can these occur? }
  1775. constord,
  1776. conststring,constreal,
  1777. constset,constpointer,constnil,
  1778. constwstring,constguid:
  1779. internalerror(2015090903);
  1780. else
  1781. internalerror(2015090904);
  1782. end;
  1783. fqueue_offset:=low(fqueue_offset);
  1784. end;
  1785. procedure ttai_typedconstbuilder.queue_emit_asmsym(sym: tasmsymbol; def: tdef);
  1786. begin
  1787. { pointerdef, because "sym" represents the address of whatever the
  1788. data is }
  1789. def:=cpointerdef.getreusable(def);
  1790. emit_tai(Tai_const.Create_sym_offset(sym,fqueue_offset),def);
  1791. fqueue_offset:=low(fqueue_offset);
  1792. end;
  1793. procedure ttai_typedconstbuilder.queue_emit_ordconst(value: int64; def: tdef);
  1794. begin
  1795. emit_ord_const(value,def);
  1796. fqueue_offset:=low(fqueue_offset);
  1797. end;
  1798. function ttai_typedconstbuilder.queue_is_active: boolean;
  1799. begin
  1800. result:=fqueue_offset<>low(fqueue_offset)
  1801. end;
  1802. {****************************************************************************
  1803. tlowleveltypedconstplaceholder
  1804. ****************************************************************************}
  1805. constructor tlowleveltypedconstplaceholder.create(l: tasmlist; pos: tai; d: tdef);
  1806. begin
  1807. inherited create(d);
  1808. list:=l;
  1809. insertpos:=pos;
  1810. end;
  1811. procedure tlowleveltypedconstplaceholder.replace(ai: tai; d: tdef);
  1812. begin
  1813. if d<>def then
  1814. internalerror(2015091001);
  1815. list.insertafter(ai,insertpos);
  1816. list.remove(insertpos);
  1817. insertpos.free;
  1818. end;
  1819. {****************************************************************************
  1820. tai_abstracttypedconst
  1821. ****************************************************************************}
  1822. class constructor ttai_lowleveltypedconstbuilder.classcreate;
  1823. begin
  1824. caggregateinformation:=tlowlevelaggregateinformation;
  1825. end;
  1826. function ttai_lowleveltypedconstbuilder.emit_placeholder(def: tdef): ttypedconstplaceholder;
  1827. var
  1828. p: tai;
  1829. begin
  1830. check_add_placeholder(def);
  1831. p:=tai_marker.Create(mark_position);
  1832. emit_tai(p,def);
  1833. result:=tlowleveltypedconstplaceholder.create(fasmlist,p,def);
  1834. end;
  1835. procedure ttai_lowleveltypedconstbuilder.mark_anon_aggregate_alignment;
  1836. var
  1837. marker: tai_marker;
  1838. begin
  1839. marker:=tai_marker.Create(mark_position);
  1840. fasmlist.concat(marker);
  1841. tlowlevelaggregateinformation(curagginfo).anonrecmarker:=marker;
  1842. end;
  1843. procedure ttai_lowleveltypedconstbuilder.insert_marked_aggregate_alignment(def: tdef);
  1844. var
  1845. info: tlowlevelaggregateinformation;
  1846. fillbytes: asizeint;
  1847. begin
  1848. info:=tlowlevelaggregateinformation(curagginfo);
  1849. if not assigned(info.anonrecmarker) then
  1850. internalerror(2014091401);
  1851. fillbytes:=info.prepare_next_field(def);
  1852. while fillbytes>0 do
  1853. begin
  1854. fasmlist.insertafter(tai_const.create_8bit(0),info.anonrecmarker);
  1855. dec(fillbytes);
  1856. end;
  1857. fasmlist.remove(info.anonrecmarker);
  1858. info.anonrecmarker.free;
  1859. info.anonrecmarker:=nil;
  1860. end;
  1861. procedure ttai_lowleveltypedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  1862. begin
  1863. inherited;
  1864. { The darwin/ppc64 assembler or linker seems to have trouble }
  1865. { if a section ends with a global label without any data after it. }
  1866. { So for safety, just put a dummy value here. }
  1867. { Further, the regular linker also kills this symbol when turning }
  1868. { on smart linking in case no value appears after it, so put the }
  1869. { dummy byte there always }
  1870. { Update: the Mac OS X 10.6 linker orders data that needs to be }
  1871. { relocated before all other data, so make this data relocatable, }
  1872. { otherwise the end label won't be moved with the rest }
  1873. if (tcalo_vectorized_dead_strip_end in options) and
  1874. (target_info.system in (systems_darwin+systems_aix)) then
  1875. fasmlist.concat(Tai_const.create_sym(sym));
  1876. end;
  1877. begin
  1878. ctai_typedconstbuilder:=ttai_lowleveltypedconstbuilder;
  1879. end.