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