aasmcnst.pas 84 KB

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