aasmcnst.pas 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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,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. protected
  45. fval: tai;
  46. public
  47. constructor create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  48. property val: tai read fval;
  49. end;
  50. { an aggregate data element (record or array). Values are stored as an
  51. array of tsimpledataelement. }
  52. tai_aggregatetypedconst = class(tai_abstracttypedconst)
  53. public type
  54. { iterator to walk over all individual items in the aggregate }
  55. tadeenumerator = class(tobject)
  56. private
  57. fvalues: tfplist;
  58. fvaluespos: longint;
  59. function getcurrent: tai_abstracttypedconst;
  60. public
  61. constructor create(data: tai_aggregatetypedconst);
  62. function movenext: boolean;
  63. procedure reset;
  64. property current: tai_abstracttypedconst read getcurrent;
  65. end;
  66. protected
  67. fvalues: tfplist;
  68. fisstring: boolean;
  69. { converts the existing data to a single tai_string }
  70. procedure convert_to_string;
  71. procedure add_to_string(strtai: tai_string; othertai: tai);
  72. public
  73. constructor create(_adetyp: ttypedconstkind; _fdef: tdef);
  74. function getenumerator: tadeenumerator;
  75. procedure addvalue(val: tai_abstracttypedconst);
  76. function valuecount: longint;
  77. procedure insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  78. procedure finish;
  79. destructor destroy; override;
  80. end;
  81. tasmlabofs = record
  82. lab: tasmlabel;
  83. ofs: asizeint;
  84. end;
  85. { flags for the finalisation of the typed const builder asmlist }
  86. ttcasmlistoption = (
  87. { the tasmsymbol is a tasmlabel }
  88. tcalo_is_lab,
  89. { start a new section }
  90. tcalo_new_section
  91. );
  92. ttcasmlistoptions = set of ttcasmlistoption;
  93. { information about aggregates we are parsing }
  94. taggregateinformation = class
  95. private
  96. function getcuroffset: asizeint;
  97. function getfieldoffset(l: longint): asizeint;
  98. protected
  99. { type of the aggregate }
  100. fdef: tdef;
  101. { type of the aggregate }
  102. ftyp: ttypedconstkind;
  103. { symtable entry of the previously emitted field in case of a
  104. record/object (nil if none emitted yet), used to insert alignment bytes
  105. if necessary for variant records and objects }
  106. fcurfield,
  107. { field corresponding to the data that will be emitted next in case of a
  108. record/object (nil if not set), used to handle variant records and
  109. objects }
  110. fnextfield: tfieldvarsym;
  111. { similar as the fcurfield/fnextfield above, but instead of fieldvarsyms
  112. these are indices in the symlist of a recorddef that correspond to
  113. fieldvarsyms. These are used only for non-variant records, simply
  114. traversing the fields in order. We could use the above method here as
  115. well, but to find the next field we'd always have to use
  116. symlist.indexof(fcurfield), which would be quite slow. These have -1 as
  117. value if they're not set }
  118. fcurindex,
  119. fnextindex: longint;
  120. { anonymous record that is being built as we add constant data }
  121. fanonrecord: boolean;
  122. property curindex: longint read fcurindex write fcurindex;
  123. property nextindex: longint read fnextindex write fnextindex;
  124. public
  125. constructor create(_def: tdef; _typ: ttypedconstkind); virtual;
  126. { calculated padding bytes for alignment if needed, and add the def of the
  127. next field in case we are constructing an anonymous record }
  128. function prepare_next_field(nextfielddef: tdef): asizeint;
  129. property def: tdef read fdef;
  130. property typ: ttypedconstkind read ftyp;
  131. property curfield: tfieldvarsym read fcurfield write fcurfield;
  132. property nextfield: tfieldvarsym read fnextfield write fnextfield;
  133. property fieldoffset[l: longint]: asizeint read getfieldoffset;
  134. property curoffset: asizeint read getcuroffset;
  135. property anonrecord: boolean read fanonrecord write fanonrecord;
  136. end;
  137. taggregateinformationclass = class of taggregateinformation;
  138. { Warning: never directly create a ttai_typedconstbuilder instance,
  139. instead create a cai_typedconstbuilder (this class can be overridden) }
  140. ttai_typedconstbuilder = class abstract
  141. { class type to use when creating new aggregate information instances }
  142. protected class var
  143. caggregateinformation: taggregateinformationclass;
  144. private
  145. function getcurragginfo: taggregateinformation;
  146. procedure set_next_field(AValue: tfieldvarsym);
  147. protected
  148. { temporary list in which all data is collected }
  149. fasmlist: tasmlist;
  150. { while queueing elements of a compound expression, this is the current
  151. offset in the top-level array/record }
  152. fqueue_offset: asizeint;
  153. { array of caggregateinformation instances }
  154. faggregateinformation: tfpobjectlist;
  155. { ensure that finalize_asmlist is called only once }
  156. fasmlist_finalized: boolean;
  157. { returns whether def must be handled as an aggregate on the current
  158. platform }
  159. function aggregate_kind(def: tdef): ttypedconstkind; virtual;
  160. { finalize the asmlist: add the necessary symbols etc }
  161. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); virtual;
  162. { called by the public emit_tai() routines to actually add the typed
  163. constant data; the public ones also take care of adding extra padding
  164. bytes etc (by calling this one) }
  165. procedure do_emit_tai(p: tai; def: tdef); virtual;
  166. { calls prepare_next_field() and adds the padding bytes in the current
  167. location }
  168. procedure pad_next_field(nextfielddef: tdef);
  169. { easy access to the top level aggregate information instance }
  170. property curagginfo: taggregateinformation read getcurragginfo;
  171. public
  172. constructor create; virtual;
  173. destructor destroy; override;
  174. { add a simple constant data element (p) to the typed constant.
  175. def is the type of the added value }
  176. procedure emit_tai(p: tai; def: tdef); virtual;
  177. { same as above, for a special case: when the def is a procvardef and we
  178. want to use it explicitly as a procdef (i.e., not as a record with a
  179. code and data pointer in case of a complex procvardef) }
  180. procedure emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef); virtual;
  181. protected
  182. function emit_string_const_common(list: TAsmList; stringtype: tstringtype; len: asizeint; encoding: tstringencoding; out startlab: tasmlabel):tasmlabofs;
  183. procedure begin_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  184. procedure end_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  185. { when building an anonymous record, we cannot immediately insert the
  186. alignment before it in case it's nested, since we only know the required
  187. alignment once all fields have been inserted -> mark the location before
  188. the anonymous record, and insert the alignment once it's finished }
  189. procedure mark_anon_aggregate_alignment; virtual; abstract;
  190. procedure insert_marked_aggregate_alignment(def: tdef); virtual; abstract;
  191. public
  192. class function get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): string;
  193. { class functions and an extra list parameter, because emitting the data
  194. for the strings has to happen via a separate typed const builder (which
  195. will be created/destroyed internally by these methods) }
  196. class function emit_ansistring_const(list: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding; newsection: boolean): tasmlabofs;
  197. class function emit_unicodestring_const(list: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  198. { begin a potential aggregate type. Must be called for any type
  199. that consists of multiple tai constant data entries, or that
  200. represents an aggregate at the Pascal level (a record, a non-dynamic
  201. array, ... }
  202. procedure maybe_begin_aggregate(def: tdef);
  203. { end a potential aggregate type. Must be paired with every
  204. maybe_begin_aggregate }
  205. procedure maybe_end_aggregate(def: tdef);
  206. { similar as above, but in case
  207. a) it's definitely a record
  208. b) the def of the record should be automatically constructed based on
  209. the types of the emitted fields
  210. }
  211. function begin_anonymous_record(const optionalname: string; packrecords: shortint): trecorddef; virtual;
  212. function end_anonymous_record: trecorddef; virtual;
  213. { The next group of routines are for constructing complex expressions.
  214. While parsing a typed constant these operators are encountered from
  215. outer to inner, so that is also the order in which they should be
  216. added to the queue. Only one queue can be active at a time. }
  217. { Init the queue. Gives an internalerror if a queue was already active }
  218. procedure queue_init(todef: tdef); virtual;
  219. { queue an array/string indexing operation (performs all range checking,
  220. so it doesn't have to be duplicated in all descendents). }
  221. procedure queue_vecn(def: tdef; const index: tconstexprint); virtual;
  222. { queue a subscripting operation }
  223. procedure queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym); virtual;
  224. { queue a type conversion operation }
  225. procedure queue_typeconvn(fromdef, todef: tdef); virtual;
  226. { queue an address taking operation }
  227. procedure queue_addrn(fromdef, todef: tdef); virtual;
  228. { finalise the queue (so a new one can be created) and flush the
  229. previously queued operations, applying them in reverse order on a...}
  230. { ... procdef }
  231. procedure queue_emit_proc(pd: tprocdef); virtual;
  232. { ... staticvarsym }
  233. procedure queue_emit_staticvar(vs: tstaticvarsym); virtual;
  234. { ... labelsym }
  235. procedure queue_emit_label(l: tlabelsym); virtual;
  236. { ... constsym }
  237. procedure queue_emit_const(cs: tconstsym); virtual;
  238. { ... asmsym/asmlabel }
  239. procedure queue_emit_asmsym(sym: tasmsymbol; def: tdef); virtual;
  240. { finalize the internal asmlist (if necessary) and return it.
  241. This asmlist will be freed when the builder is destroyed, so add its
  242. contents to another list first. This property should only be accessed
  243. once all data has been added. }
  244. function get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint; const options: ttcasmlistoptions): tasmlist;
  245. { returns the offset of the string data relative to ansi/unicode/widestring
  246. constant labels. On most platforms, this is 0 (with the header at a
  247. negative offset), but on some platforms such negative offsets are not
  248. supported this is equal to the header size }
  249. class function get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint; virtual;
  250. { set the fieldvarsym whose data we will emit next; needed
  251. in case of variant records, so we know which part of the variant gets
  252. initialised. Also in case of objects, because the fieldvarsyms are spread
  253. over the symtables of the entire inheritance tree }
  254. property next_field: tfieldvarsym write set_next_field;
  255. protected
  256. { this one always return the actual offset, called by the above (and
  257. overridden versions) }
  258. class function get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  259. end;
  260. ttai_typedconstbuilderclass = class of ttai_typedconstbuilder;
  261. tlowlevelaggregateinformation = class(taggregateinformation)
  262. protected
  263. fanonrecmarker: tai;
  264. public
  265. property anonrecmarker: tai read fanonrecmarker write fanonrecmarker;
  266. end;
  267. ttai_lowleveltypedconstbuilder = class(ttai_typedconstbuilder)
  268. protected
  269. procedure mark_anon_aggregate_alignment; override;
  270. procedure insert_marked_aggregate_alignment(def: tdef); override;
  271. public
  272. { set the default value for caggregateinformation (= tlowlevelaggregateinformation) }
  273. class constructor classcreate;
  274. end;
  275. var
  276. ctai_typedconstbuilder: ttai_typedconstbuilderclass;
  277. implementation
  278. uses
  279. verbose,globals,systems,widestr,
  280. symbase,symtable,defutil;
  281. {****************************************************************************
  282. taggregateinformation
  283. ****************************************************************************}
  284. function taggregateinformation.getcuroffset: asizeint;
  285. var
  286. field: tfieldvarsym;
  287. begin
  288. if assigned(curfield) then
  289. result:=curfield.fieldoffset+curfield.vardef.size
  290. else if curindex<>-1 then
  291. begin
  292. field:=tfieldvarsym(tabstractrecorddef(def).symtable.symlist[curindex]);
  293. result:=field.fieldoffset+field.vardef.size
  294. end
  295. else
  296. result:=0
  297. end;
  298. function taggregateinformation.getfieldoffset(l: longint): asizeint;
  299. var
  300. field: tfieldvarsym;
  301. begin
  302. field:=tfieldvarsym(tabstractrecorddef(def).symtable.symlist[l]);
  303. result:=field.fieldoffset;
  304. end;
  305. constructor taggregateinformation.create(_def: tdef; _typ: ttypedconstkind);
  306. begin
  307. fdef:=_def;
  308. ftyp:=_typ;
  309. fcurindex:=-1;
  310. fnextindex:=-1;
  311. end;
  312. function taggregateinformation.prepare_next_field(nextfielddef: tdef): asizeint;
  313. var
  314. currentoffset,nextoffset: asizeint;
  315. i: longint;
  316. begin
  317. { get the next field and its offset, and make that next field the current
  318. one }
  319. if assigned(nextfield) then
  320. begin
  321. nextoffset:=nextfield.fieldoffset;
  322. currentoffset:=curoffset;
  323. curfield:=nextfield;
  324. end
  325. else
  326. begin
  327. { must set nextfield for unions and objects, as we cannot
  328. automatically detect the "next" field in that case }
  329. if ((def.typ=recorddef) and
  330. trecorddef(def).isunion) or
  331. is_object(def) then
  332. internalerror(2014091202);
  333. { if we are constructing this record as data gets emitted, add a field
  334. for this data }
  335. if anonrecord then
  336. trecorddef(def).add_field_by_def(nextfielddef);
  337. { find next field }
  338. i:=curindex;
  339. repeat
  340. inc(i);
  341. until tsym(tabstractrecorddef(def).symtable.symlist[i]).typ=fieldvarsym;
  342. nextoffset:=fieldoffset[i];
  343. currentoffset:=curoffset;
  344. curindex:=i;
  345. end;
  346. { need padding? }
  347. result:=nextoffset-currentoffset;
  348. end;
  349. {****************************************************************************
  350. tai_abstracttypedconst
  351. ****************************************************************************}
  352. procedure tai_abstracttypedconst.setdef(def: tdef);
  353. begin
  354. { should not be changed, rewrite the calling code if this happens }
  355. if assigned(fdef) then
  356. Internalerror(2014080203);
  357. fdef:=def;
  358. end;
  359. constructor tai_abstracttypedconst.create(_adetyp: ttypedconstkind; _def: tdef);
  360. begin
  361. inherited create;
  362. typ:=ait_typedconst;
  363. fadetyp:=_adetyp;
  364. fdef:=_def;
  365. end;
  366. {****************************************************************************
  367. tai_simpletypedconst
  368. ****************************************************************************}
  369. constructor tai_simpletypedconst.create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  370. begin
  371. inherited create(_adetyp,_def);
  372. fval:=_val;
  373. end;
  374. {****************************************************************************
  375. tai_aggregatetypedconst.tadeenumerator
  376. ****************************************************************************}
  377. constructor tai_aggregatetypedconst.tadeenumerator.create(data: tai_aggregatetypedconst);
  378. begin
  379. fvalues:=data.fvalues;
  380. fvaluespos:=-1;
  381. end;
  382. function tai_aggregatetypedconst.tadeenumerator.getcurrent: tai_abstracttypedconst;
  383. begin
  384. result:=tai_abstracttypedconst(fvalues[fvaluespos]);
  385. end;
  386. function tai_aggregatetypedconst.tadeenumerator.movenext: boolean;
  387. begin
  388. if fvaluespos<pred(fvalues.count) then
  389. begin
  390. inc(fvaluespos);
  391. result:=true
  392. end
  393. else
  394. result:=false;
  395. end;
  396. procedure tai_aggregatetypedconst.tadeenumerator.reset;
  397. begin
  398. fvaluespos:=0
  399. end;
  400. {****************************************************************************
  401. tai_aggregatetypedconst
  402. ****************************************************************************}
  403. procedure tai_aggregatetypedconst.convert_to_string;
  404. var
  405. ai: tai_abstracttypedconst;
  406. newstr: tai_string;
  407. begin
  408. newstr:=tai_string.Create('');
  409. for ai in self do
  410. begin
  411. if ai.adetyp<>tck_simple then
  412. internalerror(2014070103);
  413. add_to_string(newstr,tai_simpletypedconst(ai).val);
  414. ai.free;
  415. end;
  416. fvalues.count:=0;
  417. { the "nil" def will be replaced with an array def of the appropriate
  418. size once we're finished adding data, so we don't create intermediate
  419. arraydefs all the time }
  420. fvalues.add(tai_simpletypedconst.create(tck_simple,nil,newstr));
  421. end;
  422. procedure tai_aggregatetypedconst.add_to_string(strtai: tai_string; othertai: tai);
  423. begin
  424. case othertai.typ of
  425. ait_string:
  426. begin
  427. strtai.str:=reallocmem(strtai.str,strtai.len+tai_string(othertai).len+1);
  428. { also copy null terminator }
  429. move(tai_string(othertai).str[0],strtai.str[strtai.len],tai_string(othertai).len+1);
  430. { the null terminator is not part of the string data }
  431. strtai.len:=strtai.len+tai_string(othertai).len;
  432. end;
  433. ait_const:
  434. begin
  435. if tai_const(othertai).size<>1 then
  436. internalerror(2014070101);
  437. strtai.str:=reallocmem(strtai.str,strtai.len+1);
  438. strtai.str[strtai.len]:=ansichar(tai_const(othertai).value);
  439. strtai.str[strtai.len+1]:=#0;
  440. inc(strtai.len);
  441. end;
  442. else
  443. internalerror(2014070102);
  444. end;
  445. end;
  446. constructor tai_aggregatetypedconst.create(_adetyp: ttypedconstkind; _fdef: tdef);
  447. begin
  448. inherited;
  449. fisstring:=false;
  450. fvalues:=tfplist.create;
  451. end;
  452. function tai_aggregatetypedconst.getenumerator: tadeenumerator;
  453. begin
  454. result:=tadeenumerator.create(self);
  455. end;
  456. procedure tai_aggregatetypedconst.addvalue(val: tai_abstracttypedconst);
  457. begin
  458. { merge string constants and ordinal constants added in an array of
  459. char, to unify the length and the string data }
  460. if fisstring or
  461. ((val.adetyp=tck_simple) and
  462. (tai_simpletypedconst(val).val.typ=ait_string)) then
  463. begin
  464. if not fisstring and
  465. (fvalues.count>0) then
  466. convert_to_string;
  467. fisstring:=true;
  468. case fvalues.count of
  469. 0: fvalues.add(val);
  470. 1:
  471. begin
  472. add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
  473. val.free
  474. end
  475. else
  476. internalerror(2014070104);
  477. end;
  478. end
  479. else
  480. fvalues.add(val);
  481. end;
  482. function tai_aggregatetypedconst.valuecount: longint;
  483. begin
  484. result:=fvalues.count;
  485. end;
  486. procedure tai_aggregatetypedconst.insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  487. begin
  488. fvalues.insert(pos,val);
  489. end;
  490. procedure tai_aggregatetypedconst.finish;
  491. begin
  492. if fisstring then
  493. begin
  494. { set the def: an array of char with the same length as the string
  495. data }
  496. if fvalues.count<>1 then
  497. internalerror(2014070105);
  498. tai_simpletypedconst(fvalues[0]).fdef:=
  499. getarraydef(cansichartype,
  500. tai_string(tai_simpletypedconst(fvalues[0]).val).len);
  501. end;
  502. end;
  503. destructor tai_aggregatetypedconst.destroy;
  504. begin
  505. fvalues.free;
  506. inherited destroy;
  507. end;
  508. {*****************************************************************************
  509. ttai_typedconstbuilder
  510. *****************************************************************************}
  511. function ttai_typedconstbuilder.getcurragginfo: taggregateinformation;
  512. begin
  513. if assigned(faggregateinformation) and
  514. (faggregateinformation.count>0) then
  515. result:=taggregateinformation(faggregateinformation[faggregateinformation.count-1])
  516. else
  517. result:=nil;
  518. end;
  519. procedure ttai_typedconstbuilder.set_next_field(AValue: tfieldvarsym);
  520. var
  521. info: taggregateinformation;
  522. begin
  523. info:=curagginfo;
  524. if not assigned(info) then
  525. internalerror(2014091206);
  526. info.nextfield:=AValue;
  527. end;
  528. procedure ttai_typedconstbuilder.pad_next_field(nextfielddef: tdef);
  529. var
  530. fillbytes: asizeint;
  531. begin
  532. fillbytes:=curagginfo.prepare_next_field(nextfielddef);
  533. while fillbytes>0 do
  534. begin
  535. do_emit_tai(tai_const.create_8bit(0),u8inttype);
  536. dec(fillbytes);
  537. end;
  538. end;
  539. function ttai_typedconstbuilder.aggregate_kind(def: tdef): ttypedconstkind;
  540. begin
  541. if (def.typ in [recorddef,filedef,variantdef]) or
  542. is_object(def) or
  543. ((def.typ=procvardef) and
  544. not tprocvardef(def).is_addressonly) then
  545. result:=tck_record
  546. else if ((def.typ=arraydef) and
  547. not is_dynamic_array(def)) or
  548. ((def.typ=setdef) and
  549. not is_smallset(def)) or
  550. is_shortstring(def) then
  551. result:=tck_array
  552. else
  553. result:=tck_simple;
  554. end;
  555. procedure ttai_typedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  556. var
  557. prelist: tasmlist;
  558. begin
  559. prelist:=tasmlist.create_without_marker;
  560. { only now add items based on the symbolname, because it may be
  561. modified by the "section" specifier in case of a typed constant }
  562. if tcalo_new_section in options then
  563. begin
  564. maybe_new_object_file(prelist);
  565. new_section(prelist,section,secname,const_align(alignment));
  566. end
  567. else
  568. prelist.concat(cai_align.Create(const_align(alignment)));
  569. if not(tcalo_is_lab in options) then
  570. if sym.bind=AB_GLOBAL then
  571. prelist.concat(tai_symbol.Create_Global(sym,0))
  572. else
  573. prelist.concat(tai_symbol.Create(sym,0))
  574. else
  575. prelist.concat(tai_label.Create(tasmlabel(sym)));
  576. { insert the symbol information before the data }
  577. fasmlist.insertlist(prelist);
  578. { end of the symbol }
  579. fasmlist.concat(tai_symbol_end.Createname(sym.name));
  580. { free the temporary list }
  581. prelist.free;
  582. end;
  583. procedure ttai_typedconstbuilder.do_emit_tai(p: tai; def: tdef);
  584. begin
  585. { by default we don't care about the type }
  586. fasmlist.concat(p);
  587. end;
  588. function ttai_typedconstbuilder.get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint; const options: ttcasmlistoptions): tasmlist;
  589. begin
  590. if not fasmlist_finalized then
  591. begin
  592. finalize_asmlist(sym,def,section,secname,alignment,options);
  593. fasmlist_finalized:=true;
  594. end;
  595. result:=fasmlist;
  596. end;
  597. class function ttai_typedconstbuilder.get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint;
  598. begin
  599. { darwin's linker does not support negative offsets }
  600. if not(target_info.system in systems_darwin) then
  601. result:=0
  602. else
  603. result:=get_string_header_size(typ,winlikewidestring);
  604. end;
  605. class function ttai_typedconstbuilder.get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  606. const
  607. ansistring_header_size =
  608. { encoding }
  609. 2 +
  610. { elesize }
  611. 2 +
  612. {$ifdef cpu64bitaddr}
  613. { alignment }
  614. 4 +
  615. {$endif cpu64bitaddr}
  616. { reference count }
  617. sizeof(pint) +
  618. { length }
  619. sizeof(pint);
  620. unicodestring_header_size = ansistring_header_size;
  621. begin
  622. case typ of
  623. st_ansistring:
  624. result:=ansistring_header_size;
  625. st_unicodestring:
  626. result:=unicodestring_header_size;
  627. st_widestring:
  628. if winlikewidestring then
  629. result:=0
  630. else
  631. result:=unicodestring_header_size;
  632. else
  633. result:=0;
  634. end;
  635. end;
  636. constructor ttai_typedconstbuilder.create;
  637. begin
  638. inherited create;
  639. fasmlist:=tasmlist.create_without_marker;
  640. { queue is empty }
  641. fqueue_offset:=low(fqueue_offset);
  642. end;
  643. destructor ttai_typedconstbuilder.destroy;
  644. begin
  645. { the queue should have been flushed if it was used }
  646. if fqueue_offset<>low(fqueue_offset) then
  647. internalerror(2014062901);
  648. faggregateinformation.free;
  649. fasmlist.free;
  650. inherited destroy;
  651. end;
  652. procedure ttai_typedconstbuilder.emit_tai(p: tai; def: tdef);
  653. var
  654. kind: ttypedconstkind;
  655. info: taggregateinformation;
  656. begin
  657. { these elements can be aggregates themselves, e.g. a shortstring can
  658. be emitted as a series of bytes and char arrays }
  659. kind:=aggregate_kind(def);
  660. info:=curagginfo;
  661. if (kind<>tck_simple) and
  662. (not assigned(info) or
  663. (info.typ<>kind)) then
  664. internalerror(2014091001);
  665. { if we're emitting a record, handle the padding bytes, and in case of
  666. an anonymous record also add the next field }
  667. if assigned(info) then
  668. begin
  669. if ((info.def.typ=recorddef) or
  670. is_object(info.def)) and
  671. { may add support for these later }
  672. not is_packed_record_or_object(info.def) then
  673. pad_next_field(def);
  674. end;
  675. { emit the data }
  676. do_emit_tai(p,def);
  677. end;
  678. procedure ttai_typedconstbuilder.emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef);
  679. begin
  680. { nothing special by default, since we don't care about the type }
  681. emit_tai(p,pvdef);
  682. end;
  683. function ttai_typedconstbuilder.emit_string_const_common(list: TAsmList; stringtype: tstringtype; len: asizeint; encoding: tstringencoding; out startlab: tasmlabel): tasmlabofs;
  684. var
  685. string_symofs: asizeint;
  686. charptrdef: tdef;
  687. elesize: word;
  688. begin
  689. current_asmdata.getdatalabel(result.lab);
  690. startlab:=result.lab;
  691. result.ofs:=0;
  692. { pack the data, so that we don't add unnecessary null bytes after the
  693. constant string }
  694. begin_anonymous_record('$'+get_dynstring_rec_name(stringtype,false,len),1);
  695. string_symofs:=get_string_symofs(stringtype,false);
  696. { encoding }
  697. emit_tai(tai_const.create_16bit(encoding),u16inttype);
  698. inc(result.ofs,2);
  699. { element size }
  700. case stringtype of
  701. st_ansistring:
  702. begin
  703. elesize:=1;
  704. charptrdef:=charpointertype;
  705. end;
  706. st_unicodestring:
  707. begin
  708. elesize:=2;
  709. charptrdef:=widecharpointertype;
  710. end
  711. else
  712. internalerror(2014080401);
  713. end;
  714. emit_tai(tai_const.create_16bit(elesize),u16inttype);
  715. inc(result.ofs,2);
  716. {$ifdef cpu64bitaddr}
  717. { dummy for alignment }
  718. emit_tai(tai_const.create_32bit(0),u32inttype);
  719. inc(result.ofs,4);
  720. {$endif cpu64bitaddr}
  721. emit_tai(tai_const.create_pint(-1),ptrsinttype);
  722. inc(result.ofs,sizeof(pint));
  723. emit_tai(tai_const.create_pint(len),ptrsinttype);
  724. inc(result.ofs,sizeof(pint));
  725. if string_symofs=0 then
  726. begin
  727. { results in slightly more efficient code }
  728. emit_tai(tai_label.create(result.lab),charptrdef);
  729. result.ofs:=0;
  730. current_asmdata.getdatalabel(startlab);
  731. end;
  732. { sanity check }
  733. if result.ofs<>string_symofs then
  734. internalerror(2012051701);
  735. end;
  736. procedure ttai_typedconstbuilder.begin_aggregate_internal(def: tdef; anonymous: boolean);
  737. var
  738. info: taggregateinformation;
  739. tck: ttypedconstkind;
  740. begin
  741. tck:=aggregate_kind(def);
  742. if tck=tck_simple then
  743. exit;
  744. if not assigned(faggregateinformation) then
  745. faggregateinformation:=tfpobjectlist.create
  746. { if we're starting an anonymous record, we can't align it yet because
  747. the alignment depends on the fields that will be added -> we'll do
  748. it at the end }
  749. else if not anonymous then
  750. begin
  751. { add padding if necessary, and update the current field/offset }
  752. info:=curagginfo;
  753. if is_record(curagginfo.def) or
  754. is_object(curagginfo.def) then
  755. pad_next_field(def);
  756. end
  757. { if this is the outer record, no padding is required; the alignment
  758. has to be specified explicitly in that case via get_final_asmlist() }
  759. else if assigned(curagginfo) and
  760. (curagginfo.def.typ=recorddef) then
  761. { mark where we'll have to insert the padding bytes at the end }
  762. mark_anon_aggregate_alignment;
  763. info:=caggregateinformation.create(def,aggregate_kind(def));
  764. faggregateinformation.add(info);
  765. end;
  766. procedure ttai_typedconstbuilder.end_aggregate_internal(def: tdef; anonymous: boolean);
  767. var
  768. info: taggregateinformation;
  769. fillbytes: asizeint;
  770. tck: ttypedconstkind;
  771. begin
  772. tck:=aggregate_kind(def);
  773. if tck=tck_simple then
  774. exit;
  775. info:=curagginfo;
  776. if not assigned(info) then
  777. internalerror(2014091002);
  778. if def<>info.def then
  779. internalerror(2014091205);
  780. { add tail padding if necessary }
  781. if (is_record(def) or
  782. is_object(def)) and
  783. not is_packed_record_or_object(def) then
  784. begin
  785. fillbytes:=def.size-info.curoffset;
  786. while fillbytes>0 do
  787. begin
  788. do_emit_tai(Tai_const.Create_8bit(0),u8inttype);
  789. dec(fillbytes)
  790. end;
  791. end;
  792. { pop and free the information }
  793. faggregateinformation.count:=faggregateinformation.count-1;
  794. info.free;
  795. end;
  796. class function ttai_typedconstbuilder.get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): string;
  797. begin
  798. case typ of
  799. st_ansistring:
  800. result:='ansistrrec';
  801. st_unicodestring,
  802. st_widestring:
  803. if (typ=st_unicodestring) or
  804. not winlike then
  805. result:='unicodestrrec'
  806. else
  807. result:='widestrrec';
  808. else
  809. internalerror(2014080402);
  810. end;
  811. result:=result+tostr(len);
  812. end;
  813. class function ttai_typedconstbuilder.emit_ansistring_const(list: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding; newsection: boolean): tasmlabofs;
  814. var
  815. s: PChar;
  816. startlab: tasmlabel;
  817. ansistrrecdef: trecorddef;
  818. datadef: tdef;
  819. datatcb: ttai_typedconstbuilder;
  820. options: ttcasmlistoptions;
  821. begin
  822. datatcb:=self.create;
  823. result:=datatcb.emit_string_const_common(list,st_ansistring,len,encoding,startlab);
  824. getmem(s,len+1);
  825. move(data^,s^,len);
  826. s[len]:=#0;
  827. { terminating zero included }
  828. datadef:=getarraydef(cansichartype,len+1);
  829. datatcb.maybe_begin_aggregate(datadef);
  830. datatcb.emit_tai(tai_string.create_pchar(s,len+1),datadef);
  831. datatcb.maybe_end_aggregate(datadef);
  832. ansistrrecdef:=datatcb.end_anonymous_record;
  833. options:=[tcalo_is_lab];
  834. if NewSection then
  835. include(options,tcalo_new_section);
  836. list.concatlist(datatcb.get_final_asmlist(startlab,ansistrrecdef,sec_rodata_norel,startlab.name,const_align(sizeof(pint)),options));
  837. datatcb.free;
  838. end;
  839. class function ttai_typedconstbuilder.emit_unicodestring_const(list: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  840. var
  841. i, strlength: longint;
  842. string_symofs: asizeint;
  843. startlab: tasmlabel;
  844. datadef: tdef;
  845. uniwidestrrecdef: trecorddef;
  846. datatcb: ttai_typedconstbuilder;
  847. begin
  848. datatcb:=self.create;
  849. strlength:=getlengthwidestring(pcompilerwidestring(data));
  850. if winlike then
  851. begin
  852. datatcb.begin_anonymous_record('$'+get_dynstring_rec_name(st_widestring,true,strlength),sizeof(pint));
  853. current_asmdata.getdatalabel(result.lab);
  854. datatcb.emit_tai(Tai_const.Create_32bit(strlength*cwidechartype.size),s32inttype);
  855. { can we optimise by placing the string constant label at the
  856. required offset? }
  857. string_symofs:=get_string_symofs(st_widestring,true);
  858. if string_symofs=0 then
  859. begin
  860. { yes }
  861. datatcb.emit_tai(Tai_label.Create(result.lab),widecharpointertype);
  862. { allocate a separate label for the start of the data }
  863. current_asmdata.getdatalabel(startlab);
  864. end;
  865. result.ofs:=string_symofs;
  866. end
  867. else
  868. begin
  869. result:=datatcb.emit_string_const_common(list,st_unicodestring,strlength,encoding,startlab);
  870. end;
  871. if cwidechartype.size = 2 then
  872. begin
  873. datadef:=getarraydef(cwidechartype,strlength+1);
  874. datatcb.maybe_begin_aggregate(datadef);
  875. for i:=0 to strlength-1 do
  876. datatcb.emit_tai(Tai_const.Create_16bit(pcompilerwidestring(data)^.data[i]),cwidechartype);
  877. { ending #0 }
  878. datatcb.emit_tai(Tai_const.Create_16bit(0),cwidechartype);
  879. datatcb.maybe_end_aggregate(datadef);
  880. uniwidestrrecdef:=datatcb.end_anonymous_record;
  881. end
  882. else
  883. { code generation for other sizes must be written }
  884. internalerror(200904271);
  885. list.concatlist(datatcb.get_final_asmlist(startlab,uniwidestrrecdef,sec_rodata_norel,startlab.name,const_align(sizeof(pint)),[tcalo_is_lab,tcalo_new_section]));
  886. datatcb.free;
  887. end;
  888. procedure ttai_typedconstbuilder.maybe_begin_aggregate(def: tdef);
  889. begin
  890. begin_aggregate_internal(def,false);
  891. end;
  892. procedure ttai_typedconstbuilder.maybe_end_aggregate(def: tdef);
  893. begin
  894. end_aggregate_internal(def,false);
  895. end;
  896. function ttai_typedconstbuilder.begin_anonymous_record(const optionalname: string; packrecords: shortint): trecorddef;
  897. var
  898. anonrecorddef: trecorddef;
  899. srsym: tsym;
  900. srsymtable: tsymtable;
  901. found: boolean;
  902. begin
  903. { if the name is specified, we create a typesym with that name in order
  904. to ensure we can find it again later with that name -> reuse here as
  905. well if possible (and that also avoids duplicate type name issues) }
  906. if optionalname<>'' then
  907. begin
  908. if optionalname[1]='$' then
  909. found:=searchsym_type(copy(optionalname,2,length(optionalname)),srsym,srsymtable)
  910. else
  911. found:=searchsym_type(optionalname,srsym,srsymtable);
  912. if found then
  913. begin
  914. if ttypesym(srsym).typedef.typ<>recorddef then
  915. internalerror(2014091207);
  916. result:=trecorddef(ttypesym(srsym).typedef);
  917. maybe_begin_aggregate(result);
  918. exit;
  919. end;
  920. end;
  921. { create skeleton def }
  922. anonrecorddef:=crecorddef.create_global_internal(optionalname,packrecords);
  923. { generic aggregate housekeeping }
  924. begin_aggregate_internal(anonrecorddef,true);
  925. { mark as anonymous record }
  926. curagginfo.anonrecord:=true;
  927. { in case a descendent wants to do something with the anonrecorddef too }
  928. result:=anonrecorddef;
  929. end;
  930. function ttai_typedconstbuilder.end_anonymous_record: trecorddef;
  931. var
  932. info: taggregateinformation;
  933. anonrecord: boolean;
  934. begin
  935. info:=curagginfo;
  936. if not assigned(info) or
  937. (info.def.typ<>recorddef) then
  938. internalerror(2014080201);
  939. result:=trecorddef(info.def);
  940. { make a copy, as we need it after info has been freed by
  941. maybe_end_aggregate(result) }
  942. anonrecord:=info.anonrecord;
  943. { finalise the record skeleton (all fields have been added already by
  944. emit_tai()) -- anonrecord may not be set in case we reused an earlier
  945. constructed def }
  946. if anonrecord then
  947. trecordsymtable(result.symtable).addalignmentpadding;
  948. end_aggregate_internal(result,true);
  949. if anonrecord and
  950. assigned(curagginfo) and
  951. (curagginfo.def.typ=recorddef) then
  952. insert_marked_aggregate_alignment(result);
  953. end;
  954. procedure ttai_typedconstbuilder.queue_init(todef: tdef);
  955. begin
  956. { nested call to init? }
  957. if fqueue_offset<>low(fqueue_offset) then
  958. internalerror(2014062101);
  959. fqueue_offset:=0;
  960. end;
  961. procedure ttai_typedconstbuilder.queue_vecn(def: tdef; const index: tconstexprint);
  962. var
  963. elelen,
  964. vecbase: asizeint;
  965. v: tconstexprint;
  966. begin
  967. elelen:=1;
  968. vecbase:=0;
  969. case def.typ of
  970. stringdef :
  971. ;
  972. arraydef :
  973. begin
  974. if not is_packed_array(def) then
  975. begin
  976. elelen:=tarraydef(def).elesize;
  977. vecbase:=tarraydef(def).lowrange;
  978. end
  979. else
  980. Message(parser_e_packed_dynamic_open_array);
  981. end;
  982. else
  983. Message(parser_e_illegal_expression);
  984. end;
  985. { Prevent overflow }
  986. v:=index-vecbase;
  987. if (v<int64(low(fqueue_offset))) or (v>int64(high(fqueue_offset))) then
  988. message3(type_e_range_check_error_bounds,tostr(v),tostr(low(fqueue_offset)),tostr(high(fqueue_offset)));
  989. if high(fqueue_offset)-fqueue_offset div elelen>v then
  990. inc(fqueue_offset,elelen*v.svalue)
  991. else
  992. message3(type_e_range_check_error_bounds,tostr(index),tostr(vecbase),tostr(high(fqueue_offset)-fqueue_offset div elelen+vecbase))
  993. end;
  994. procedure ttai_typedconstbuilder.queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym);
  995. begin
  996. inc(fqueue_offset,vs.fieldoffset);
  997. end;
  998. procedure ttai_typedconstbuilder.queue_typeconvn(fromdef, todef: tdef);
  999. begin
  1000. { do nothing }
  1001. end;
  1002. procedure ttai_typedconstbuilder.queue_addrn(fromdef, todef: tdef);
  1003. begin
  1004. { do nothing }
  1005. end;
  1006. procedure ttai_typedconstbuilder.queue_emit_proc(pd: tprocdef);
  1007. begin
  1008. emit_tai(Tai_const.Createname(pd.mangledname,fqueue_offset),pd.getcopyas(procvardef,pc_address_only));
  1009. fqueue_offset:=low(fqueue_offset);
  1010. end;
  1011. procedure ttai_typedconstbuilder.queue_emit_staticvar(vs: tstaticvarsym);
  1012. begin
  1013. { getpointerdef because we are emitting a pointer to the staticvarsym
  1014. data, not the data itself }
  1015. emit_tai(Tai_const.Createname(vs.mangledname,fqueue_offset),getpointerdef(vs.vardef));
  1016. fqueue_offset:=low(fqueue_offset);
  1017. end;
  1018. procedure ttai_typedconstbuilder.queue_emit_label(l: tlabelsym);
  1019. begin
  1020. emit_tai(Tai_const.Createname(l.mangledname,fqueue_offset),voidcodepointertype);
  1021. fqueue_offset:=low(fqueue_offset);
  1022. end;
  1023. procedure ttai_typedconstbuilder.queue_emit_const(cs: tconstsym);
  1024. begin
  1025. if cs.consttyp<>constresourcestring then
  1026. internalerror(2014062102);
  1027. if fqueue_offset<>0 then
  1028. internalerror(2014062103);
  1029. { warning: update if/when the type of resource strings changes }
  1030. emit_tai(Tai_const.Createname(make_mangledname('RESSTR',cs.owner,cs.name),AT_DATA,sizeof(pint)),cansistringtype);
  1031. fqueue_offset:=low(fqueue_offset);
  1032. end;
  1033. procedure ttai_typedconstbuilder.queue_emit_asmsym(sym: tasmsymbol; def: tdef);
  1034. begin
  1035. { getpointerdef, because "sym" represents the address of whatever the
  1036. data is }
  1037. def:=getpointerdef(def);
  1038. emit_tai(Tai_const.Create_sym_offset(sym,fqueue_offset),def);
  1039. fqueue_offset:=low(fqueue_offset);
  1040. end;
  1041. {****************************************************************************
  1042. tai_abstracttypedconst
  1043. ****************************************************************************}
  1044. class constructor ttai_lowleveltypedconstbuilder.classcreate;
  1045. begin
  1046. caggregateinformation:=tlowlevelaggregateinformation;
  1047. end;
  1048. procedure ttai_lowleveltypedconstbuilder.mark_anon_aggregate_alignment;
  1049. var
  1050. marker: tai_marker;
  1051. begin
  1052. marker:=tai_marker.Create(mark_position);
  1053. fasmlist.concat(marker);
  1054. tlowlevelaggregateinformation(curagginfo).anonrecmarker:=marker;
  1055. end;
  1056. procedure ttai_lowleveltypedconstbuilder.insert_marked_aggregate_alignment(def: tdef);
  1057. var
  1058. info: tlowlevelaggregateinformation;
  1059. fillbytes: asizeint;
  1060. begin
  1061. info:=tlowlevelaggregateinformation(curagginfo);
  1062. if not assigned(info.anonrecmarker) then
  1063. internalerror(2014091401);
  1064. fillbytes:=info.prepare_next_field(def);
  1065. while fillbytes>0 do
  1066. begin
  1067. fasmlist.insertafter(tai_const.create_8bit(0),info.anonrecmarker);
  1068. dec(fillbytes);
  1069. end;
  1070. fasmlist.remove(info.anonrecmarker);
  1071. info.anonrecmarker.free;
  1072. info.anonrecmarker:=nil;
  1073. end;
  1074. begin
  1075. ctai_typedconstbuilder:=ttai_lowleveltypedconstbuilder;
  1076. end.