aasmcnst.pas 86 KB

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