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