aasmcnst.pas 40 KB

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