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