Record.h 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the main TableGen data structures, including the TableGen
  15. // types, values, and high-level data structures.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_TABLEGEN_RECORD_H
  19. #define LLVM_TABLEGEN_RECORD_H
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/DenseSet.h"
  23. #include "llvm/ADT/FoldingSet.h"
  24. #include "llvm/ADT/PointerIntPair.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/Support/Casting.h"
  29. #include "llvm/Support/ErrorHandling.h"
  30. #include "llvm/Support/SMLoc.h"
  31. #include "llvm/Support/Timer.h"
  32. #include "llvm/Support/TrailingObjects.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <cassert>
  35. #include <cstddef>
  36. #include <cstdint>
  37. #include <map>
  38. #include <memory>
  39. #include <optional>
  40. #include <string>
  41. #include <utility>
  42. #include <vector>
  43. namespace llvm {
  44. namespace detail {
  45. struct RecordKeeperImpl;
  46. } // namespace detail
  47. class ListRecTy;
  48. class Record;
  49. class RecordKeeper;
  50. class RecordVal;
  51. class Resolver;
  52. class StringInit;
  53. class TypedInit;
  54. //===----------------------------------------------------------------------===//
  55. // Type Classes
  56. //===----------------------------------------------------------------------===//
  57. class RecTy {
  58. public:
  59. /// Subclass discriminator (for dyn_cast<> et al.)
  60. enum RecTyKind {
  61. BitRecTyKind,
  62. BitsRecTyKind,
  63. IntRecTyKind,
  64. StringRecTyKind,
  65. ListRecTyKind,
  66. DagRecTyKind,
  67. RecordRecTyKind
  68. };
  69. private:
  70. RecTyKind Kind;
  71. /// The RecordKeeper that uniqued this Type.
  72. RecordKeeper &RK;
  73. /// ListRecTy of the list that has elements of this type.
  74. ListRecTy *ListTy = nullptr;
  75. public:
  76. RecTy(RecTyKind K, RecordKeeper &RK) : Kind(K), RK(RK) {}
  77. virtual ~RecTy() = default;
  78. RecTyKind getRecTyKind() const { return Kind; }
  79. /// Return the RecordKeeper that uniqued this Type.
  80. RecordKeeper &getRecordKeeper() const { return RK; }
  81. virtual std::string getAsString() const = 0;
  82. void print(raw_ostream &OS) const { OS << getAsString(); }
  83. void dump() const;
  84. /// Return true if all values of 'this' type can be converted to the specified
  85. /// type.
  86. virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
  87. /// Return true if 'this' type is equal to or a subtype of RHS. For example,
  88. /// a bit set is not an int, but they are convertible.
  89. virtual bool typeIsA(const RecTy *RHS) const;
  90. /// Returns the type representing list<thistype>.
  91. ListRecTy *getListTy();
  92. };
  93. inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
  94. Ty.print(OS);
  95. return OS;
  96. }
  97. /// 'bit' - Represent a single bit
  98. class BitRecTy : public RecTy {
  99. friend detail::RecordKeeperImpl;
  100. BitRecTy(RecordKeeper &RK) : RecTy(BitRecTyKind, RK) {}
  101. public:
  102. static bool classof(const RecTy *RT) {
  103. return RT->getRecTyKind() == BitRecTyKind;
  104. }
  105. static BitRecTy *get(RecordKeeper &RK);
  106. std::string getAsString() const override { return "bit"; }
  107. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  108. };
  109. /// 'bits<n>' - Represent a fixed number of bits
  110. class BitsRecTy : public RecTy {
  111. unsigned Size;
  112. explicit BitsRecTy(RecordKeeper &RK, unsigned Sz)
  113. : RecTy(BitsRecTyKind, RK), Size(Sz) {}
  114. public:
  115. static bool classof(const RecTy *RT) {
  116. return RT->getRecTyKind() == BitsRecTyKind;
  117. }
  118. static BitsRecTy *get(RecordKeeper &RK, unsigned Sz);
  119. unsigned getNumBits() const { return Size; }
  120. std::string getAsString() const override;
  121. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  122. bool typeIsA(const RecTy *RHS) const override;
  123. };
  124. /// 'int' - Represent an integer value of no particular size
  125. class IntRecTy : public RecTy {
  126. friend detail::RecordKeeperImpl;
  127. IntRecTy(RecordKeeper &RK) : RecTy(IntRecTyKind, RK) {}
  128. public:
  129. static bool classof(const RecTy *RT) {
  130. return RT->getRecTyKind() == IntRecTyKind;
  131. }
  132. static IntRecTy *get(RecordKeeper &RK);
  133. std::string getAsString() const override { return "int"; }
  134. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  135. };
  136. /// 'string' - Represent an string value
  137. class StringRecTy : public RecTy {
  138. friend detail::RecordKeeperImpl;
  139. StringRecTy(RecordKeeper &RK) : RecTy(StringRecTyKind, RK) {}
  140. public:
  141. static bool classof(const RecTy *RT) {
  142. return RT->getRecTyKind() == StringRecTyKind;
  143. }
  144. static StringRecTy *get(RecordKeeper &RK);
  145. std::string getAsString() const override;
  146. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  147. };
  148. /// 'list<Ty>' - Represent a list of element values, all of which must be of
  149. /// the specified type. The type is stored in ElementTy.
  150. class ListRecTy : public RecTy {
  151. friend ListRecTy *RecTy::getListTy();
  152. RecTy *ElementTy;
  153. explicit ListRecTy(RecTy *T)
  154. : RecTy(ListRecTyKind, T->getRecordKeeper()), ElementTy(T) {}
  155. public:
  156. static bool classof(const RecTy *RT) {
  157. return RT->getRecTyKind() == ListRecTyKind;
  158. }
  159. static ListRecTy *get(RecTy *T) { return T->getListTy(); }
  160. RecTy *getElementType() const { return ElementTy; }
  161. std::string getAsString() const override;
  162. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  163. bool typeIsA(const RecTy *RHS) const override;
  164. };
  165. /// 'dag' - Represent a dag fragment
  166. class DagRecTy : public RecTy {
  167. friend detail::RecordKeeperImpl;
  168. DagRecTy(RecordKeeper &RK) : RecTy(DagRecTyKind, RK) {}
  169. public:
  170. static bool classof(const RecTy *RT) {
  171. return RT->getRecTyKind() == DagRecTyKind;
  172. }
  173. static DagRecTy *get(RecordKeeper &RK);
  174. std::string getAsString() const override;
  175. };
  176. /// '[classname]' - Type of record values that have zero or more superclasses.
  177. ///
  178. /// The list of superclasses is non-redundant, i.e. only contains classes that
  179. /// are not the superclass of some other listed class.
  180. class RecordRecTy final : public RecTy, public FoldingSetNode,
  181. public TrailingObjects<RecordRecTy, Record *> {
  182. friend class Record;
  183. friend detail::RecordKeeperImpl;
  184. unsigned NumClasses;
  185. explicit RecordRecTy(RecordKeeper &RK, unsigned Num)
  186. : RecTy(RecordRecTyKind, RK), NumClasses(Num) {}
  187. public:
  188. RecordRecTy(const RecordRecTy &) = delete;
  189. RecordRecTy &operator=(const RecordRecTy &) = delete;
  190. // Do not use sized deallocation due to trailing objects.
  191. void operator delete(void *p) { ::operator delete(p); }
  192. static bool classof(const RecTy *RT) {
  193. return RT->getRecTyKind() == RecordRecTyKind;
  194. }
  195. /// Get the record type with the given non-redundant list of superclasses.
  196. static RecordRecTy *get(RecordKeeper &RK, ArrayRef<Record *> Classes);
  197. static RecordRecTy *get(Record *Class);
  198. void Profile(FoldingSetNodeID &ID) const;
  199. ArrayRef<Record *> getClasses() const {
  200. return ArrayRef(getTrailingObjects<Record *>(), NumClasses);
  201. }
  202. using const_record_iterator = Record * const *;
  203. const_record_iterator classes_begin() const { return getClasses().begin(); }
  204. const_record_iterator classes_end() const { return getClasses().end(); }
  205. std::string getAsString() const override;
  206. bool isSubClassOf(Record *Class) const;
  207. bool typeIsConvertibleTo(const RecTy *RHS) const override;
  208. bool typeIsA(const RecTy *RHS) const override;
  209. };
  210. /// Find a common type that T1 and T2 convert to.
  211. /// Return 0 if no such type exists.
  212. RecTy *resolveTypes(RecTy *T1, RecTy *T2);
  213. //===----------------------------------------------------------------------===//
  214. // Initializer Classes
  215. //===----------------------------------------------------------------------===//
  216. class Init {
  217. protected:
  218. /// Discriminator enum (for isa<>, dyn_cast<>, et al.)
  219. ///
  220. /// This enum is laid out by a preorder traversal of the inheritance
  221. /// hierarchy, and does not contain an entry for abstract classes, as per
  222. /// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
  223. ///
  224. /// We also explicitly include "first" and "last" values for each
  225. /// interior node of the inheritance tree, to make it easier to read the
  226. /// corresponding classof().
  227. ///
  228. /// We could pack these a bit tighter by not having the IK_FirstXXXInit
  229. /// and IK_LastXXXInit be their own values, but that would degrade
  230. /// readability for really no benefit.
  231. enum InitKind : uint8_t {
  232. IK_First, // unused; silence a spurious warning
  233. IK_FirstTypedInit,
  234. IK_BitInit,
  235. IK_BitsInit,
  236. IK_DagInit,
  237. IK_DefInit,
  238. IK_FieldInit,
  239. IK_IntInit,
  240. IK_ListInit,
  241. IK_FirstOpInit,
  242. IK_BinOpInit,
  243. IK_TernOpInit,
  244. IK_UnOpInit,
  245. IK_LastOpInit,
  246. IK_CondOpInit,
  247. IK_FoldOpInit,
  248. IK_IsAOpInit,
  249. IK_ExistsOpInit,
  250. IK_AnonymousNameInit,
  251. IK_StringInit,
  252. IK_VarInit,
  253. IK_VarListElementInit,
  254. IK_VarBitInit,
  255. IK_VarDefInit,
  256. IK_LastTypedInit,
  257. IK_UnsetInit
  258. };
  259. private:
  260. const InitKind Kind;
  261. protected:
  262. uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
  263. private:
  264. virtual void anchor();
  265. public:
  266. /// Get the kind (type) of the value.
  267. InitKind getKind() const { return Kind; }
  268. /// Get the record keeper that initialized this Init.
  269. RecordKeeper &getRecordKeeper() const;
  270. protected:
  271. explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
  272. public:
  273. Init(const Init &) = delete;
  274. Init &operator=(const Init &) = delete;
  275. virtual ~Init() = default;
  276. /// Is this a complete value with no unset (uninitialized) subvalues?
  277. virtual bool isComplete() const { return true; }
  278. /// Is this a concrete and fully resolved value without any references or
  279. /// stuck operations? Unset values are concrete.
  280. virtual bool isConcrete() const { return false; }
  281. /// Print this value.
  282. void print(raw_ostream &OS) const { OS << getAsString(); }
  283. /// Convert this value to a literal form.
  284. virtual std::string getAsString() const = 0;
  285. /// Convert this value to a literal form,
  286. /// without adding quotes around a string.
  287. virtual std::string getAsUnquotedString() const { return getAsString(); }
  288. /// Debugging method that may be called through a debugger; just
  289. /// invokes print on stderr.
  290. void dump() const;
  291. /// If this value is convertible to type \p Ty, return a value whose
  292. /// type is \p Ty, generating a !cast operation if required.
  293. /// Otherwise, return null.
  294. virtual Init *getCastTo(RecTy *Ty) const = 0;
  295. /// Convert to a value whose type is \p Ty, or return null if this
  296. /// is not possible. This can happen if the value's type is convertible
  297. /// to \p Ty, but there are unresolved references.
  298. virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
  299. /// This function is used to implement the bit range
  300. /// selection operator. Given a value, it selects the specified bits,
  301. /// returning them as a new \p Init of type \p bits. If it is not legal
  302. /// to use the bit selection operator on this value, null is returned.
  303. virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  304. return nullptr;
  305. }
  306. /// This function is used to implement the list slice
  307. /// selection operator. Given a value, it selects the specified list
  308. /// elements, returning them as a new \p Init of type \p list. If it
  309. /// is not legal to use the slice operator, null is returned.
  310. virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
  311. return nullptr;
  312. }
  313. /// This function is used to implement the FieldInit class.
  314. /// Implementors of this method should return the type of the named
  315. /// field if they are of type record.
  316. virtual RecTy *getFieldType(StringInit *FieldName) const {
  317. return nullptr;
  318. }
  319. /// This function is used by classes that refer to other
  320. /// variables which may not be defined at the time the expression is formed.
  321. /// If a value is set for the variable later, this method will be called on
  322. /// users of the value to allow the value to propagate out.
  323. virtual Init *resolveReferences(Resolver &R) const {
  324. return const_cast<Init *>(this);
  325. }
  326. /// Get the \p Init value of the specified bit.
  327. virtual Init *getBit(unsigned Bit) const = 0;
  328. };
  329. inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
  330. I.print(OS); return OS;
  331. }
  332. /// This is the common superclass of types that have a specific,
  333. /// explicit type, stored in ValueTy.
  334. class TypedInit : public Init {
  335. RecTy *ValueTy;
  336. protected:
  337. explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
  338. : Init(K, Opc), ValueTy(T) {}
  339. public:
  340. TypedInit(const TypedInit &) = delete;
  341. TypedInit &operator=(const TypedInit &) = delete;
  342. static bool classof(const Init *I) {
  343. return I->getKind() >= IK_FirstTypedInit &&
  344. I->getKind() <= IK_LastTypedInit;
  345. }
  346. /// Get the type of the Init as a RecTy.
  347. RecTy *getType() const { return ValueTy; }
  348. /// Get the record keeper that initialized this Init.
  349. RecordKeeper &getRecordKeeper() const { return ValueTy->getRecordKeeper(); }
  350. Init *getCastTo(RecTy *Ty) const override;
  351. Init *convertInitializerTo(RecTy *Ty) const override;
  352. Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
  353. Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
  354. /// This method is used to implement the FieldInit class.
  355. /// Implementors of this method should return the type of the named field if
  356. /// they are of type record.
  357. RecTy *getFieldType(StringInit *FieldName) const override;
  358. };
  359. /// '?' - Represents an uninitialized value.
  360. class UnsetInit : public Init {
  361. friend detail::RecordKeeperImpl;
  362. /// The record keeper that initialized this Init.
  363. RecordKeeper &RK;
  364. UnsetInit(RecordKeeper &RK) : Init(IK_UnsetInit), RK(RK) {}
  365. public:
  366. UnsetInit(const UnsetInit &) = delete;
  367. UnsetInit &operator=(const UnsetInit &) = delete;
  368. static bool classof(const Init *I) {
  369. return I->getKind() == IK_UnsetInit;
  370. }
  371. /// Get the singleton unset Init.
  372. static UnsetInit *get(RecordKeeper &RK);
  373. /// Get the record keeper that initialized this Init.
  374. RecordKeeper &getRecordKeeper() const { return RK; }
  375. Init *getCastTo(RecTy *Ty) const override;
  376. Init *convertInitializerTo(RecTy *Ty) const override;
  377. Init *getBit(unsigned Bit) const override {
  378. return const_cast<UnsetInit*>(this);
  379. }
  380. /// Is this a complete value with no unset (uninitialized) subvalues?
  381. bool isComplete() const override { return false; }
  382. bool isConcrete() const override { return true; }
  383. /// Get the string representation of the Init.
  384. std::string getAsString() const override { return "?"; }
  385. };
  386. /// 'true'/'false' - Represent a concrete initializer for a bit.
  387. class BitInit final : public TypedInit {
  388. friend detail::RecordKeeperImpl;
  389. bool Value;
  390. explicit BitInit(bool V, RecTy *T) : TypedInit(IK_BitInit, T), Value(V) {}
  391. public:
  392. BitInit(const BitInit &) = delete;
  393. BitInit &operator=(BitInit &) = delete;
  394. static bool classof(const Init *I) {
  395. return I->getKind() == IK_BitInit;
  396. }
  397. static BitInit *get(RecordKeeper &RK, bool V);
  398. bool getValue() const { return Value; }
  399. Init *convertInitializerTo(RecTy *Ty) const override;
  400. Init *getBit(unsigned Bit) const override {
  401. assert(Bit < 1 && "Bit index out of range!");
  402. return const_cast<BitInit*>(this);
  403. }
  404. bool isConcrete() const override { return true; }
  405. std::string getAsString() const override { return Value ? "1" : "0"; }
  406. };
  407. /// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
  408. /// It contains a vector of bits, whose size is determined by the type.
  409. class BitsInit final : public TypedInit, public FoldingSetNode,
  410. public TrailingObjects<BitsInit, Init *> {
  411. unsigned NumBits;
  412. BitsInit(RecordKeeper &RK, unsigned N)
  413. : TypedInit(IK_BitsInit, BitsRecTy::get(RK, N)), NumBits(N) {}
  414. public:
  415. BitsInit(const BitsInit &) = delete;
  416. BitsInit &operator=(const BitsInit &) = delete;
  417. // Do not use sized deallocation due to trailing objects.
  418. void operator delete(void *p) { ::operator delete(p); }
  419. static bool classof(const Init *I) {
  420. return I->getKind() == IK_BitsInit;
  421. }
  422. static BitsInit *get(RecordKeeper &RK, ArrayRef<Init *> Range);
  423. void Profile(FoldingSetNodeID &ID) const;
  424. unsigned getNumBits() const { return NumBits; }
  425. Init *convertInitializerTo(RecTy *Ty) const override;
  426. Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
  427. bool isComplete() const override {
  428. for (unsigned i = 0; i != getNumBits(); ++i)
  429. if (!getBit(i)->isComplete()) return false;
  430. return true;
  431. }
  432. bool allInComplete() const {
  433. for (unsigned i = 0; i != getNumBits(); ++i)
  434. if (getBit(i)->isComplete()) return false;
  435. return true;
  436. }
  437. bool isConcrete() const override;
  438. std::string getAsString() const override;
  439. Init *resolveReferences(Resolver &R) const override;
  440. Init *getBit(unsigned Bit) const override {
  441. assert(Bit < NumBits && "Bit index out of range!");
  442. return getTrailingObjects<Init *>()[Bit];
  443. }
  444. };
  445. /// '7' - Represent an initialization by a literal integer value.
  446. class IntInit : public TypedInit {
  447. int64_t Value;
  448. explicit IntInit(RecordKeeper &RK, int64_t V)
  449. : TypedInit(IK_IntInit, IntRecTy::get(RK)), Value(V) {}
  450. public:
  451. IntInit(const IntInit &) = delete;
  452. IntInit &operator=(const IntInit &) = delete;
  453. static bool classof(const Init *I) {
  454. return I->getKind() == IK_IntInit;
  455. }
  456. static IntInit *get(RecordKeeper &RK, int64_t V);
  457. int64_t getValue() const { return Value; }
  458. Init *convertInitializerTo(RecTy *Ty) const override;
  459. Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
  460. bool isConcrete() const override { return true; }
  461. std::string getAsString() const override;
  462. Init *getBit(unsigned Bit) const override {
  463. return BitInit::get(getRecordKeeper(), (Value & (1ULL << Bit)) != 0);
  464. }
  465. };
  466. /// "anonymous_n" - Represent an anonymous record name
  467. class AnonymousNameInit : public TypedInit {
  468. unsigned Value;
  469. explicit AnonymousNameInit(RecordKeeper &RK, unsigned V)
  470. : TypedInit(IK_AnonymousNameInit, StringRecTy::get(RK)), Value(V) {}
  471. public:
  472. AnonymousNameInit(const AnonymousNameInit &) = delete;
  473. AnonymousNameInit &operator=(const AnonymousNameInit &) = delete;
  474. static bool classof(const Init *I) {
  475. return I->getKind() == IK_AnonymousNameInit;
  476. }
  477. static AnonymousNameInit *get(RecordKeeper &RK, unsigned);
  478. unsigned getValue() const { return Value; }
  479. StringInit *getNameInit() const;
  480. std::string getAsString() const override;
  481. Init *resolveReferences(Resolver &R) const override;
  482. Init *getBit(unsigned Bit) const override {
  483. llvm_unreachable("Illegal bit reference off string");
  484. }
  485. };
  486. /// "foo" - Represent an initialization by a string value.
  487. class StringInit : public TypedInit {
  488. public:
  489. enum StringFormat {
  490. SF_String, // Format as "text"
  491. SF_Code, // Format as [{text}]
  492. };
  493. private:
  494. StringRef Value;
  495. StringFormat Format;
  496. explicit StringInit(RecordKeeper &RK, StringRef V, StringFormat Fmt)
  497. : TypedInit(IK_StringInit, StringRecTy::get(RK)), Value(V), Format(Fmt) {}
  498. public:
  499. StringInit(const StringInit &) = delete;
  500. StringInit &operator=(const StringInit &) = delete;
  501. static bool classof(const Init *I) {
  502. return I->getKind() == IK_StringInit;
  503. }
  504. static StringInit *get(RecordKeeper &RK, StringRef,
  505. StringFormat Fmt = SF_String);
  506. static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) {
  507. return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String;
  508. }
  509. StringRef getValue() const { return Value; }
  510. StringFormat getFormat() const { return Format; }
  511. bool hasCodeFormat() const { return Format == SF_Code; }
  512. Init *convertInitializerTo(RecTy *Ty) const override;
  513. bool isConcrete() const override { return true; }
  514. std::string getAsString() const override {
  515. if (Format == SF_String)
  516. return "\"" + Value.str() + "\"";
  517. else
  518. return "[{" + Value.str() + "}]";
  519. }
  520. std::string getAsUnquotedString() const override {
  521. return std::string(Value);
  522. }
  523. Init *getBit(unsigned Bit) const override {
  524. llvm_unreachable("Illegal bit reference off string");
  525. }
  526. };
  527. /// [AL, AH, CL] - Represent a list of defs
  528. ///
  529. class ListInit final : public TypedInit, public FoldingSetNode,
  530. public TrailingObjects<ListInit, Init *> {
  531. unsigned NumValues;
  532. public:
  533. using const_iterator = Init *const *;
  534. private:
  535. explicit ListInit(unsigned N, RecTy *EltTy)
  536. : TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
  537. public:
  538. ListInit(const ListInit &) = delete;
  539. ListInit &operator=(const ListInit &) = delete;
  540. // Do not use sized deallocation due to trailing objects.
  541. void operator delete(void *p) { ::operator delete(p); }
  542. static bool classof(const Init *I) {
  543. return I->getKind() == IK_ListInit;
  544. }
  545. static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
  546. void Profile(FoldingSetNodeID &ID) const;
  547. Init *getElement(unsigned i) const {
  548. assert(i < NumValues && "List element index out of range!");
  549. return getTrailingObjects<Init *>()[i];
  550. }
  551. RecTy *getElementType() const {
  552. return cast<ListRecTy>(getType())->getElementType();
  553. }
  554. Record *getElementAsRecord(unsigned i) const;
  555. Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
  556. Init *convertInitializerTo(RecTy *Ty) const override;
  557. /// This method is used by classes that refer to other
  558. /// variables which may not be defined at the time they expression is formed.
  559. /// If a value is set for the variable later, this method will be called on
  560. /// users of the value to allow the value to propagate out.
  561. ///
  562. Init *resolveReferences(Resolver &R) const override;
  563. bool isComplete() const override;
  564. bool isConcrete() const override;
  565. std::string getAsString() const override;
  566. ArrayRef<Init*> getValues() const {
  567. return ArrayRef(getTrailingObjects<Init *>(), NumValues);
  568. }
  569. const_iterator begin() const { return getTrailingObjects<Init *>(); }
  570. const_iterator end () const { return begin() + NumValues; }
  571. size_t size () const { return NumValues; }
  572. bool empty() const { return NumValues == 0; }
  573. Init *getBit(unsigned Bit) const override {
  574. llvm_unreachable("Illegal bit reference off list");
  575. }
  576. };
  577. /// Base class for operators
  578. ///
  579. class OpInit : public TypedInit {
  580. protected:
  581. explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
  582. : TypedInit(K, Type, Opc) {}
  583. public:
  584. OpInit(const OpInit &) = delete;
  585. OpInit &operator=(OpInit &) = delete;
  586. static bool classof(const Init *I) {
  587. return I->getKind() >= IK_FirstOpInit &&
  588. I->getKind() <= IK_LastOpInit;
  589. }
  590. // Clone - Clone this operator, replacing arguments with the new list
  591. virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
  592. virtual unsigned getNumOperands() const = 0;
  593. virtual Init *getOperand(unsigned i) const = 0;
  594. Init *getBit(unsigned Bit) const override;
  595. };
  596. /// !op (X) - Transform an init.
  597. ///
  598. class UnOpInit : public OpInit, public FoldingSetNode {
  599. public:
  600. enum UnaryOp : uint8_t { CAST, NOT, HEAD, TAIL, SIZE, EMPTY, GETDAGOP, LOG2 };
  601. private:
  602. Init *LHS;
  603. UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
  604. : OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
  605. public:
  606. UnOpInit(const UnOpInit &) = delete;
  607. UnOpInit &operator=(const UnOpInit &) = delete;
  608. static bool classof(const Init *I) {
  609. return I->getKind() == IK_UnOpInit;
  610. }
  611. static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
  612. void Profile(FoldingSetNodeID &ID) const;
  613. // Clone - Clone this operator, replacing arguments with the new list
  614. OpInit *clone(ArrayRef<Init *> Operands) const override {
  615. assert(Operands.size() == 1 &&
  616. "Wrong number of operands for unary operation");
  617. return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
  618. }
  619. unsigned getNumOperands() const override { return 1; }
  620. Init *getOperand(unsigned i) const override {
  621. assert(i == 0 && "Invalid operand id for unary operator");
  622. return getOperand();
  623. }
  624. UnaryOp getOpcode() const { return (UnaryOp)Opc; }
  625. Init *getOperand() const { return LHS; }
  626. // Fold - If possible, fold this to a simpler init. Return this if not
  627. // possible to fold.
  628. Init *Fold(Record *CurRec, bool IsFinal = false) const;
  629. Init *resolveReferences(Resolver &R) const override;
  630. std::string getAsString() const override;
  631. };
  632. /// !op (X, Y) - Combine two inits.
  633. class BinOpInit : public OpInit, public FoldingSetNode {
  634. public:
  635. enum BinaryOp : uint8_t {
  636. ADD,
  637. SUB,
  638. MUL,
  639. DIV,
  640. AND,
  641. OR,
  642. XOR,
  643. SHL,
  644. SRA,
  645. SRL,
  646. LISTCONCAT,
  647. LISTSPLAT,
  648. LISTREMOVE,
  649. STRCONCAT,
  650. INTERLEAVE,
  651. CONCAT,
  652. EQ,
  653. NE,
  654. LE,
  655. LT,
  656. GE,
  657. GT,
  658. SETDAGOP
  659. };
  660. private:
  661. Init *LHS, *RHS;
  662. BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
  663. OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
  664. public:
  665. BinOpInit(const BinOpInit &) = delete;
  666. BinOpInit &operator=(const BinOpInit &) = delete;
  667. static bool classof(const Init *I) {
  668. return I->getKind() == IK_BinOpInit;
  669. }
  670. static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
  671. RecTy *Type);
  672. static Init *getStrConcat(Init *lhs, Init *rhs);
  673. static Init *getListConcat(TypedInit *lhs, Init *rhs);
  674. void Profile(FoldingSetNodeID &ID) const;
  675. // Clone - Clone this operator, replacing arguments with the new list
  676. OpInit *clone(ArrayRef<Init *> Operands) const override {
  677. assert(Operands.size() == 2 &&
  678. "Wrong number of operands for binary operation");
  679. return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
  680. }
  681. unsigned getNumOperands() const override { return 2; }
  682. Init *getOperand(unsigned i) const override {
  683. switch (i) {
  684. default: llvm_unreachable("Invalid operand id for binary operator");
  685. case 0: return getLHS();
  686. case 1: return getRHS();
  687. }
  688. }
  689. BinaryOp getOpcode() const { return (BinaryOp)Opc; }
  690. Init *getLHS() const { return LHS; }
  691. Init *getRHS() const { return RHS; }
  692. std::optional<bool> CompareInit(unsigned Opc, Init *LHS, Init *RHS) const;
  693. // Fold - If possible, fold this to a simpler init. Return this if not
  694. // possible to fold.
  695. Init *Fold(Record *CurRec) const;
  696. Init *resolveReferences(Resolver &R) const override;
  697. std::string getAsString() const override;
  698. };
  699. /// !op (X, Y, Z) - Combine two inits.
  700. class TernOpInit : public OpInit, public FoldingSetNode {
  701. public:
  702. enum TernaryOp : uint8_t { SUBST, FOREACH, FILTER, IF, DAG, SUBSTR, FIND };
  703. private:
  704. Init *LHS, *MHS, *RHS;
  705. TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
  706. RecTy *Type) :
  707. OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
  708. public:
  709. TernOpInit(const TernOpInit &) = delete;
  710. TernOpInit &operator=(const TernOpInit &) = delete;
  711. static bool classof(const Init *I) {
  712. return I->getKind() == IK_TernOpInit;
  713. }
  714. static TernOpInit *get(TernaryOp opc, Init *lhs,
  715. Init *mhs, Init *rhs,
  716. RecTy *Type);
  717. void Profile(FoldingSetNodeID &ID) const;
  718. // Clone - Clone this operator, replacing arguments with the new list
  719. OpInit *clone(ArrayRef<Init *> Operands) const override {
  720. assert(Operands.size() == 3 &&
  721. "Wrong number of operands for ternary operation");
  722. return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
  723. getType());
  724. }
  725. unsigned getNumOperands() const override { return 3; }
  726. Init *getOperand(unsigned i) const override {
  727. switch (i) {
  728. default: llvm_unreachable("Invalid operand id for ternary operator");
  729. case 0: return getLHS();
  730. case 1: return getMHS();
  731. case 2: return getRHS();
  732. }
  733. }
  734. TernaryOp getOpcode() const { return (TernaryOp)Opc; }
  735. Init *getLHS() const { return LHS; }
  736. Init *getMHS() const { return MHS; }
  737. Init *getRHS() const { return RHS; }
  738. // Fold - If possible, fold this to a simpler init. Return this if not
  739. // possible to fold.
  740. Init *Fold(Record *CurRec) const;
  741. bool isComplete() const override {
  742. return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
  743. }
  744. Init *resolveReferences(Resolver &R) const override;
  745. std::string getAsString() const override;
  746. };
  747. /// !cond(condition_1: value1, ... , condition_n: value)
  748. /// Selects the first value for which condition is true.
  749. /// Otherwise reports an error.
  750. class CondOpInit final : public TypedInit, public FoldingSetNode,
  751. public TrailingObjects<CondOpInit, Init *> {
  752. unsigned NumConds;
  753. RecTy *ValType;
  754. CondOpInit(unsigned NC, RecTy *Type)
  755. : TypedInit(IK_CondOpInit, Type),
  756. NumConds(NC), ValType(Type) {}
  757. size_t numTrailingObjects(OverloadToken<Init *>) const {
  758. return 2*NumConds;
  759. }
  760. public:
  761. CondOpInit(const CondOpInit &) = delete;
  762. CondOpInit &operator=(const CondOpInit &) = delete;
  763. static bool classof(const Init *I) {
  764. return I->getKind() == IK_CondOpInit;
  765. }
  766. static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
  767. RecTy *Type);
  768. void Profile(FoldingSetNodeID &ID) const;
  769. RecTy *getValType() const { return ValType; }
  770. unsigned getNumConds() const { return NumConds; }
  771. Init *getCond(unsigned Num) const {
  772. assert(Num < NumConds && "Condition number out of range!");
  773. return getTrailingObjects<Init *>()[Num];
  774. }
  775. Init *getVal(unsigned Num) const {
  776. assert(Num < NumConds && "Val number out of range!");
  777. return getTrailingObjects<Init *>()[Num+NumConds];
  778. }
  779. ArrayRef<Init *> getConds() const {
  780. return ArrayRef(getTrailingObjects<Init *>(), NumConds);
  781. }
  782. ArrayRef<Init *> getVals() const {
  783. return ArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds);
  784. }
  785. Init *Fold(Record *CurRec) const;
  786. Init *resolveReferences(Resolver &R) const override;
  787. bool isConcrete() const override;
  788. bool isComplete() const override;
  789. std::string getAsString() const override;
  790. using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
  791. using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
  792. inline const_case_iterator arg_begin() const { return getConds().begin(); }
  793. inline const_case_iterator arg_end () const { return getConds().end(); }
  794. inline size_t case_size () const { return NumConds; }
  795. inline bool case_empty() const { return NumConds == 0; }
  796. inline const_val_iterator name_begin() const { return getVals().begin();}
  797. inline const_val_iterator name_end () const { return getVals().end(); }
  798. inline size_t val_size () const { return NumConds; }
  799. inline bool val_empty() const { return NumConds == 0; }
  800. Init *getBit(unsigned Bit) const override;
  801. };
  802. /// !foldl (a, b, expr, start, lst) - Fold over a list.
  803. class FoldOpInit : public TypedInit, public FoldingSetNode {
  804. private:
  805. Init *Start;
  806. Init *List;
  807. Init *A;
  808. Init *B;
  809. Init *Expr;
  810. FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
  811. : TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
  812. Expr(Expr) {}
  813. public:
  814. FoldOpInit(const FoldOpInit &) = delete;
  815. FoldOpInit &operator=(const FoldOpInit &) = delete;
  816. static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
  817. static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
  818. RecTy *Type);
  819. void Profile(FoldingSetNodeID &ID) const;
  820. // Fold - If possible, fold this to a simpler init. Return this if not
  821. // possible to fold.
  822. Init *Fold(Record *CurRec) const;
  823. bool isComplete() const override { return false; }
  824. Init *resolveReferences(Resolver &R) const override;
  825. Init *getBit(unsigned Bit) const override;
  826. std::string getAsString() const override;
  827. };
  828. /// !isa<type>(expr) - Dynamically determine the type of an expression.
  829. class IsAOpInit : public TypedInit, public FoldingSetNode {
  830. private:
  831. RecTy *CheckType;
  832. Init *Expr;
  833. IsAOpInit(RecTy *CheckType, Init *Expr)
  834. : TypedInit(IK_IsAOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
  835. CheckType(CheckType), Expr(Expr) {}
  836. public:
  837. IsAOpInit(const IsAOpInit &) = delete;
  838. IsAOpInit &operator=(const IsAOpInit &) = delete;
  839. static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
  840. static IsAOpInit *get(RecTy *CheckType, Init *Expr);
  841. void Profile(FoldingSetNodeID &ID) const;
  842. // Fold - If possible, fold this to a simpler init. Return this if not
  843. // possible to fold.
  844. Init *Fold() const;
  845. bool isComplete() const override { return false; }
  846. Init *resolveReferences(Resolver &R) const override;
  847. Init *getBit(unsigned Bit) const override;
  848. std::string getAsString() const override;
  849. };
  850. /// !exists<type>(expr) - Dynamically determine if a record of `type` named
  851. /// `expr` exists.
  852. class ExistsOpInit : public TypedInit, public FoldingSetNode {
  853. private:
  854. RecTy *CheckType;
  855. Init *Expr;
  856. ExistsOpInit(RecTy *CheckType, Init *Expr)
  857. : TypedInit(IK_ExistsOpInit, IntRecTy::get(CheckType->getRecordKeeper())),
  858. CheckType(CheckType), Expr(Expr) {}
  859. public:
  860. ExistsOpInit(const ExistsOpInit &) = delete;
  861. ExistsOpInit &operator=(const ExistsOpInit &) = delete;
  862. static bool classof(const Init *I) { return I->getKind() == IK_ExistsOpInit; }
  863. static ExistsOpInit *get(RecTy *CheckType, Init *Expr);
  864. void Profile(FoldingSetNodeID &ID) const;
  865. // Fold - If possible, fold this to a simpler init. Return this if not
  866. // possible to fold.
  867. Init *Fold(Record *CurRec, bool IsFinal = false) const;
  868. bool isComplete() const override { return false; }
  869. Init *resolveReferences(Resolver &R) const override;
  870. Init *getBit(unsigned Bit) const override;
  871. std::string getAsString() const override;
  872. };
  873. /// 'Opcode' - Represent a reference to an entire variable object.
  874. class VarInit : public TypedInit {
  875. Init *VarName;
  876. explicit VarInit(Init *VN, RecTy *T)
  877. : TypedInit(IK_VarInit, T), VarName(VN) {}
  878. public:
  879. VarInit(const VarInit &) = delete;
  880. VarInit &operator=(const VarInit &) = delete;
  881. static bool classof(const Init *I) {
  882. return I->getKind() == IK_VarInit;
  883. }
  884. static VarInit *get(StringRef VN, RecTy *T);
  885. static VarInit *get(Init *VN, RecTy *T);
  886. StringRef getName() const;
  887. Init *getNameInit() const { return VarName; }
  888. std::string getNameInitAsString() const {
  889. return getNameInit()->getAsUnquotedString();
  890. }
  891. /// This method is used by classes that refer to other
  892. /// variables which may not be defined at the time they expression is formed.
  893. /// If a value is set for the variable later, this method will be called on
  894. /// users of the value to allow the value to propagate out.
  895. ///
  896. Init *resolveReferences(Resolver &R) const override;
  897. Init *getBit(unsigned Bit) const override;
  898. std::string getAsString() const override { return std::string(getName()); }
  899. };
  900. /// Opcode{0} - Represent access to one bit of a variable or field.
  901. class VarBitInit final : public TypedInit {
  902. TypedInit *TI;
  903. unsigned Bit;
  904. VarBitInit(TypedInit *T, unsigned B)
  905. : TypedInit(IK_VarBitInit, BitRecTy::get(T->getRecordKeeper())), TI(T),
  906. Bit(B) {
  907. assert(T->getType() &&
  908. (isa<IntRecTy>(T->getType()) ||
  909. (isa<BitsRecTy>(T->getType()) &&
  910. cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
  911. "Illegal VarBitInit expression!");
  912. }
  913. public:
  914. VarBitInit(const VarBitInit &) = delete;
  915. VarBitInit &operator=(const VarBitInit &) = delete;
  916. static bool classof(const Init *I) {
  917. return I->getKind() == IK_VarBitInit;
  918. }
  919. static VarBitInit *get(TypedInit *T, unsigned B);
  920. Init *getBitVar() const { return TI; }
  921. unsigned getBitNum() const { return Bit; }
  922. std::string getAsString() const override;
  923. Init *resolveReferences(Resolver &R) const override;
  924. Init *getBit(unsigned B) const override {
  925. assert(B < 1 && "Bit index out of range!");
  926. return const_cast<VarBitInit*>(this);
  927. }
  928. };
  929. /// List[4] - Represent access to one element of a var or
  930. /// field.
  931. class VarListElementInit : public TypedInit {
  932. TypedInit *TI;
  933. unsigned Element;
  934. VarListElementInit(TypedInit *T, unsigned E)
  935. : TypedInit(IK_VarListElementInit,
  936. cast<ListRecTy>(T->getType())->getElementType()),
  937. TI(T), Element(E) {
  938. assert(T->getType() && isa<ListRecTy>(T->getType()) &&
  939. "Illegal VarBitInit expression!");
  940. }
  941. public:
  942. VarListElementInit(const VarListElementInit &) = delete;
  943. VarListElementInit &operator=(const VarListElementInit &) = delete;
  944. static bool classof(const Init *I) {
  945. return I->getKind() == IK_VarListElementInit;
  946. }
  947. static VarListElementInit *get(TypedInit *T, unsigned E);
  948. TypedInit *getVariable() const { return TI; }
  949. unsigned getElementNum() const { return Element; }
  950. std::string getAsString() const override;
  951. Init *resolveReferences(Resolver &R) const override;
  952. Init *getBit(unsigned Bit) const override;
  953. };
  954. /// AL - Represent a reference to a 'def' in the description
  955. class DefInit : public TypedInit {
  956. friend class Record;
  957. Record *Def;
  958. explicit DefInit(Record *D);
  959. public:
  960. DefInit(const DefInit &) = delete;
  961. DefInit &operator=(const DefInit &) = delete;
  962. static bool classof(const Init *I) {
  963. return I->getKind() == IK_DefInit;
  964. }
  965. static DefInit *get(Record*);
  966. Init *convertInitializerTo(RecTy *Ty) const override;
  967. Record *getDef() const { return Def; }
  968. //virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
  969. RecTy *getFieldType(StringInit *FieldName) const override;
  970. bool isConcrete() const override { return true; }
  971. std::string getAsString() const override;
  972. Init *getBit(unsigned Bit) const override {
  973. llvm_unreachable("Illegal bit reference off def");
  974. }
  975. };
  976. /// classname<targs...> - Represent an uninstantiated anonymous class
  977. /// instantiation.
  978. class VarDefInit final : public TypedInit, public FoldingSetNode,
  979. public TrailingObjects<VarDefInit, Init *> {
  980. Record *Class;
  981. DefInit *Def = nullptr; // after instantiation
  982. unsigned NumArgs;
  983. explicit VarDefInit(Record *Class, unsigned N);
  984. DefInit *instantiate();
  985. public:
  986. VarDefInit(const VarDefInit &) = delete;
  987. VarDefInit &operator=(const VarDefInit &) = delete;
  988. // Do not use sized deallocation due to trailing objects.
  989. void operator delete(void *p) { ::operator delete(p); }
  990. static bool classof(const Init *I) {
  991. return I->getKind() == IK_VarDefInit;
  992. }
  993. static VarDefInit *get(Record *Class, ArrayRef<Init *> Args);
  994. void Profile(FoldingSetNodeID &ID) const;
  995. Init *resolveReferences(Resolver &R) const override;
  996. Init *Fold() const;
  997. std::string getAsString() const override;
  998. Init *getArg(unsigned i) const {
  999. assert(i < NumArgs && "Argument index out of range!");
  1000. return getTrailingObjects<Init *>()[i];
  1001. }
  1002. using const_iterator = Init *const *;
  1003. const_iterator args_begin() const { return getTrailingObjects<Init *>(); }
  1004. const_iterator args_end () const { return args_begin() + NumArgs; }
  1005. size_t args_size () const { return NumArgs; }
  1006. bool args_empty() const { return NumArgs == 0; }
  1007. ArrayRef<Init *> args() const { return ArrayRef(args_begin(), NumArgs); }
  1008. Init *getBit(unsigned Bit) const override {
  1009. llvm_unreachable("Illegal bit reference off anonymous def");
  1010. }
  1011. };
  1012. /// X.Y - Represent a reference to a subfield of a variable
  1013. class FieldInit : public TypedInit {
  1014. Init *Rec; // Record we are referring to
  1015. StringInit *FieldName; // Field we are accessing
  1016. FieldInit(Init *R, StringInit *FN)
  1017. : TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
  1018. #ifndef NDEBUG
  1019. if (!getType()) {
  1020. llvm::errs() << "In Record = " << Rec->getAsString()
  1021. << ", got FieldName = " << *FieldName
  1022. << " with non-record type!\n";
  1023. llvm_unreachable("FieldInit with non-record type!");
  1024. }
  1025. #endif
  1026. }
  1027. public:
  1028. FieldInit(const FieldInit &) = delete;
  1029. FieldInit &operator=(const FieldInit &) = delete;
  1030. static bool classof(const Init *I) {
  1031. return I->getKind() == IK_FieldInit;
  1032. }
  1033. static FieldInit *get(Init *R, StringInit *FN);
  1034. Init *getRecord() const { return Rec; }
  1035. StringInit *getFieldName() const { return FieldName; }
  1036. Init *getBit(unsigned Bit) const override;
  1037. Init *resolveReferences(Resolver &R) const override;
  1038. Init *Fold(Record *CurRec) const;
  1039. bool isConcrete() const override;
  1040. std::string getAsString() const override {
  1041. return Rec->getAsString() + "." + FieldName->getValue().str();
  1042. }
  1043. };
  1044. /// (v a, b) - Represent a DAG tree value. DAG inits are required
  1045. /// to have at least one value then a (possibly empty) list of arguments. Each
  1046. /// argument can have a name associated with it.
  1047. class DagInit final : public TypedInit, public FoldingSetNode,
  1048. public TrailingObjects<DagInit, Init *, StringInit *> {
  1049. friend TrailingObjects;
  1050. Init *Val;
  1051. StringInit *ValName;
  1052. unsigned NumArgs;
  1053. unsigned NumArgNames;
  1054. DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
  1055. : TypedInit(IK_DagInit, DagRecTy::get(V->getRecordKeeper())), Val(V),
  1056. ValName(VN), NumArgs(NumArgs), NumArgNames(NumArgNames) {}
  1057. size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
  1058. public:
  1059. DagInit(const DagInit &) = delete;
  1060. DagInit &operator=(const DagInit &) = delete;
  1061. static bool classof(const Init *I) {
  1062. return I->getKind() == IK_DagInit;
  1063. }
  1064. static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
  1065. ArrayRef<StringInit*> NameRange);
  1066. static DagInit *get(Init *V, StringInit *VN,
  1067. ArrayRef<std::pair<Init*, StringInit*>> Args);
  1068. void Profile(FoldingSetNodeID &ID) const;
  1069. Init *getOperator() const { return Val; }
  1070. Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
  1071. StringInit *getName() const { return ValName; }
  1072. StringRef getNameStr() const {
  1073. return ValName ? ValName->getValue() : StringRef();
  1074. }
  1075. unsigned getNumArgs() const { return NumArgs; }
  1076. Init *getArg(unsigned Num) const {
  1077. assert(Num < NumArgs && "Arg number out of range!");
  1078. return getTrailingObjects<Init *>()[Num];
  1079. }
  1080. StringInit *getArgName(unsigned Num) const {
  1081. assert(Num < NumArgNames && "Arg number out of range!");
  1082. return getTrailingObjects<StringInit *>()[Num];
  1083. }
  1084. StringRef getArgNameStr(unsigned Num) const {
  1085. StringInit *Init = getArgName(Num);
  1086. return Init ? Init->getValue() : StringRef();
  1087. }
  1088. ArrayRef<Init *> getArgs() const {
  1089. return ArrayRef(getTrailingObjects<Init *>(), NumArgs);
  1090. }
  1091. ArrayRef<StringInit *> getArgNames() const {
  1092. return ArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
  1093. }
  1094. Init *resolveReferences(Resolver &R) const override;
  1095. bool isConcrete() const override;
  1096. std::string getAsString() const override;
  1097. using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
  1098. using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
  1099. inline const_arg_iterator arg_begin() const { return getArgs().begin(); }
  1100. inline const_arg_iterator arg_end () const { return getArgs().end(); }
  1101. inline size_t arg_size () const { return NumArgs; }
  1102. inline bool arg_empty() const { return NumArgs == 0; }
  1103. inline const_name_iterator name_begin() const { return getArgNames().begin();}
  1104. inline const_name_iterator name_end () const { return getArgNames().end(); }
  1105. inline size_t name_size () const { return NumArgNames; }
  1106. inline bool name_empty() const { return NumArgNames == 0; }
  1107. Init *getBit(unsigned Bit) const override {
  1108. llvm_unreachable("Illegal bit reference off dag");
  1109. }
  1110. };
  1111. //===----------------------------------------------------------------------===//
  1112. // High-Level Classes
  1113. //===----------------------------------------------------------------------===//
  1114. /// This class represents a field in a record, including its name, type,
  1115. /// value, and source location.
  1116. class RecordVal {
  1117. friend class Record;
  1118. public:
  1119. enum FieldKind {
  1120. FK_Normal, // A normal record field.
  1121. FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword).
  1122. FK_TemplateArg, // A template argument.
  1123. };
  1124. private:
  1125. Init *Name;
  1126. SMLoc Loc; // Source location of definition of name.
  1127. PointerIntPair<RecTy *, 2, FieldKind> TyAndKind;
  1128. Init *Value;
  1129. bool IsUsed = false;
  1130. /// Reference locations to this record value.
  1131. SmallVector<SMRange> ReferenceLocs;
  1132. public:
  1133. RecordVal(Init *N, RecTy *T, FieldKind K);
  1134. RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K);
  1135. /// Get the record keeper used to unique this value.
  1136. RecordKeeper &getRecordKeeper() const { return Name->getRecordKeeper(); }
  1137. /// Get the name of the field as a StringRef.
  1138. StringRef getName() const;
  1139. /// Get the name of the field as an Init.
  1140. Init *getNameInit() const { return Name; }
  1141. /// Get the name of the field as a std::string.
  1142. std::string getNameInitAsString() const {
  1143. return getNameInit()->getAsUnquotedString();
  1144. }
  1145. /// Get the source location of the point where the field was defined.
  1146. const SMLoc &getLoc() const { return Loc; }
  1147. /// Is this a field where nonconcrete values are okay?
  1148. bool isNonconcreteOK() const {
  1149. return TyAndKind.getInt() == FK_NonconcreteOK;
  1150. }
  1151. /// Is this a template argument?
  1152. bool isTemplateArg() const {
  1153. return TyAndKind.getInt() == FK_TemplateArg;
  1154. }
  1155. /// Get the type of the field value as a RecTy.
  1156. RecTy *getType() const { return TyAndKind.getPointer(); }
  1157. /// Get the type of the field for printing purposes.
  1158. std::string getPrintType() const;
  1159. /// Get the value of the field as an Init.
  1160. Init *getValue() const { return Value; }
  1161. /// Set the value of the field from an Init.
  1162. bool setValue(Init *V);
  1163. /// Set the value and source location of the field.
  1164. bool setValue(Init *V, SMLoc NewLoc);
  1165. /// Add a reference to this record value.
  1166. void addReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); }
  1167. /// Return the references of this record value.
  1168. ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; }
  1169. /// Whether this value is used. Useful for reporting warnings, for example
  1170. /// when a template argument is unused.
  1171. void setUsed(bool Used) { IsUsed = Used; }
  1172. bool isUsed() const { return IsUsed; }
  1173. void dump() const;
  1174. /// Print the value to an output stream, possibly with a semicolon.
  1175. void print(raw_ostream &OS, bool PrintSem = true) const;
  1176. };
  1177. inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
  1178. RV.print(OS << " ");
  1179. return OS;
  1180. }
  1181. class Record {
  1182. public:
  1183. struct AssertionInfo {
  1184. SMLoc Loc;
  1185. Init *Condition;
  1186. Init *Message;
  1187. // User-defined constructor to support std::make_unique(). It can be
  1188. // removed in C++20 when braced initialization is supported.
  1189. AssertionInfo(SMLoc Loc, Init *Condition, Init *Message)
  1190. : Loc(Loc), Condition(Condition), Message(Message) {}
  1191. };
  1192. private:
  1193. Init *Name;
  1194. // Location where record was instantiated, followed by the location of
  1195. // multiclass prototypes used, and finally by the locations of references to
  1196. // this record.
  1197. SmallVector<SMLoc, 4> Locs;
  1198. SmallVector<SMLoc, 0> ForwardDeclarationLocs;
  1199. SmallVector<SMRange, 0> ReferenceLocs;
  1200. SmallVector<Init *, 0> TemplateArgs;
  1201. SmallVector<RecordVal, 0> Values;
  1202. SmallVector<AssertionInfo, 0> Assertions;
  1203. // All superclasses in the inheritance forest in post-order (yes, it
  1204. // must be a forest; diamond-shaped inheritance is not allowed).
  1205. SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
  1206. // Tracks Record instances. Not owned by Record.
  1207. RecordKeeper &TrackedRecords;
  1208. // The DefInit corresponding to this record.
  1209. DefInit *CorrespondingDefInit = nullptr;
  1210. // Unique record ID.
  1211. unsigned ID;
  1212. bool IsAnonymous;
  1213. bool IsClass;
  1214. void checkName();
  1215. public:
  1216. // Constructs a record.
  1217. explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
  1218. bool Anonymous = false, bool Class = false)
  1219. : Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
  1220. ID(getNewUID(N->getRecordKeeper())), IsAnonymous(Anonymous),
  1221. IsClass(Class) {
  1222. checkName();
  1223. }
  1224. explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
  1225. bool Class = false)
  1226. : Record(StringInit::get(records, N), locs, records, false, Class) {}
  1227. // When copy-constructing a Record, we must still guarantee a globally unique
  1228. // ID number. Don't copy CorrespondingDefInit either, since it's owned by the
  1229. // original record. All other fields can be copied normally.
  1230. Record(const Record &O)
  1231. : Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
  1232. Values(O.Values), Assertions(O.Assertions),
  1233. SuperClasses(O.SuperClasses), TrackedRecords(O.TrackedRecords),
  1234. ID(getNewUID(O.getRecords())), IsAnonymous(O.IsAnonymous),
  1235. IsClass(O.IsClass) {}
  1236. static unsigned getNewUID(RecordKeeper &RK);
  1237. unsigned getID() const { return ID; }
  1238. StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
  1239. Init *getNameInit() const {
  1240. return Name;
  1241. }
  1242. std::string getNameInitAsString() const {
  1243. return getNameInit()->getAsUnquotedString();
  1244. }
  1245. void setName(Init *Name); // Also updates RecordKeeper.
  1246. ArrayRef<SMLoc> getLoc() const { return Locs; }
  1247. void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
  1248. ArrayRef<SMLoc> getForwardDeclarationLocs() const {
  1249. return ForwardDeclarationLocs;
  1250. }
  1251. /// Add a reference to this record value.
  1252. void appendReferenceLoc(SMRange Loc) { ReferenceLocs.push_back(Loc); }
  1253. /// Return the references of this record value.
  1254. ArrayRef<SMRange> getReferenceLocs() const { return ReferenceLocs; }
  1255. // Update a class location when encountering a (re-)definition.
  1256. void updateClassLoc(SMLoc Loc);
  1257. // Make the type that this record should have based on its superclasses.
  1258. RecordRecTy *getType();
  1259. /// get the corresponding DefInit.
  1260. DefInit *getDefInit();
  1261. bool isClass() const { return IsClass; }
  1262. ArrayRef<Init *> getTemplateArgs() const {
  1263. return TemplateArgs;
  1264. }
  1265. ArrayRef<RecordVal> getValues() const { return Values; }
  1266. ArrayRef<AssertionInfo> getAssertions() const { return Assertions; }
  1267. ArrayRef<std::pair<Record *, SMRange>> getSuperClasses() const {
  1268. return SuperClasses;
  1269. }
  1270. /// Determine whether this record has the specified direct superclass.
  1271. bool hasDirectSuperClass(const Record *SuperClass) const;
  1272. /// Append the direct superclasses of this record to Classes.
  1273. void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
  1274. bool isTemplateArg(Init *Name) const {
  1275. return llvm::is_contained(TemplateArgs, Name);
  1276. }
  1277. const RecordVal *getValue(const Init *Name) const {
  1278. for (const RecordVal &Val : Values)
  1279. if (Val.Name == Name) return &Val;
  1280. return nullptr;
  1281. }
  1282. const RecordVal *getValue(StringRef Name) const {
  1283. return getValue(StringInit::get(getRecords(), Name));
  1284. }
  1285. RecordVal *getValue(const Init *Name) {
  1286. return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
  1287. }
  1288. RecordVal *getValue(StringRef Name) {
  1289. return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
  1290. }
  1291. void addTemplateArg(Init *Name) {
  1292. assert(!isTemplateArg(Name) && "Template arg already defined!");
  1293. TemplateArgs.push_back(Name);
  1294. }
  1295. void addValue(const RecordVal &RV) {
  1296. assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
  1297. Values.push_back(RV);
  1298. }
  1299. void removeValue(Init *Name) {
  1300. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  1301. if (Values[i].getNameInit() == Name) {
  1302. Values.erase(Values.begin()+i);
  1303. return;
  1304. }
  1305. llvm_unreachable("Cannot remove an entry that does not exist!");
  1306. }
  1307. void removeValue(StringRef Name) {
  1308. removeValue(StringInit::get(getRecords(), Name));
  1309. }
  1310. void addAssertion(SMLoc Loc, Init *Condition, Init *Message) {
  1311. Assertions.push_back(AssertionInfo(Loc, Condition, Message));
  1312. }
  1313. void appendAssertions(const Record *Rec) {
  1314. Assertions.append(Rec->Assertions);
  1315. }
  1316. void checkRecordAssertions();
  1317. void checkUnusedTemplateArgs();
  1318. bool isSubClassOf(const Record *R) const {
  1319. for (const auto &SCPair : SuperClasses)
  1320. if (SCPair.first == R)
  1321. return true;
  1322. return false;
  1323. }
  1324. bool isSubClassOf(StringRef Name) const {
  1325. for (const auto &SCPair : SuperClasses) {
  1326. if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
  1327. if (SI->getValue() == Name)
  1328. return true;
  1329. } else if (SCPair.first->getNameInitAsString() == Name) {
  1330. return true;
  1331. }
  1332. }
  1333. return false;
  1334. }
  1335. void addSuperClass(Record *R, SMRange Range) {
  1336. assert(!CorrespondingDefInit &&
  1337. "changing type of record after it has been referenced");
  1338. assert(!isSubClassOf(R) && "Already subclassing record!");
  1339. SuperClasses.push_back(std::make_pair(R, Range));
  1340. }
  1341. /// If there are any field references that refer to fields that have been
  1342. /// filled in, we can propagate the values now.
  1343. ///
  1344. /// This is a final resolve: any error messages, e.g. due to undefined !cast
  1345. /// references, are generated now.
  1346. void resolveReferences(Init *NewName = nullptr);
  1347. /// Apply the resolver to the name of the record as well as to the
  1348. /// initializers of all fields of the record except SkipVal.
  1349. ///
  1350. /// The resolver should not resolve any of the fields itself, to avoid
  1351. /// recursion / infinite loops.
  1352. void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
  1353. RecordKeeper &getRecords() const {
  1354. return TrackedRecords;
  1355. }
  1356. bool isAnonymous() const {
  1357. return IsAnonymous;
  1358. }
  1359. void dump() const;
  1360. //===--------------------------------------------------------------------===//
  1361. // High-level methods useful to tablegen back-ends
  1362. //
  1363. /// Return the source location for the named field.
  1364. SMLoc getFieldLoc(StringRef FieldName) const;
  1365. /// Return the initializer for a value with the specified name, or throw an
  1366. /// exception if the field does not exist.
  1367. Init *getValueInit(StringRef FieldName) const;
  1368. /// Return true if the named field is unset.
  1369. bool isValueUnset(StringRef FieldName) const {
  1370. return isa<UnsetInit>(getValueInit(FieldName));
  1371. }
  1372. /// This method looks up the specified field and returns its value as a
  1373. /// string, throwing an exception if the field does not exist or if the value
  1374. /// is not a string.
  1375. StringRef getValueAsString(StringRef FieldName) const;
  1376. /// This method looks up the specified field and returns its value as a
  1377. /// string, throwing an exception if the value is not a string and
  1378. /// llvm::Optional() if the field does not exist.
  1379. std::optional<StringRef> getValueAsOptionalString(StringRef FieldName) const;
  1380. /// This method looks up the specified field and returns its value as a
  1381. /// BitsInit, throwing an exception if the field does not exist or if the
  1382. /// value is not the right type.
  1383. BitsInit *getValueAsBitsInit(StringRef FieldName) const;
  1384. /// This method looks up the specified field and returns its value as a
  1385. /// ListInit, throwing an exception if the field does not exist or if the
  1386. /// value is not the right type.
  1387. ListInit *getValueAsListInit(StringRef FieldName) const;
  1388. /// This method looks up the specified field and returns its value as a
  1389. /// vector of records, throwing an exception if the field does not exist or
  1390. /// if the value is not the right type.
  1391. std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
  1392. /// This method looks up the specified field and returns its value as a
  1393. /// vector of integers, throwing an exception if the field does not exist or
  1394. /// if the value is not the right type.
  1395. std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
  1396. /// This method looks up the specified field and returns its value as a
  1397. /// vector of strings, throwing an exception if the field does not exist or
  1398. /// if the value is not the right type.
  1399. std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
  1400. /// This method looks up the specified field and returns its value as a
  1401. /// Record, throwing an exception if the field does not exist or if the value
  1402. /// is not the right type.
  1403. Record *getValueAsDef(StringRef FieldName) const;
  1404. /// This method looks up the specified field and returns its value as a
  1405. /// Record, returning null if the field exists but is "uninitialized" (i.e.
  1406. /// set to `?`), and throwing an exception if the field does not exist or if
  1407. /// its value is not the right type.
  1408. Record *getValueAsOptionalDef(StringRef FieldName) const;
  1409. /// This method looks up the specified field and returns its value as a bit,
  1410. /// throwing an exception if the field does not exist or if the value is not
  1411. /// the right type.
  1412. bool getValueAsBit(StringRef FieldName) const;
  1413. /// This method looks up the specified field and returns its value as a bit.
  1414. /// If the field is unset, sets Unset to true and returns false.
  1415. bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
  1416. /// This method looks up the specified field and returns its value as an
  1417. /// int64_t, throwing an exception if the field does not exist or if the
  1418. /// value is not the right type.
  1419. int64_t getValueAsInt(StringRef FieldName) const;
  1420. /// This method looks up the specified field and returns its value as an Dag,
  1421. /// throwing an exception if the field does not exist or if the value is not
  1422. /// the right type.
  1423. DagInit *getValueAsDag(StringRef FieldName) const;
  1424. };
  1425. raw_ostream &operator<<(raw_ostream &OS, const Record &R);
  1426. class RecordKeeper {
  1427. using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
  1428. using GlobalMap = std::map<std::string, Init *, std::less<>>;
  1429. public:
  1430. RecordKeeper();
  1431. ~RecordKeeper();
  1432. /// Return the internal implementation of the RecordKeeper.
  1433. detail::RecordKeeperImpl &getImpl() { return *Impl; }
  1434. /// Get the main TableGen input file's name.
  1435. const std::string getInputFilename() const { return InputFilename; }
  1436. /// Get the map of classes.
  1437. const RecordMap &getClasses() const { return Classes; }
  1438. /// Get the map of records (defs).
  1439. const RecordMap &getDefs() const { return Defs; }
  1440. /// Get the map of global variables.
  1441. const GlobalMap &getGlobals() const { return ExtraGlobals; }
  1442. /// Get the class with the specified name.
  1443. Record *getClass(StringRef Name) const {
  1444. auto I = Classes.find(Name);
  1445. return I == Classes.end() ? nullptr : I->second.get();
  1446. }
  1447. /// Get the concrete record with the specified name.
  1448. Record *getDef(StringRef Name) const {
  1449. auto I = Defs.find(Name);
  1450. return I == Defs.end() ? nullptr : I->second.get();
  1451. }
  1452. /// Get the \p Init value of the specified global variable.
  1453. Init *getGlobal(StringRef Name) const {
  1454. if (Record *R = getDef(Name))
  1455. return R->getDefInit();
  1456. auto It = ExtraGlobals.find(Name);
  1457. return It == ExtraGlobals.end() ? nullptr : It->second;
  1458. }
  1459. void saveInputFilename(std::string Filename) {
  1460. InputFilename = Filename;
  1461. }
  1462. void addClass(std::unique_ptr<Record> R) {
  1463. bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
  1464. std::move(R))).second;
  1465. (void)Ins;
  1466. assert(Ins && "Class already exists");
  1467. }
  1468. void addDef(std::unique_ptr<Record> R) {
  1469. bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
  1470. std::move(R))).second;
  1471. (void)Ins;
  1472. assert(Ins && "Record already exists");
  1473. }
  1474. void addExtraGlobal(StringRef Name, Init *I) {
  1475. bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
  1476. (void)Ins;
  1477. assert(!getDef(Name));
  1478. assert(Ins && "Global already exists");
  1479. }
  1480. Init *getNewAnonymousName();
  1481. /// Start phase timing; called if the --time-phases option is specified.
  1482. void startPhaseTiming() {
  1483. TimingGroup = new TimerGroup("TableGen", "TableGen Phase Timing");
  1484. }
  1485. /// Start timing a phase. Automatically stops any previous phase timer.
  1486. void startTimer(StringRef Name);
  1487. /// Stop timing a phase.
  1488. void stopTimer();
  1489. /// Start timing the overall backend. If the backend itself starts a timer,
  1490. /// then this timer is cleared.
  1491. void startBackendTimer(StringRef Name);
  1492. /// Stop timing the overall backend.
  1493. void stopBackendTimer();
  1494. /// Stop phase timing and print the report.
  1495. void stopPhaseTiming() {
  1496. if (TimingGroup)
  1497. delete TimingGroup;
  1498. }
  1499. //===--------------------------------------------------------------------===//
  1500. // High-level helper methods, useful for tablegen backends.
  1501. /// Get all the concrete records that inherit from the one specified
  1502. /// class. The class must be defined.
  1503. std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
  1504. /// Get all the concrete records that inherit from all the specified
  1505. /// classes. The classes must be defined.
  1506. std::vector<Record *> getAllDerivedDefinitions(
  1507. ArrayRef<StringRef> ClassNames) const;
  1508. /// Get all the concrete records that inherit from specified class, if the
  1509. /// class is defined. Returns an empty vector if the class is not defined.
  1510. std::vector<Record *>
  1511. getAllDerivedDefinitionsIfDefined(StringRef ClassName) const;
  1512. void dump() const;
  1513. private:
  1514. RecordKeeper(RecordKeeper &&) = delete;
  1515. RecordKeeper(const RecordKeeper &) = delete;
  1516. RecordKeeper &operator=(RecordKeeper &&) = delete;
  1517. RecordKeeper &operator=(const RecordKeeper &) = delete;
  1518. std::string InputFilename;
  1519. RecordMap Classes, Defs;
  1520. mutable StringMap<std::vector<Record *>> ClassRecordsMap;
  1521. GlobalMap ExtraGlobals;
  1522. // These members are for the phase timing feature. We need a timer group,
  1523. // the last timer started, and a flag to say whether the last timer
  1524. // is the special "backend overall timer."
  1525. TimerGroup *TimingGroup = nullptr;
  1526. Timer *LastTimer = nullptr;
  1527. bool BackendTimer = false;
  1528. /// The internal uniquer implementation of the RecordKeeper.
  1529. std::unique_ptr<detail::RecordKeeperImpl> Impl;
  1530. };
  1531. /// Sorting predicate to sort record pointers by name.
  1532. struct LessRecord {
  1533. bool operator()(const Record *Rec1, const Record *Rec2) const {
  1534. return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
  1535. }
  1536. };
  1537. /// Sorting predicate to sort record pointers by their
  1538. /// unique ID. If you just need a deterministic order, use this, since it
  1539. /// just compares two `unsigned`; the other sorting predicates require
  1540. /// string manipulation.
  1541. struct LessRecordByID {
  1542. bool operator()(const Record *LHS, const Record *RHS) const {
  1543. return LHS->getID() < RHS->getID();
  1544. }
  1545. };
  1546. /// Sorting predicate to sort record pointers by their
  1547. /// name field.
  1548. struct LessRecordFieldName {
  1549. bool operator()(const Record *Rec1, const Record *Rec2) const {
  1550. return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
  1551. }
  1552. };
  1553. struct LessRecordRegister {
  1554. struct RecordParts {
  1555. SmallVector<std::pair< bool, StringRef>, 4> Parts;
  1556. RecordParts(StringRef Rec) {
  1557. if (Rec.empty())
  1558. return;
  1559. size_t Len = 0;
  1560. const char *Start = Rec.data();
  1561. const char *Curr = Start;
  1562. bool IsDigitPart = isDigit(Curr[0]);
  1563. for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
  1564. bool IsDigit = isDigit(Curr[I]);
  1565. if (IsDigit != IsDigitPart) {
  1566. Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
  1567. Len = 0;
  1568. Start = &Curr[I];
  1569. IsDigitPart = isDigit(Curr[I]);
  1570. }
  1571. }
  1572. // Push the last part.
  1573. Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
  1574. }
  1575. size_t size() { return Parts.size(); }
  1576. std::pair<bool, StringRef> getPart(size_t i) {
  1577. assert (i < Parts.size() && "Invalid idx!");
  1578. return Parts[i];
  1579. }
  1580. };
  1581. bool operator()(const Record *Rec1, const Record *Rec2) const {
  1582. RecordParts LHSParts(StringRef(Rec1->getName()));
  1583. RecordParts RHSParts(StringRef(Rec2->getName()));
  1584. size_t LHSNumParts = LHSParts.size();
  1585. size_t RHSNumParts = RHSParts.size();
  1586. assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
  1587. if (LHSNumParts != RHSNumParts)
  1588. return LHSNumParts < RHSNumParts;
  1589. // We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
  1590. for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
  1591. std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
  1592. std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
  1593. // Expect even part to always be alpha.
  1594. assert (LHSPart.first == false && RHSPart.first == false &&
  1595. "Expected both parts to be alpha.");
  1596. if (int Res = LHSPart.second.compare(RHSPart.second))
  1597. return Res < 0;
  1598. }
  1599. for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
  1600. std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
  1601. std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
  1602. // Expect odd part to always be numeric.
  1603. assert (LHSPart.first == true && RHSPart.first == true &&
  1604. "Expected both parts to be numeric.");
  1605. if (LHSPart.second.size() != RHSPart.second.size())
  1606. return LHSPart.second.size() < RHSPart.second.size();
  1607. unsigned LHSVal, RHSVal;
  1608. bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
  1609. assert(!LHSFailed && "Unable to convert LHS to integer.");
  1610. bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
  1611. assert(!RHSFailed && "Unable to convert RHS to integer.");
  1612. if (LHSVal != RHSVal)
  1613. return LHSVal < RHSVal;
  1614. }
  1615. return LHSNumParts < RHSNumParts;
  1616. }
  1617. };
  1618. raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
  1619. //===----------------------------------------------------------------------===//
  1620. // Resolvers
  1621. //===----------------------------------------------------------------------===//
  1622. /// Interface for looking up the initializer for a variable name, used by
  1623. /// Init::resolveReferences.
  1624. class Resolver {
  1625. Record *CurRec;
  1626. bool IsFinal = false;
  1627. public:
  1628. explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
  1629. virtual ~Resolver() = default;
  1630. Record *getCurrentRecord() const { return CurRec; }
  1631. /// Return the initializer for the given variable name (should normally be a
  1632. /// StringInit), or nullptr if the name could not be resolved.
  1633. virtual Init *resolve(Init *VarName) = 0;
  1634. // Whether bits in a BitsInit should stay unresolved if resolving them would
  1635. // result in a ? (UnsetInit). This behavior is used to represent instruction
  1636. // encodings by keeping references to unset variables within a record.
  1637. virtual bool keepUnsetBits() const { return false; }
  1638. // Whether this is the final resolve step before adding a record to the
  1639. // RecordKeeper. Error reporting during resolve and related constant folding
  1640. // should only happen when this is true.
  1641. bool isFinal() const { return IsFinal; }
  1642. void setFinal(bool Final) { IsFinal = Final; }
  1643. };
  1644. /// Resolve arbitrary mappings.
  1645. class MapResolver final : public Resolver {
  1646. struct MappedValue {
  1647. Init *V;
  1648. bool Resolved;
  1649. MappedValue() : V(nullptr), Resolved(false) {}
  1650. MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
  1651. };
  1652. DenseMap<Init *, MappedValue> Map;
  1653. public:
  1654. explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
  1655. void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
  1656. bool isComplete(Init *VarName) const {
  1657. auto It = Map.find(VarName);
  1658. assert(It != Map.end() && "key must be present in map");
  1659. return It->second.V->isComplete();
  1660. }
  1661. Init *resolve(Init *VarName) override;
  1662. };
  1663. /// Resolve all variables from a record except for unset variables.
  1664. class RecordResolver final : public Resolver {
  1665. DenseMap<Init *, Init *> Cache;
  1666. SmallVector<Init *, 4> Stack;
  1667. Init *Name = nullptr;
  1668. public:
  1669. explicit RecordResolver(Record &R) : Resolver(&R) {}
  1670. void setName(Init *NewName) { Name = NewName; }
  1671. Init *resolve(Init *VarName) override;
  1672. bool keepUnsetBits() const override { return true; }
  1673. };
  1674. /// Delegate resolving to a sub-resolver, but shadow some variable names.
  1675. class ShadowResolver final : public Resolver {
  1676. Resolver &R;
  1677. DenseSet<Init *> Shadowed;
  1678. public:
  1679. explicit ShadowResolver(Resolver &R)
  1680. : Resolver(R.getCurrentRecord()), R(R) {
  1681. setFinal(R.isFinal());
  1682. }
  1683. void addShadow(Init *Key) { Shadowed.insert(Key); }
  1684. Init *resolve(Init *VarName) override {
  1685. if (Shadowed.count(VarName))
  1686. return nullptr;
  1687. return R.resolve(VarName);
  1688. }
  1689. };
  1690. /// (Optionally) delegate resolving to a sub-resolver, and keep track whether
  1691. /// there were unresolved references.
  1692. class TrackUnresolvedResolver final : public Resolver {
  1693. Resolver *R;
  1694. bool FoundUnresolved = false;
  1695. public:
  1696. explicit TrackUnresolvedResolver(Resolver *R = nullptr)
  1697. : Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
  1698. bool foundUnresolved() const { return FoundUnresolved; }
  1699. Init *resolve(Init *VarName) override;
  1700. };
  1701. /// Do not resolve anything, but keep track of whether a given variable was
  1702. /// referenced.
  1703. class HasReferenceResolver final : public Resolver {
  1704. Init *VarNameToTrack;
  1705. bool Found = false;
  1706. public:
  1707. explicit HasReferenceResolver(Init *VarNameToTrack)
  1708. : Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
  1709. bool found() const { return Found; }
  1710. Init *resolve(Init *VarName) override;
  1711. };
  1712. void EmitDetailedRecords(RecordKeeper &RK, raw_ostream &OS);
  1713. void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
  1714. } // end namespace llvm
  1715. #endif // LLVM_TABLEGEN_RECORD_H
  1716. #ifdef __GNUC__
  1717. #pragma GCC diagnostic pop
  1718. #endif