Home | History | Annotate | Line # | Download | only in IR
      1 //===- llvm/IR/DebugInfoMetadata.h - Debug info metadata --------*- 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 // Declarations for metadata specific to debug info.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #ifndef LLVM_IR_DEBUGINFOMETADATA_H
     14 #define LLVM_IR_DEBUGINFOMETADATA_H
     15 
     16 #include "llvm/ADT/ArrayRef.h"
     17 #include "llvm/ADT/BitmaskEnum.h"
     18 #include "llvm/ADT/None.h"
     19 #include "llvm/ADT/Optional.h"
     20 #include "llvm/ADT/PointerUnion.h"
     21 #include "llvm/ADT/STLExtras.h"
     22 #include "llvm/ADT/SmallVector.h"
     23 #include "llvm/ADT/StringRef.h"
     24 #include "llvm/ADT/iterator_range.h"
     25 #include "llvm/BinaryFormat/Dwarf.h"
     26 #include "llvm/IR/Constants.h"
     27 #include "llvm/IR/Metadata.h"
     28 #include "llvm/Support/Casting.h"
     29 #include "llvm/Support/CommandLine.h"
     30 #include "llvm/Support/Discriminator.h"
     31 #include <cassert>
     32 #include <climits>
     33 #include <cstddef>
     34 #include <cstdint>
     35 #include <iterator>
     36 #include <type_traits>
     37 #include <vector>
     38 
     39 // Helper macros for defining get() overrides.
     40 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
     41 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
     42 #define DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)              \
     43   static CLASS *getDistinct(LLVMContext &Context,                              \
     44                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
     45     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
     46   }                                                                            \
     47   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
     48                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
     49     return Temp##CLASS(                                                        \
     50         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
     51   }
     52 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
     53   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
     54     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
     55   }                                                                            \
     56   static CLASS *getIfExists(LLVMContext &Context,                              \
     57                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
     58     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
     59                    /* ShouldCreate */ false);                                  \
     60   }                                                                            \
     61   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)
     62 
     63 namespace llvm {
     64 
     65 extern cl::opt<bool> EnableFSDiscriminator;
     66 
     67 class DITypeRefArray {
     68   const MDTuple *N = nullptr;
     69 
     70 public:
     71   DITypeRefArray() = default;
     72   DITypeRefArray(const MDTuple *N) : N(N) {}
     73 
     74   explicit operator bool() const { return get(); }
     75   explicit operator MDTuple *() const { return get(); }
     76 
     77   MDTuple *get() const { return const_cast<MDTuple *>(N); }
     78   MDTuple *operator->() const { return get(); }
     79   MDTuple &operator*() const { return *get(); }
     80 
     81   // FIXME: Fix callers and remove condition on N.
     82   unsigned size() const { return N ? N->getNumOperands() : 0u; }
     83   DIType *operator[](unsigned I) const {
     84     return cast_or_null<DIType>(N->getOperand(I));
     85   }
     86 
     87   class iterator {
     88     MDNode::op_iterator I = nullptr;
     89 
     90   public:
     91     using iterator_category = std::input_iterator_tag;
     92     using value_type = DIType *;
     93     using difference_type = std::ptrdiff_t;
     94     using pointer = void;
     95     using reference = DIType *;
     96 
     97     iterator() = default;
     98     explicit iterator(MDNode::op_iterator I) : I(I) {}
     99 
    100     DIType *operator*() const { return cast_or_null<DIType>(*I); }
    101 
    102     iterator &operator++() {
    103       ++I;
    104       return *this;
    105     }
    106 
    107     iterator operator++(int) {
    108       iterator Temp(*this);
    109       ++I;
    110       return Temp;
    111     }
    112 
    113     bool operator==(const iterator &X) const { return I == X.I; }
    114     bool operator!=(const iterator &X) const { return I != X.I; }
    115   };
    116 
    117   // FIXME: Fix callers and remove condition on N.
    118   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
    119   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
    120 };
    121 
    122 /// Tagged DWARF-like metadata node.
    123 ///
    124 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
    125 /// defined in llvm/BinaryFormat/Dwarf.h).  Called \a DINode because it's
    126 /// potentially used for non-DWARF output.
    127 class DINode : public MDNode {
    128   friend class LLVMContextImpl;
    129   friend class MDNode;
    130 
    131 protected:
    132   DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
    133          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
    134       : MDNode(C, ID, Storage, Ops1, Ops2) {
    135     assert(Tag < 1u << 16);
    136     SubclassData16 = Tag;
    137   }
    138   ~DINode() = default;
    139 
    140   template <class Ty> Ty *getOperandAs(unsigned I) const {
    141     return cast_or_null<Ty>(getOperand(I));
    142   }
    143 
    144   StringRef getStringOperand(unsigned I) const {
    145     if (auto *S = getOperandAs<MDString>(I))
    146       return S->getString();
    147     return StringRef();
    148   }
    149 
    150   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
    151     if (S.empty())
    152       return nullptr;
    153     return MDString::get(Context, S);
    154   }
    155 
    156   /// Allow subclasses to mutate the tag.
    157   void setTag(unsigned Tag) { SubclassData16 = Tag; }
    158 
    159 public:
    160   dwarf::Tag getTag() const { return (dwarf::Tag)SubclassData16; }
    161 
    162   /// Debug info flags.
    163   ///
    164   /// The three accessibility flags are mutually exclusive and rolled together
    165   /// in the first two bits.
    166   enum DIFlags : uint32_t {
    167 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
    168 #define DI_FLAG_LARGEST_NEEDED
    169 #include "llvm/IR/DebugInfoFlags.def"
    170     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic,
    171     FlagPtrToMemberRep = FlagSingleInheritance | FlagMultipleInheritance |
    172                          FlagVirtualInheritance,
    173     LLVM_MARK_AS_BITMASK_ENUM(FlagLargest)
    174   };
    175 
    176   static DIFlags getFlag(StringRef Flag);
    177   static StringRef getFlagString(DIFlags Flag);
    178 
    179   /// Split up a flags bitfield.
    180   ///
    181   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
    182   /// any remaining (unrecognized) bits.
    183   static DIFlags splitFlags(DIFlags Flags,
    184                             SmallVectorImpl<DIFlags> &SplitFlags);
    185 
    186   static bool classof(const Metadata *MD) {
    187     switch (MD->getMetadataID()) {
    188     default:
    189       return false;
    190     case GenericDINodeKind:
    191     case DISubrangeKind:
    192     case DIEnumeratorKind:
    193     case DIBasicTypeKind:
    194     case DIStringTypeKind:
    195     case DIDerivedTypeKind:
    196     case DICompositeTypeKind:
    197     case DISubroutineTypeKind:
    198     case DIFileKind:
    199     case DICompileUnitKind:
    200     case DISubprogramKind:
    201     case DILexicalBlockKind:
    202     case DILexicalBlockFileKind:
    203     case DINamespaceKind:
    204     case DICommonBlockKind:
    205     case DITemplateTypeParameterKind:
    206     case DITemplateValueParameterKind:
    207     case DIGlobalVariableKind:
    208     case DILocalVariableKind:
    209     case DILabelKind:
    210     case DIObjCPropertyKind:
    211     case DIImportedEntityKind:
    212     case DIModuleKind:
    213     case DIGenericSubrangeKind:
    214       return true;
    215     }
    216   }
    217 };
    218 
    219 /// Generic tagged DWARF-like metadata node.
    220 ///
    221 /// An un-specialized DWARF-like metadata node.  The first operand is a
    222 /// (possibly empty) null-separated \a MDString header that contains arbitrary
    223 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
    224 /// to other metadata.
    225 class GenericDINode : public DINode {
    226   friend class LLVMContextImpl;
    227   friend class MDNode;
    228 
    229   GenericDINode(LLVMContext &C, StorageType Storage, unsigned Hash,
    230                 unsigned Tag, ArrayRef<Metadata *> Ops1,
    231                 ArrayRef<Metadata *> Ops2)
    232       : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
    233     setHash(Hash);
    234   }
    235   ~GenericDINode() { dropAllReferences(); }
    236 
    237   void setHash(unsigned Hash) { SubclassData32 = Hash; }
    238   void recalculateHash();
    239 
    240   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
    241                                 StringRef Header, ArrayRef<Metadata *> DwarfOps,
    242                                 StorageType Storage, bool ShouldCreate = true) {
    243     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
    244                    DwarfOps, Storage, ShouldCreate);
    245   }
    246 
    247   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
    248                                 MDString *Header, ArrayRef<Metadata *> DwarfOps,
    249                                 StorageType Storage, bool ShouldCreate = true);
    250 
    251   TempGenericDINode cloneImpl() const {
    252     return getTemporary(getContext(), getTag(), getHeader(),
    253                         SmallVector<Metadata *, 4>(dwarf_operands()));
    254   }
    255 
    256 public:
    257   unsigned getHash() const { return SubclassData32; }
    258 
    259   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, StringRef Header,
    260                                     ArrayRef<Metadata *> DwarfOps),
    261                     (Tag, Header, DwarfOps))
    262   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, MDString *Header,
    263                                     ArrayRef<Metadata *> DwarfOps),
    264                     (Tag, Header, DwarfOps))
    265 
    266   /// Return a (temporary) clone of this.
    267   TempGenericDINode clone() const { return cloneImpl(); }
    268 
    269   dwarf::Tag getTag() const { return (dwarf::Tag)SubclassData16; }
    270   StringRef getHeader() const { return getStringOperand(0); }
    271   MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
    272 
    273   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
    274   op_iterator dwarf_op_end() const { return op_end(); }
    275   op_range dwarf_operands() const {
    276     return op_range(dwarf_op_begin(), dwarf_op_end());
    277   }
    278 
    279   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
    280   const MDOperand &getDwarfOperand(unsigned I) const {
    281     return getOperand(I + 1);
    282   }
    283   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
    284     replaceOperandWith(I + 1, New);
    285   }
    286 
    287   static bool classof(const Metadata *MD) {
    288     return MD->getMetadataID() == GenericDINodeKind;
    289   }
    290 };
    291 
    292 /// Array subrange.
    293 ///
    294 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
    295 /// type.
    296 class DISubrange : public DINode {
    297   friend class LLVMContextImpl;
    298   friend class MDNode;
    299 
    300   DISubrange(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
    301       : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {}
    302 
    303   ~DISubrange() = default;
    304 
    305   static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
    306                              int64_t LowerBound, StorageType Storage,
    307                              bool ShouldCreate = true);
    308 
    309   static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
    310                              int64_t LowerBound, StorageType Storage,
    311                              bool ShouldCreate = true);
    312 
    313   static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
    314                              Metadata *LowerBound, Metadata *UpperBound,
    315                              Metadata *Stride, StorageType Storage,
    316                              bool ShouldCreate = true);
    317 
    318   TempDISubrange cloneImpl() const {
    319     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
    320                         getRawUpperBound(), getRawStride());
    321   }
    322 
    323 public:
    324   DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
    325                     (Count, LowerBound))
    326 
    327   DEFINE_MDNODE_GET(DISubrange, (Metadata *CountNode, int64_t LowerBound = 0),
    328                     (CountNode, LowerBound))
    329 
    330   DEFINE_MDNODE_GET(DISubrange,
    331                     (Metadata * CountNode, Metadata *LowerBound,
    332                      Metadata *UpperBound, Metadata *Stride),
    333                     (CountNode, LowerBound, UpperBound, Stride))
    334 
    335   TempDISubrange clone() const { return cloneImpl(); }
    336 
    337   Metadata *getRawCountNode() const {
    338     return getOperand(0).get();
    339   }
    340 
    341   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
    342 
    343   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
    344 
    345   Metadata *getRawStride() const { return getOperand(3).get(); }
    346 
    347   typedef PointerUnion<ConstantInt *, DIVariable *, DIExpression *> BoundType;
    348 
    349   BoundType getCount() const;
    350 
    351   BoundType getLowerBound() const;
    352 
    353   BoundType getUpperBound() const;
    354 
    355   BoundType getStride() const;
    356 
    357   static bool classof(const Metadata *MD) {
    358     return MD->getMetadataID() == DISubrangeKind;
    359   }
    360 };
    361 
    362 class DIGenericSubrange : public DINode {
    363   friend class LLVMContextImpl;
    364   friend class MDNode;
    365 
    366   DIGenericSubrange(LLVMContext &C, StorageType Storage,
    367                     ArrayRef<Metadata *> Ops)
    368       : DINode(C, DIGenericSubrangeKind, Storage,
    369                dwarf::DW_TAG_generic_subrange, Ops) {}
    370 
    371   ~DIGenericSubrange() = default;
    372 
    373   static DIGenericSubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
    374                                     Metadata *LowerBound, Metadata *UpperBound,
    375                                     Metadata *Stride, StorageType Storage,
    376                                     bool ShouldCreate = true);
    377 
    378   TempDIGenericSubrange cloneImpl() const {
    379     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
    380                         getRawUpperBound(), getRawStride());
    381   }
    382 
    383 public:
    384   DEFINE_MDNODE_GET(DIGenericSubrange,
    385                     (Metadata * CountNode, Metadata *LowerBound,
    386                      Metadata *UpperBound, Metadata *Stride),
    387                     (CountNode, LowerBound, UpperBound, Stride))
    388 
    389   TempDIGenericSubrange clone() const { return cloneImpl(); }
    390 
    391   Metadata *getRawCountNode() const { return getOperand(0).get(); }
    392   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
    393   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
    394   Metadata *getRawStride() const { return getOperand(3).get(); }
    395 
    396   using BoundType = PointerUnion<DIVariable *, DIExpression *>;
    397 
    398   BoundType getCount() const;
    399   BoundType getLowerBound() const;
    400   BoundType getUpperBound() const;
    401   BoundType getStride() const;
    402 
    403   static bool classof(const Metadata *MD) {
    404     return MD->getMetadataID() == DIGenericSubrangeKind;
    405   }
    406 };
    407 
    408 /// Enumeration value.
    409 ///
    410 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
    411 /// longer creates a type cycle.
    412 class DIEnumerator : public DINode {
    413   friend class LLVMContextImpl;
    414   friend class MDNode;
    415 
    416   APInt Value;
    417   DIEnumerator(LLVMContext &C, StorageType Storage, const APInt &Value,
    418                bool IsUnsigned, ArrayRef<Metadata *> Ops)
    419       : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
    420         Value(Value) {
    421     SubclassData32 = IsUnsigned;
    422   }
    423   DIEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
    424                bool IsUnsigned, ArrayRef<Metadata *> Ops)
    425       : DIEnumerator(C, Storage, APInt(64, Value, !IsUnsigned), IsUnsigned,
    426                      Ops) {}
    427   ~DIEnumerator() = default;
    428 
    429   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
    430                                bool IsUnsigned, StringRef Name,
    431                                StorageType Storage, bool ShouldCreate = true) {
    432     return getImpl(Context, Value, IsUnsigned,
    433                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
    434   }
    435   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
    436                                bool IsUnsigned, MDString *Name,
    437                                StorageType Storage, bool ShouldCreate = true);
    438 
    439   TempDIEnumerator cloneImpl() const {
    440     return getTemporary(getContext(), getValue(), isUnsigned(), getName());
    441   }
    442 
    443 public:
    444   DEFINE_MDNODE_GET(DIEnumerator,
    445                     (int64_t Value, bool IsUnsigned, StringRef Name),
    446                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
    447   DEFINE_MDNODE_GET(DIEnumerator,
    448                     (int64_t Value, bool IsUnsigned, MDString *Name),
    449                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
    450   DEFINE_MDNODE_GET(DIEnumerator,
    451                     (APInt Value, bool IsUnsigned, StringRef Name),
    452                     (Value, IsUnsigned, Name))
    453   DEFINE_MDNODE_GET(DIEnumerator,
    454                     (APInt Value, bool IsUnsigned, MDString *Name),
    455                     (Value, IsUnsigned, Name))
    456 
    457   TempDIEnumerator clone() const { return cloneImpl(); }
    458 
    459   const APInt &getValue() const { return Value; }
    460   bool isUnsigned() const { return SubclassData32; }
    461   StringRef getName() const { return getStringOperand(0); }
    462 
    463   MDString *getRawName() const { return getOperandAs<MDString>(0); }
    464 
    465   static bool classof(const Metadata *MD) {
    466     return MD->getMetadataID() == DIEnumeratorKind;
    467   }
    468 };
    469 
    470 /// Base class for scope-like contexts.
    471 ///
    472 /// Base class for lexical scopes and types (which are also declaration
    473 /// contexts).
    474 ///
    475 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
    476 class DIScope : public DINode {
    477 protected:
    478   DIScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
    479           ArrayRef<Metadata *> Ops)
    480       : DINode(C, ID, Storage, Tag, Ops) {}
    481   ~DIScope() = default;
    482 
    483 public:
    484   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
    485 
    486   inline StringRef getFilename() const;
    487   inline StringRef getDirectory() const;
    488   inline Optional<StringRef> getSource() const;
    489 
    490   StringRef getName() const;
    491   DIScope *getScope() const;
    492 
    493   /// Return the raw underlying file.
    494   ///
    495   /// A \a DIFile is a \a DIScope, but it doesn't point at a separate file (it
    496   /// \em is the file).  If \c this is an \a DIFile, we need to return \c this.
    497   /// Otherwise, return the first operand, which is where all other subclasses
    498   /// store their file pointer.
    499   Metadata *getRawFile() const {
    500     return isa<DIFile>(this) ? const_cast<DIScope *>(this)
    501                              : static_cast<Metadata *>(getOperand(0));
    502   }
    503 
    504   static bool classof(const Metadata *MD) {
    505     switch (MD->getMetadataID()) {
    506     default:
    507       return false;
    508     case DIBasicTypeKind:
    509     case DIStringTypeKind:
    510     case DIDerivedTypeKind:
    511     case DICompositeTypeKind:
    512     case DISubroutineTypeKind:
    513     case DIFileKind:
    514     case DICompileUnitKind:
    515     case DISubprogramKind:
    516     case DILexicalBlockKind:
    517     case DILexicalBlockFileKind:
    518     case DINamespaceKind:
    519     case DICommonBlockKind:
    520     case DIModuleKind:
    521       return true;
    522     }
    523   }
    524 };
    525 
    526 /// File.
    527 ///
    528 /// TODO: Merge with directory/file node (including users).
    529 /// TODO: Canonicalize paths on creation.
    530 class DIFile : public DIScope {
    531   friend class LLVMContextImpl;
    532   friend class MDNode;
    533 
    534 public:
    535   /// Which algorithm (e.g. MD5) a checksum was generated with.
    536   ///
    537   /// The encoding is explicit because it is used directly in Bitcode. The
    538   /// value 0 is reserved to indicate the absence of a checksum in Bitcode.
    539   enum ChecksumKind {
    540     // The first variant was originally CSK_None, encoded as 0. The new
    541     // internal representation removes the need for this by wrapping the
    542     // ChecksumInfo in an Optional, but to preserve Bitcode compatibility the 0
    543     // encoding is reserved.
    544     CSK_MD5 = 1,
    545     CSK_SHA1 = 2,
    546     CSK_SHA256 = 3,
    547     CSK_Last = CSK_SHA256 // Should be last enumeration.
    548   };
    549 
    550   /// A single checksum, represented by a \a Kind and a \a Value (a string).
    551   template <typename T>
    552   struct ChecksumInfo {
    553     /// The kind of checksum which \a Value encodes.
    554     ChecksumKind Kind;
    555     /// The string value of the checksum.
    556     T Value;
    557 
    558     ChecksumInfo(ChecksumKind Kind, T Value) : Kind(Kind), Value(Value) { }
    559     ~ChecksumInfo() = default;
    560     bool operator==(const ChecksumInfo<T> &X) const {
    561       return Kind == X.Kind && Value == X.Value;
    562     }
    563     bool operator!=(const ChecksumInfo<T> &X) const { return !(*this == X); }
    564     StringRef getKindAsString() const { return getChecksumKindAsString(Kind); }
    565   };
    566 
    567 private:
    568   Optional<ChecksumInfo<MDString *>> Checksum;
    569   Optional<MDString *> Source;
    570 
    571   DIFile(LLVMContext &C, StorageType Storage,
    572          Optional<ChecksumInfo<MDString *>> CS, Optional<MDString *> Src,
    573          ArrayRef<Metadata *> Ops)
    574       : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
    575         Checksum(CS), Source(Src) {}
    576   ~DIFile() = default;
    577 
    578   static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
    579                          StringRef Directory,
    580                          Optional<ChecksumInfo<StringRef>> CS,
    581                          Optional<StringRef> Source,
    582                          StorageType Storage, bool ShouldCreate = true) {
    583     Optional<ChecksumInfo<MDString *>> MDChecksum;
    584     if (CS)
    585       MDChecksum.emplace(CS->Kind, getCanonicalMDString(Context, CS->Value));
    586     return getImpl(Context, getCanonicalMDString(Context, Filename),
    587                    getCanonicalMDString(Context, Directory), MDChecksum,
    588                    Source ? Optional<MDString *>(getCanonicalMDString(Context, *Source)) : None,
    589                    Storage, ShouldCreate);
    590   }
    591   static DIFile *getImpl(LLVMContext &Context, MDString *Filename,
    592                          MDString *Directory,
    593                          Optional<ChecksumInfo<MDString *>> CS,
    594                          Optional<MDString *> Source, StorageType Storage,
    595                          bool ShouldCreate = true);
    596 
    597   TempDIFile cloneImpl() const {
    598     return getTemporary(getContext(), getFilename(), getDirectory(),
    599                         getChecksum(), getSource());
    600   }
    601 
    602 public:
    603   DEFINE_MDNODE_GET(DIFile, (StringRef Filename, StringRef Directory,
    604                              Optional<ChecksumInfo<StringRef>> CS = None,
    605                              Optional<StringRef> Source = None),
    606                     (Filename, Directory, CS, Source))
    607   DEFINE_MDNODE_GET(DIFile, (MDString * Filename, MDString *Directory,
    608                              Optional<ChecksumInfo<MDString *>> CS = None,
    609                              Optional<MDString *> Source = None),
    610                     (Filename, Directory, CS, Source))
    611 
    612   TempDIFile clone() const { return cloneImpl(); }
    613 
    614   StringRef getFilename() const { return getStringOperand(0); }
    615   StringRef getDirectory() const { return getStringOperand(1); }
    616   Optional<ChecksumInfo<StringRef>> getChecksum() const {
    617     Optional<ChecksumInfo<StringRef>> StringRefChecksum;
    618     if (Checksum)
    619       StringRefChecksum.emplace(Checksum->Kind, Checksum->Value->getString());
    620     return StringRefChecksum;
    621   }
    622   Optional<StringRef> getSource() const {
    623     return Source ? Optional<StringRef>((*Source)->getString()) : None;
    624   }
    625 
    626   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
    627   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
    628   Optional<ChecksumInfo<MDString *>> getRawChecksum() const { return Checksum; }
    629   Optional<MDString *> getRawSource() const { return Source; }
    630 
    631   static StringRef getChecksumKindAsString(ChecksumKind CSKind);
    632   static Optional<ChecksumKind> getChecksumKind(StringRef CSKindStr);
    633 
    634   static bool classof(const Metadata *MD) {
    635     return MD->getMetadataID() == DIFileKind;
    636   }
    637 };
    638 
    639 StringRef DIScope::getFilename() const {
    640   if (auto *F = getFile())
    641     return F->getFilename();
    642   return "";
    643 }
    644 
    645 StringRef DIScope::getDirectory() const {
    646   if (auto *F = getFile())
    647     return F->getDirectory();
    648   return "";
    649 }
    650 
    651 Optional<StringRef> DIScope::getSource() const {
    652   if (auto *F = getFile())
    653     return F->getSource();
    654   return None;
    655 }
    656 
    657 /// Base class for types.
    658 ///
    659 /// TODO: Remove the hardcoded name and context, since many types don't use
    660 /// them.
    661 /// TODO: Split up flags.
    662 class DIType : public DIScope {
    663   unsigned Line;
    664   DIFlags Flags;
    665   uint64_t SizeInBits;
    666   uint64_t OffsetInBits;
    667   uint32_t AlignInBits;
    668 
    669 protected:
    670   DIType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
    671          unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
    672          uint64_t OffsetInBits, DIFlags Flags, ArrayRef<Metadata *> Ops)
    673       : DIScope(C, ID, Storage, Tag, Ops) {
    674     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
    675   }
    676   ~DIType() = default;
    677 
    678   void init(unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
    679             uint64_t OffsetInBits, DIFlags Flags) {
    680     this->Line = Line;
    681     this->Flags = Flags;
    682     this->SizeInBits = SizeInBits;
    683     this->AlignInBits = AlignInBits;
    684     this->OffsetInBits = OffsetInBits;
    685   }
    686 
    687   /// Change fields in place.
    688   void mutate(unsigned Tag, unsigned Line, uint64_t SizeInBits,
    689               uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags) {
    690     assert(isDistinct() && "Only distinct nodes can mutate");
    691     setTag(Tag);
    692     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
    693   }
    694 
    695 public:
    696   TempDIType clone() const {
    697     return TempDIType(cast<DIType>(MDNode::clone().release()));
    698   }
    699 
    700   unsigned getLine() const { return Line; }
    701   uint64_t getSizeInBits() const { return SizeInBits; }
    702   uint32_t getAlignInBits() const { return AlignInBits; }
    703   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
    704   uint64_t getOffsetInBits() const { return OffsetInBits; }
    705   DIFlags getFlags() const { return Flags; }
    706 
    707   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
    708   StringRef getName() const { return getStringOperand(2); }
    709 
    710 
    711   Metadata *getRawScope() const { return getOperand(1); }
    712   MDString *getRawName() const { return getOperandAs<MDString>(2); }
    713 
    714   /// Returns a new temporary DIType with updated Flags
    715   TempDIType cloneWithFlags(DIFlags NewFlags) const {
    716     auto NewTy = clone();
    717     NewTy->Flags = NewFlags;
    718     return NewTy;
    719   }
    720 
    721   bool isPrivate() const {
    722     return (getFlags() & FlagAccessibility) == FlagPrivate;
    723   }
    724   bool isProtected() const {
    725     return (getFlags() & FlagAccessibility) == FlagProtected;
    726   }
    727   bool isPublic() const {
    728     return (getFlags() & FlagAccessibility) == FlagPublic;
    729   }
    730   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
    731   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
    732   bool isVirtual() const { return getFlags() & FlagVirtual; }
    733   bool isArtificial() const { return getFlags() & FlagArtificial; }
    734   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
    735   bool isObjcClassComplete() const {
    736     return getFlags() & FlagObjcClassComplete;
    737   }
    738   bool isVector() const { return getFlags() & FlagVector; }
    739   bool isBitField() const { return getFlags() & FlagBitField; }
    740   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
    741   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
    742   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
    743   bool isTypePassByValue() const { return getFlags() & FlagTypePassByValue; }
    744   bool isTypePassByReference() const {
    745     return getFlags() & FlagTypePassByReference;
    746   }
    747   bool isBigEndian() const { return getFlags() & FlagBigEndian; }
    748   bool isLittleEndian() const { return getFlags() & FlagLittleEndian; }
    749   bool getExportSymbols() const { return getFlags() & FlagExportSymbols; }
    750 
    751   static bool classof(const Metadata *MD) {
    752     switch (MD->getMetadataID()) {
    753     default:
    754       return false;
    755     case DIBasicTypeKind:
    756     case DIStringTypeKind:
    757     case DIDerivedTypeKind:
    758     case DICompositeTypeKind:
    759     case DISubroutineTypeKind:
    760       return true;
    761     }
    762   }
    763 };
    764 
    765 /// Basic type, like 'int' or 'float'.
    766 ///
    767 /// TODO: Split out DW_TAG_unspecified_type.
    768 /// TODO: Drop unused accessors.
    769 class DIBasicType : public DIType {
    770   friend class LLVMContextImpl;
    771   friend class MDNode;
    772 
    773   unsigned Encoding;
    774 
    775   DIBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
    776               uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
    777               DIFlags Flags, ArrayRef<Metadata *> Ops)
    778       : DIType(C, DIBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
    779                Flags, Ops),
    780         Encoding(Encoding) {}
    781   ~DIBasicType() = default;
    782 
    783   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
    784                               StringRef Name, uint64_t SizeInBits,
    785                               uint32_t AlignInBits, unsigned Encoding,
    786                               DIFlags Flags, StorageType Storage,
    787                               bool ShouldCreate = true) {
    788     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
    789                    SizeInBits, AlignInBits, Encoding, Flags, Storage,
    790                    ShouldCreate);
    791   }
    792   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
    793                               MDString *Name, uint64_t SizeInBits,
    794                               uint32_t AlignInBits, unsigned Encoding,
    795                               DIFlags Flags, StorageType Storage,
    796                               bool ShouldCreate = true);
    797 
    798   TempDIBasicType cloneImpl() const {
    799     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
    800                         getAlignInBits(), getEncoding(), getFlags());
    801   }
    802 
    803 public:
    804   DEFINE_MDNODE_GET(DIBasicType, (unsigned Tag, StringRef Name),
    805                     (Tag, Name, 0, 0, 0, FlagZero))
    806   DEFINE_MDNODE_GET(DIBasicType,
    807                     (unsigned Tag, StringRef Name, uint64_t SizeInBits),
    808                     (Tag, Name, SizeInBits, 0, 0, FlagZero))
    809   DEFINE_MDNODE_GET(DIBasicType,
    810                     (unsigned Tag, MDString *Name, uint64_t SizeInBits),
    811                     (Tag, Name, SizeInBits, 0, 0, FlagZero))
    812   DEFINE_MDNODE_GET(DIBasicType,
    813                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
    814                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
    815                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
    816   DEFINE_MDNODE_GET(DIBasicType,
    817                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
    818                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
    819                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
    820 
    821   TempDIBasicType clone() const { return cloneImpl(); }
    822 
    823   unsigned getEncoding() const { return Encoding; }
    824 
    825   enum class Signedness { Signed, Unsigned };
    826 
    827   /// Return the signedness of this type, or None if this type is neither
    828   /// signed nor unsigned.
    829   Optional<Signedness> getSignedness() const;
    830 
    831   static bool classof(const Metadata *MD) {
    832     return MD->getMetadataID() == DIBasicTypeKind;
    833   }
    834 };
    835 
    836 /// String type, Fortran CHARACTER(n)
    837 class DIStringType : public DIType {
    838   friend class LLVMContextImpl;
    839   friend class MDNode;
    840 
    841   unsigned Encoding;
    842 
    843   DIStringType(LLVMContext &C, StorageType Storage, unsigned Tag,
    844                uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
    845                ArrayRef<Metadata *> Ops)
    846       : DIType(C, DIStringTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
    847                FlagZero, Ops),
    848         Encoding(Encoding) {}
    849   ~DIStringType() = default;
    850 
    851   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
    852                                StringRef Name, Metadata *StringLength,
    853                                Metadata *StrLenExp, uint64_t SizeInBits,
    854                                uint32_t AlignInBits, unsigned Encoding,
    855                                StorageType Storage, bool ShouldCreate = true) {
    856     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
    857                    StringLength, StrLenExp, SizeInBits, AlignInBits, Encoding,
    858                    Storage, ShouldCreate);
    859   }
    860   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
    861                                MDString *Name, Metadata *StringLength,
    862                                Metadata *StrLenExp, uint64_t SizeInBits,
    863                                uint32_t AlignInBits, unsigned Encoding,
    864                                StorageType Storage, bool ShouldCreate = true);
    865 
    866   TempDIStringType cloneImpl() const {
    867     return getTemporary(getContext(), getTag(), getRawName(),
    868                         getRawStringLength(), getRawStringLengthExp(),
    869                         getSizeInBits(), getAlignInBits(), getEncoding());
    870   }
    871 
    872 public:
    873   DEFINE_MDNODE_GET(DIStringType,
    874                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
    875                      uint32_t AlignInBits),
    876                     (Tag, Name, nullptr, nullptr, SizeInBits, AlignInBits, 0))
    877   DEFINE_MDNODE_GET(DIStringType,
    878                     (unsigned Tag, MDString *Name, Metadata *StringLength,
    879                      Metadata *StringLengthExp, uint64_t SizeInBits,
    880                      uint32_t AlignInBits, unsigned Encoding),
    881                     (Tag, Name, StringLength, StringLengthExp, SizeInBits,
    882                      AlignInBits, Encoding))
    883   DEFINE_MDNODE_GET(DIStringType,
    884                     (unsigned Tag, StringRef Name, Metadata *StringLength,
    885                      Metadata *StringLengthExp, uint64_t SizeInBits,
    886                      uint32_t AlignInBits, unsigned Encoding),
    887                     (Tag, Name, StringLength, StringLengthExp, SizeInBits,
    888                      AlignInBits, Encoding))
    889 
    890   TempDIStringType clone() const { return cloneImpl(); }
    891 
    892   static bool classof(const Metadata *MD) {
    893     return MD->getMetadataID() == DIStringTypeKind;
    894   }
    895 
    896   DIVariable *getStringLength() const {
    897     return cast_or_null<DIVariable>(getRawStringLength());
    898   }
    899 
    900   DIExpression *getStringLengthExp() const {
    901     return cast_or_null<DIExpression>(getRawStringLengthExp());
    902   }
    903 
    904   unsigned getEncoding() const { return Encoding; }
    905 
    906   Metadata *getRawStringLength() const { return getOperand(3); }
    907 
    908   Metadata *getRawStringLengthExp() const { return getOperand(4); }
    909 };
    910 
    911 /// Derived types.
    912 ///
    913 /// This includes qualified types, pointers, references, friends, typedefs, and
    914 /// class members.
    915 ///
    916 /// TODO: Split out members (inheritance, fields, methods, etc.).
    917 class DIDerivedType : public DIType {
    918   friend class LLVMContextImpl;
    919   friend class MDNode;
    920 
    921   /// The DWARF address space of the memory pointed to or referenced by a
    922   /// pointer or reference type respectively.
    923   Optional<unsigned> DWARFAddressSpace;
    924 
    925   DIDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
    926                 unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
    927                 uint64_t OffsetInBits, Optional<unsigned> DWARFAddressSpace,
    928                 DIFlags Flags, ArrayRef<Metadata *> Ops)
    929       : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, SizeInBits,
    930                AlignInBits, OffsetInBits, Flags, Ops),
    931         DWARFAddressSpace(DWARFAddressSpace) {}
    932   ~DIDerivedType() = default;
    933 
    934   static DIDerivedType *
    935   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, DIFile *File,
    936           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
    937           uint32_t AlignInBits, uint64_t OffsetInBits,
    938           Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
    939           Metadata *ExtraData, StorageType Storage, bool ShouldCreate = true) {
    940     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
    941                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
    942                    DWARFAddressSpace, Flags, ExtraData, Storage, ShouldCreate);
    943   }
    944   static DIDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
    945                                 MDString *Name, Metadata *File, unsigned Line,
    946                                 Metadata *Scope, Metadata *BaseType,
    947                                 uint64_t SizeInBits, uint32_t AlignInBits,
    948                                 uint64_t OffsetInBits,
    949                                 Optional<unsigned> DWARFAddressSpace,
    950                                 DIFlags Flags, Metadata *ExtraData,
    951                                 StorageType Storage, bool ShouldCreate = true);
    952 
    953   TempDIDerivedType cloneImpl() const {
    954     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
    955                         getScope(), getBaseType(), getSizeInBits(),
    956                         getAlignInBits(), getOffsetInBits(),
    957                         getDWARFAddressSpace(), getFlags(), getExtraData());
    958   }
    959 
    960 public:
    961   DEFINE_MDNODE_GET(DIDerivedType,
    962                     (unsigned Tag, MDString *Name, Metadata *File,
    963                      unsigned Line, Metadata *Scope, Metadata *BaseType,
    964                      uint64_t SizeInBits, uint32_t AlignInBits,
    965                      uint64_t OffsetInBits,
    966                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
    967                      Metadata *ExtraData = nullptr),
    968                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
    969                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
    970                      ExtraData))
    971   DEFINE_MDNODE_GET(DIDerivedType,
    972                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
    973                      DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
    974                      uint32_t AlignInBits, uint64_t OffsetInBits,
    975                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
    976                      Metadata *ExtraData = nullptr),
    977                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
    978                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
    979                      ExtraData))
    980 
    981   TempDIDerivedType clone() const { return cloneImpl(); }
    982 
    983   /// Get the base type this is derived from.
    984   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
    985   Metadata *getRawBaseType() const { return getOperand(3); }
    986 
    987   /// \returns The DWARF address space of the memory pointed to or referenced by
    988   /// a pointer or reference type respectively.
    989   Optional<unsigned> getDWARFAddressSpace() const { return DWARFAddressSpace; }
    990 
    991   /// Get extra data associated with this derived type.
    992   ///
    993   /// Class type for pointer-to-members, objective-c property node for ivars,
    994   /// global constant wrapper for static members, or virtual base pointer offset
    995   /// for inheritance.
    996   ///
    997   /// TODO: Separate out types that need this extra operand: pointer-to-member
    998   /// types and member fields (static members and ivars).
    999   Metadata *getExtraData() const { return getRawExtraData(); }
   1000   Metadata *getRawExtraData() const { return getOperand(4); }
   1001 
   1002   /// Get casted version of extra data.
   1003   /// @{
   1004   DIType *getClassType() const {
   1005     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
   1006     return cast_or_null<DIType>(getExtraData());
   1007   }
   1008 
   1009   DIObjCProperty *getObjCProperty() const {
   1010     return dyn_cast_or_null<DIObjCProperty>(getExtraData());
   1011   }
   1012 
   1013   uint32_t getVBPtrOffset() const {
   1014     assert(getTag() == dwarf::DW_TAG_inheritance);
   1015     if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
   1016       if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
   1017         return static_cast<uint32_t>(CI->getZExtValue());
   1018     return 0;
   1019   }
   1020 
   1021   Constant *getStorageOffsetInBits() const {
   1022     assert(getTag() == dwarf::DW_TAG_member && isBitField());
   1023     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
   1024       return C->getValue();
   1025     return nullptr;
   1026   }
   1027 
   1028   Constant *getConstant() const {
   1029     assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
   1030     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
   1031       return C->getValue();
   1032     return nullptr;
   1033   }
   1034   Constant *getDiscriminantValue() const {
   1035     assert(getTag() == dwarf::DW_TAG_member && !isStaticMember());
   1036     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
   1037       return C->getValue();
   1038     return nullptr;
   1039   }
   1040   /// @}
   1041 
   1042   static bool classof(const Metadata *MD) {
   1043     return MD->getMetadataID() == DIDerivedTypeKind;
   1044   }
   1045 };
   1046 
   1047 /// Composite types.
   1048 ///
   1049 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
   1050 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
   1051 class DICompositeType : public DIType {
   1052   friend class LLVMContextImpl;
   1053   friend class MDNode;
   1054 
   1055   unsigned RuntimeLang;
   1056 
   1057   DICompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
   1058                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
   1059                   uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
   1060                   ArrayRef<Metadata *> Ops)
   1061       : DIType(C, DICompositeTypeKind, Storage, Tag, Line, SizeInBits,
   1062                AlignInBits, OffsetInBits, Flags, Ops),
   1063         RuntimeLang(RuntimeLang) {}
   1064   ~DICompositeType() = default;
   1065 
   1066   /// Change fields in place.
   1067   void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
   1068               uint64_t SizeInBits, uint32_t AlignInBits,
   1069               uint64_t OffsetInBits, DIFlags Flags) {
   1070     assert(isDistinct() && "Only distinct nodes can mutate");
   1071     assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
   1072     this->RuntimeLang = RuntimeLang;
   1073     DIType::mutate(Tag, Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
   1074   }
   1075 
   1076   static DICompositeType *
   1077   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
   1078           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
   1079           uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
   1080           DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
   1081           DITemplateParameterArray TemplateParams, StringRef Identifier,
   1082           DIDerivedType *Discriminator, Metadata *DataLocation,
   1083           Metadata *Associated, Metadata *Allocated, Metadata *Rank,
   1084           StorageType Storage, bool ShouldCreate = true) {
   1085     return getImpl(
   1086         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
   1087         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
   1088         RuntimeLang, VTableHolder, TemplateParams.get(),
   1089         getCanonicalMDString(Context, Identifier), Discriminator, DataLocation,
   1090         Associated, Allocated, Rank, Storage, ShouldCreate);
   1091   }
   1092   static DICompositeType *
   1093   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
   1094           unsigned Line, Metadata *Scope, Metadata *BaseType,
   1095           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
   1096           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
   1097           Metadata *VTableHolder, Metadata *TemplateParams,
   1098           MDString *Identifier, Metadata *Discriminator, Metadata *DataLocation,
   1099           Metadata *Associated, Metadata *Allocated, Metadata *Rank,
   1100           StorageType Storage, bool ShouldCreate = true);
   1101 
   1102   TempDICompositeType cloneImpl() const {
   1103     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
   1104                         getScope(), getBaseType(), getSizeInBits(),
   1105                         getAlignInBits(), getOffsetInBits(), getFlags(),
   1106                         getElements(), getRuntimeLang(), getVTableHolder(),
   1107                         getTemplateParams(), getIdentifier(),
   1108                         getDiscriminator(), getRawDataLocation(),
   1109                         getRawAssociated(), getRawAllocated(), getRawRank());
   1110   }
   1111 
   1112 public:
   1113   DEFINE_MDNODE_GET(
   1114       DICompositeType,
   1115       (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
   1116        DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
   1117        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
   1118        DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
   1119        DITemplateParameterArray TemplateParams = nullptr,
   1120        StringRef Identifier = "", DIDerivedType *Discriminator = nullptr,
   1121        Metadata *DataLocation = nullptr, Metadata *Associated = nullptr,
   1122        Metadata *Allocated = nullptr, Metadata *Rank = nullptr),
   1123       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
   1124        OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
   1125        Identifier, Discriminator, DataLocation, Associated, Allocated, Rank))
   1126   DEFINE_MDNODE_GET(
   1127       DICompositeType,
   1128       (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
   1129        Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
   1130        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
   1131        Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
   1132        Metadata *TemplateParams = nullptr, MDString *Identifier = nullptr,
   1133        Metadata *Discriminator = nullptr, Metadata *DataLocation = nullptr,
   1134        Metadata *Associated = nullptr, Metadata *Allocated = nullptr,
   1135        Metadata *Rank = nullptr),
   1136       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
   1137        OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
   1138        Identifier, Discriminator, DataLocation, Associated, Allocated, Rank))
   1139 
   1140   TempDICompositeType clone() const { return cloneImpl(); }
   1141 
   1142   /// Get a DICompositeType with the given ODR identifier.
   1143   ///
   1144   /// If \a LLVMContext::isODRUniquingDebugTypes(), gets the mapped
   1145   /// DICompositeType for the given ODR \c Identifier.  If none exists, creates
   1146   /// a new node.
   1147   ///
   1148   /// Else, returns \c nullptr.
   1149   static DICompositeType *
   1150   getODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
   1151              MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
   1152              Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
   1153              uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
   1154              unsigned RuntimeLang, Metadata *VTableHolder,
   1155              Metadata *TemplateParams, Metadata *Discriminator,
   1156              Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
   1157              Metadata *Rank);
   1158   static DICompositeType *getODRTypeIfExists(LLVMContext &Context,
   1159                                              MDString &Identifier);
   1160 
   1161   /// Build a DICompositeType with the given ODR identifier.
   1162   ///
   1163   /// Looks up the mapped DICompositeType for the given ODR \c Identifier.  If
   1164   /// it doesn't exist, creates a new one.  If it does exist and \a
   1165   /// isForwardDecl(), and the new arguments would be a definition, mutates the
   1166   /// the type in place.  In either case, returns the type.
   1167   ///
   1168   /// If not \a LLVMContext::isODRUniquingDebugTypes(), this function returns
   1169   /// nullptr.
   1170   static DICompositeType *
   1171   buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
   1172                MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
   1173                Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
   1174                uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
   1175                unsigned RuntimeLang, Metadata *VTableHolder,
   1176                Metadata *TemplateParams, Metadata *Discriminator,
   1177                Metadata *DataLocation, Metadata *Associated,
   1178                Metadata *Allocated, Metadata *Rank);
   1179 
   1180   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
   1181   DINodeArray getElements() const {
   1182     return cast_or_null<MDTuple>(getRawElements());
   1183   }
   1184   DIType *getVTableHolder() const {
   1185     return cast_or_null<DIType>(getRawVTableHolder());
   1186   }
   1187   DITemplateParameterArray getTemplateParams() const {
   1188     return cast_or_null<MDTuple>(getRawTemplateParams());
   1189   }
   1190   StringRef getIdentifier() const { return getStringOperand(7); }
   1191   unsigned getRuntimeLang() const { return RuntimeLang; }
   1192 
   1193   Metadata *getRawBaseType() const { return getOperand(3); }
   1194   Metadata *getRawElements() const { return getOperand(4); }
   1195   Metadata *getRawVTableHolder() const { return getOperand(5); }
   1196   Metadata *getRawTemplateParams() const { return getOperand(6); }
   1197   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
   1198   Metadata *getRawDiscriminator() const { return getOperand(8); }
   1199   DIDerivedType *getDiscriminator() const { return getOperandAs<DIDerivedType>(8); }
   1200   Metadata *getRawDataLocation() const { return getOperand(9); }
   1201   DIVariable *getDataLocation() const {
   1202     return dyn_cast_or_null<DIVariable>(getRawDataLocation());
   1203   }
   1204   DIExpression *getDataLocationExp() const {
   1205     return dyn_cast_or_null<DIExpression>(getRawDataLocation());
   1206   }
   1207   Metadata *getRawAssociated() const { return getOperand(10); }
   1208   DIVariable *getAssociated() const {
   1209     return dyn_cast_or_null<DIVariable>(getRawAssociated());
   1210   }
   1211   DIExpression *getAssociatedExp() const {
   1212     return dyn_cast_or_null<DIExpression>(getRawAssociated());
   1213   }
   1214   Metadata *getRawAllocated() const { return getOperand(11); }
   1215   DIVariable *getAllocated() const {
   1216     return dyn_cast_or_null<DIVariable>(getRawAllocated());
   1217   }
   1218   DIExpression *getAllocatedExp() const {
   1219     return dyn_cast_or_null<DIExpression>(getRawAllocated());
   1220   }
   1221   Metadata *getRawRank() const { return getOperand(12); }
   1222   ConstantInt *getRankConst() const {
   1223     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawRank()))
   1224       return dyn_cast_or_null<ConstantInt>(MD->getValue());
   1225     return nullptr;
   1226   }
   1227   DIExpression *getRankExp() const {
   1228     return dyn_cast_or_null<DIExpression>(getRawRank());
   1229   }
   1230 
   1231   /// Replace operands.
   1232   ///
   1233   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
   1234   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
   1235   /// of its movement if necessary.
   1236   /// @{
   1237   void replaceElements(DINodeArray Elements) {
   1238 #ifndef NDEBUG
   1239     for (DINode *Op : getElements())
   1240       assert(is_contained(Elements->operands(), Op) &&
   1241              "Lost a member during member list replacement");
   1242 #endif
   1243     replaceOperandWith(4, Elements.get());
   1244   }
   1245 
   1246   void replaceVTableHolder(DIType *VTableHolder) {
   1247     replaceOperandWith(5, VTableHolder);
   1248   }
   1249 
   1250   void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
   1251     replaceOperandWith(6, TemplateParams.get());
   1252   }
   1253   /// @}
   1254 
   1255   static bool classof(const Metadata *MD) {
   1256     return MD->getMetadataID() == DICompositeTypeKind;
   1257   }
   1258 };
   1259 
   1260 /// Type array for a subprogram.
   1261 ///
   1262 /// TODO: Fold the array of types in directly as operands.
   1263 class DISubroutineType : public DIType {
   1264   friend class LLVMContextImpl;
   1265   friend class MDNode;
   1266 
   1267   /// The calling convention used with DW_AT_calling_convention. Actually of
   1268   /// type dwarf::CallingConvention.
   1269   uint8_t CC;
   1270 
   1271   DISubroutineType(LLVMContext &C, StorageType Storage, DIFlags Flags,
   1272                    uint8_t CC, ArrayRef<Metadata *> Ops)
   1273       : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type,
   1274                0, 0, 0, 0, Flags, Ops),
   1275         CC(CC) {}
   1276   ~DISubroutineType() = default;
   1277 
   1278   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
   1279                                    uint8_t CC, DITypeRefArray TypeArray,
   1280                                    StorageType Storage,
   1281                                    bool ShouldCreate = true) {
   1282     return getImpl(Context, Flags, CC, TypeArray.get(), Storage, ShouldCreate);
   1283   }
   1284   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
   1285                                    uint8_t CC, Metadata *TypeArray,
   1286                                    StorageType Storage,
   1287                                    bool ShouldCreate = true);
   1288 
   1289   TempDISubroutineType cloneImpl() const {
   1290     return getTemporary(getContext(), getFlags(), getCC(), getTypeArray());
   1291   }
   1292 
   1293 public:
   1294   DEFINE_MDNODE_GET(DISubroutineType,
   1295                     (DIFlags Flags, uint8_t CC, DITypeRefArray TypeArray),
   1296                     (Flags, CC, TypeArray))
   1297   DEFINE_MDNODE_GET(DISubroutineType,
   1298                     (DIFlags Flags, uint8_t CC, Metadata *TypeArray),
   1299                     (Flags, CC, TypeArray))
   1300 
   1301   TempDISubroutineType clone() const { return cloneImpl(); }
   1302 
   1303   uint8_t getCC() const { return CC; }
   1304 
   1305   DITypeRefArray getTypeArray() const {
   1306     return cast_or_null<MDTuple>(getRawTypeArray());
   1307   }
   1308 
   1309   Metadata *getRawTypeArray() const { return getOperand(3); }
   1310 
   1311   static bool classof(const Metadata *MD) {
   1312     return MD->getMetadataID() == DISubroutineTypeKind;
   1313   }
   1314 };
   1315 
   1316 /// Compile unit.
   1317 class DICompileUnit : public DIScope {
   1318   friend class LLVMContextImpl;
   1319   friend class MDNode;
   1320 
   1321 public:
   1322   enum DebugEmissionKind : unsigned {
   1323     NoDebug = 0,
   1324     FullDebug,
   1325     LineTablesOnly,
   1326     DebugDirectivesOnly,
   1327     LastEmissionKind = DebugDirectivesOnly
   1328   };
   1329 
   1330   enum class DebugNameTableKind : unsigned {
   1331     Default = 0,
   1332     GNU = 1,
   1333     None = 2,
   1334     LastDebugNameTableKind = None
   1335   };
   1336 
   1337   static Optional<DebugEmissionKind> getEmissionKind(StringRef Str);
   1338   static const char *emissionKindString(DebugEmissionKind EK);
   1339   static Optional<DebugNameTableKind> getNameTableKind(StringRef Str);
   1340   static const char *nameTableKindString(DebugNameTableKind PK);
   1341 
   1342 private:
   1343   unsigned SourceLanguage;
   1344   bool IsOptimized;
   1345   unsigned RuntimeVersion;
   1346   unsigned EmissionKind;
   1347   uint64_t DWOId;
   1348   bool SplitDebugInlining;
   1349   bool DebugInfoForProfiling;
   1350   unsigned NameTableKind;
   1351   bool RangesBaseAddress;
   1352 
   1353   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
   1354                 bool IsOptimized, unsigned RuntimeVersion,
   1355                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
   1356                 bool DebugInfoForProfiling, unsigned NameTableKind,
   1357                 bool RangesBaseAddress, ArrayRef<Metadata *> Ops)
   1358       : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
   1359         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
   1360         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind),
   1361         DWOId(DWOId), SplitDebugInlining(SplitDebugInlining),
   1362         DebugInfoForProfiling(DebugInfoForProfiling),
   1363         NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) {
   1364     assert(Storage != Uniqued);
   1365   }
   1366   ~DICompileUnit() = default;
   1367 
   1368   static DICompileUnit *
   1369   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
   1370           StringRef Producer, bool IsOptimized, StringRef Flags,
   1371           unsigned RuntimeVersion, StringRef SplitDebugFilename,
   1372           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
   1373           DIScopeArray RetainedTypes,
   1374           DIGlobalVariableExpressionArray GlobalVariables,
   1375           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
   1376           uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
   1377           unsigned NameTableKind, bool RangesBaseAddress, StringRef SysRoot,
   1378           StringRef SDK, StorageType Storage, bool ShouldCreate = true) {
   1379     return getImpl(
   1380         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
   1381         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
   1382         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
   1383         EnumTypes.get(), RetainedTypes.get(), GlobalVariables.get(),
   1384         ImportedEntities.get(), Macros.get(), DWOId, SplitDebugInlining,
   1385         DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
   1386         getCanonicalMDString(Context, SysRoot),
   1387         getCanonicalMDString(Context, SDK), Storage, ShouldCreate);
   1388   }
   1389   static DICompileUnit *
   1390   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
   1391           MDString *Producer, bool IsOptimized, MDString *Flags,
   1392           unsigned RuntimeVersion, MDString *SplitDebugFilename,
   1393           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
   1394           Metadata *GlobalVariables, Metadata *ImportedEntities,
   1395           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
   1396           bool DebugInfoForProfiling, unsigned NameTableKind,
   1397           bool RangesBaseAddress, MDString *SysRoot, MDString *SDK,
   1398           StorageType Storage, bool ShouldCreate = true);
   1399 
   1400   TempDICompileUnit cloneImpl() const {
   1401     return getTemporary(
   1402         getContext(), getSourceLanguage(), getFile(), getProducer(),
   1403         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
   1404         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
   1405         getGlobalVariables(), getImportedEntities(), getMacros(), DWOId,
   1406         getSplitDebugInlining(), getDebugInfoForProfiling(), getNameTableKind(),
   1407         getRangesBaseAddress(), getSysRoot(), getSDK());
   1408   }
   1409 
   1410 public:
   1411   static void get() = delete;
   1412   static void getIfExists() = delete;
   1413 
   1414   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
   1415       DICompileUnit,
   1416       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
   1417        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
   1418        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
   1419        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
   1420        DIGlobalVariableExpressionArray GlobalVariables,
   1421        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
   1422        uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
   1423        DebugNameTableKind NameTableKind, bool RangesBaseAddress,
   1424        StringRef SysRoot, StringRef SDK),
   1425       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
   1426        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
   1427        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
   1428        DebugInfoForProfiling, (unsigned)NameTableKind, RangesBaseAddress,
   1429        SysRoot, SDK))
   1430   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
   1431       DICompileUnit,
   1432       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
   1433        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
   1434        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
   1435        Metadata *RetainedTypes, Metadata *GlobalVariables,
   1436        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
   1437        bool SplitDebugInlining, bool DebugInfoForProfiling,
   1438        unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
   1439        MDString *SDK),
   1440       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
   1441        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
   1442        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
   1443        DebugInfoForProfiling, NameTableKind, RangesBaseAddress, SysRoot, SDK))
   1444 
   1445   TempDICompileUnit clone() const { return cloneImpl(); }
   1446 
   1447   unsigned getSourceLanguage() const { return SourceLanguage; }
   1448   bool isOptimized() const { return IsOptimized; }
   1449   unsigned getRuntimeVersion() const { return RuntimeVersion; }
   1450   DebugEmissionKind getEmissionKind() const {
   1451     return (DebugEmissionKind)EmissionKind;
   1452   }
   1453   bool isDebugDirectivesOnly() const {
   1454     return EmissionKind == DebugDirectivesOnly;
   1455   }
   1456   bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
   1457   DebugNameTableKind getNameTableKind() const {
   1458     return (DebugNameTableKind)NameTableKind;
   1459   }
   1460   bool getRangesBaseAddress() const { return RangesBaseAddress; }
   1461   StringRef getProducer() const { return getStringOperand(1); }
   1462   StringRef getFlags() const { return getStringOperand(2); }
   1463   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
   1464   DICompositeTypeArray getEnumTypes() const {
   1465     return cast_or_null<MDTuple>(getRawEnumTypes());
   1466   }
   1467   DIScopeArray getRetainedTypes() const {
   1468     return cast_or_null<MDTuple>(getRawRetainedTypes());
   1469   }
   1470   DIGlobalVariableExpressionArray getGlobalVariables() const {
   1471     return cast_or_null<MDTuple>(getRawGlobalVariables());
   1472   }
   1473   DIImportedEntityArray getImportedEntities() const {
   1474     return cast_or_null<MDTuple>(getRawImportedEntities());
   1475   }
   1476   DIMacroNodeArray getMacros() const {
   1477     return cast_or_null<MDTuple>(getRawMacros());
   1478   }
   1479   uint64_t getDWOId() const { return DWOId; }
   1480   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
   1481   bool getSplitDebugInlining() const { return SplitDebugInlining; }
   1482   void setSplitDebugInlining(bool SplitDebugInlining) {
   1483     this->SplitDebugInlining = SplitDebugInlining;
   1484   }
   1485   StringRef getSysRoot() const { return getStringOperand(9); }
   1486   StringRef getSDK() const { return getStringOperand(10); }
   1487 
   1488   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
   1489   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
   1490   MDString *getRawSplitDebugFilename() const {
   1491     return getOperandAs<MDString>(3);
   1492   }
   1493   Metadata *getRawEnumTypes() const { return getOperand(4); }
   1494   Metadata *getRawRetainedTypes() const { return getOperand(5); }
   1495   Metadata *getRawGlobalVariables() const { return getOperand(6); }
   1496   Metadata *getRawImportedEntities() const { return getOperand(7); }
   1497   Metadata *getRawMacros() const { return getOperand(8); }
   1498   MDString *getRawSysRoot() const { return getOperandAs<MDString>(9); }
   1499   MDString *getRawSDK() const { return getOperandAs<MDString>(10); }
   1500 
   1501   /// Replace arrays.
   1502   ///
   1503   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
   1504   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
   1505   /// DICompileUnit should be fairly rare.
   1506   /// @{
   1507   void replaceEnumTypes(DICompositeTypeArray N) {
   1508     replaceOperandWith(4, N.get());
   1509   }
   1510   void replaceRetainedTypes(DITypeArray N) {
   1511     replaceOperandWith(5, N.get());
   1512   }
   1513   void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
   1514     replaceOperandWith(6, N.get());
   1515   }
   1516   void replaceImportedEntities(DIImportedEntityArray N) {
   1517     replaceOperandWith(7, N.get());
   1518   }
   1519   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
   1520   /// @}
   1521 
   1522   static bool classof(const Metadata *MD) {
   1523     return MD->getMetadataID() == DICompileUnitKind;
   1524   }
   1525 };
   1526 
   1527 /// A scope for locals.
   1528 ///
   1529 /// A legal scope for lexical blocks, local variables, and debug info
   1530 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
   1531 /// DILexicalBlockFile.
   1532 class DILocalScope : public DIScope {
   1533 protected:
   1534   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
   1535                ArrayRef<Metadata *> Ops)
   1536       : DIScope(C, ID, Storage, Tag, Ops) {}
   1537   ~DILocalScope() = default;
   1538 
   1539 public:
   1540   /// Get the subprogram for this scope.
   1541   ///
   1542   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
   1543   /// chain.
   1544   DISubprogram *getSubprogram() const;
   1545 
   1546   /// Get the first non DILexicalBlockFile scope of this scope.
   1547   ///
   1548   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
   1549   /// scope chain.
   1550   DILocalScope *getNonLexicalBlockFileScope() const;
   1551 
   1552   static bool classof(const Metadata *MD) {
   1553     return MD->getMetadataID() == DISubprogramKind ||
   1554            MD->getMetadataID() == DILexicalBlockKind ||
   1555            MD->getMetadataID() == DILexicalBlockFileKind;
   1556   }
   1557 };
   1558 
   1559 /// Debug location.
   1560 ///
   1561 /// A debug location in source code, used for debug info and otherwise.
   1562 class DILocation : public MDNode {
   1563   friend class LLVMContextImpl;
   1564   friend class MDNode;
   1565 
   1566   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
   1567              unsigned Column, ArrayRef<Metadata *> MDs, bool ImplicitCode);
   1568   ~DILocation() { dropAllReferences(); }
   1569 
   1570   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
   1571                              unsigned Column, Metadata *Scope,
   1572                              Metadata *InlinedAt, bool ImplicitCode,
   1573                              StorageType Storage, bool ShouldCreate = true);
   1574   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
   1575                              unsigned Column, DILocalScope *Scope,
   1576                              DILocation *InlinedAt, bool ImplicitCode,
   1577                              StorageType Storage, bool ShouldCreate = true) {
   1578     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
   1579                    static_cast<Metadata *>(InlinedAt), ImplicitCode, Storage,
   1580                    ShouldCreate);
   1581   }
   1582 
   1583   TempDILocation cloneImpl() const {
   1584     // Get the raw scope/inlinedAt since it is possible to invoke this on
   1585     // a DILocation containing temporary metadata.
   1586     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
   1587                         getRawInlinedAt(), isImplicitCode());
   1588   }
   1589 
   1590 public:
   1591   // Disallow replacing operands.
   1592   void replaceOperandWith(unsigned I, Metadata *New) = delete;
   1593 
   1594   DEFINE_MDNODE_GET(DILocation,
   1595                     (unsigned Line, unsigned Column, Metadata *Scope,
   1596                      Metadata *InlinedAt = nullptr, bool ImplicitCode = false),
   1597                     (Line, Column, Scope, InlinedAt, ImplicitCode))
   1598   DEFINE_MDNODE_GET(DILocation,
   1599                     (unsigned Line, unsigned Column, DILocalScope *Scope,
   1600                      DILocation *InlinedAt = nullptr,
   1601                      bool ImplicitCode = false),
   1602                     (Line, Column, Scope, InlinedAt, ImplicitCode))
   1603 
   1604   /// Return a (temporary) clone of this.
   1605   TempDILocation clone() const { return cloneImpl(); }
   1606 
   1607   unsigned getLine() const { return SubclassData32; }
   1608   unsigned getColumn() const { return SubclassData16; }
   1609   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
   1610 
   1611   DILocation *getInlinedAt() const {
   1612     return cast_or_null<DILocation>(getRawInlinedAt());
   1613   }
   1614 
   1615   /// Check if the location corresponds to an implicit code.
   1616   /// When the ImplicitCode flag is true, it means that the Instruction
   1617   /// with this DILocation has been added by the front-end but it hasn't been
   1618   /// written explicitly by the user (e.g. cleanup stuff in C++ put on a closing
   1619   /// bracket). It's useful for code coverage to not show a counter on "empty"
   1620   /// lines.
   1621   bool isImplicitCode() const { return SubclassData1; }
   1622   void setImplicitCode(bool ImplicitCode) { SubclassData1 = ImplicitCode; }
   1623 
   1624   DIFile *getFile() const { return getScope()->getFile(); }
   1625   StringRef getFilename() const { return getScope()->getFilename(); }
   1626   StringRef getDirectory() const { return getScope()->getDirectory(); }
   1627   Optional<StringRef> getSource() const { return getScope()->getSource(); }
   1628 
   1629   /// Get the scope where this is inlined.
   1630   ///
   1631   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
   1632   /// location.
   1633   DILocalScope *getInlinedAtScope() const {
   1634     if (auto *IA = getInlinedAt())
   1635       return IA->getInlinedAtScope();
   1636     return getScope();
   1637   }
   1638 
   1639   /// Get the DWARF discriminator.
   1640   ///
   1641   /// DWARF discriminators distinguish identical file locations between
   1642   /// instructions that are on different basic blocks.
   1643   ///
   1644   /// There are 3 components stored in discriminator, from lower bits:
   1645   ///
   1646   /// Base discriminator: assigned by AddDiscriminators pass to identify IRs
   1647   ///                     that are defined by the same source line, but
   1648   ///                     different basic blocks.
   1649   /// Duplication factor: assigned by optimizations that will scale down
   1650   ///                     the execution frequency of the original IR.
   1651   /// Copy Identifier: assigned by optimizations that clones the IR.
   1652   ///                  Each copy of the IR will be assigned an identifier.
   1653   ///
   1654   /// Encoding:
   1655   ///
   1656   /// The above 3 components are encoded into a 32bit unsigned integer in
   1657   /// order. If the lowest bit is 1, the current component is empty, and the
   1658   /// next component will start in the next bit. Otherwise, the current
   1659   /// component is non-empty, and its content starts in the next bit. The
   1660   /// value of each components is either 5 bit or 12 bit: if the 7th bit
   1661   /// is 0, the bit 2~6 (5 bits) are used to represent the component; if the
   1662   /// 7th bit is 1, the bit 2~6 (5 bits) and 8~14 (7 bits) are combined to
   1663   /// represent the component. Thus, the number of bits used for a component
   1664   /// is either 0 (if it and all the next components are empty); 1 - if it is
   1665   /// empty; 7 - if its value is up to and including 0x1f (lsb and msb are both
   1666   /// 0); or 14, if its value is up to and including 0x1ff. Note that the last
   1667   /// component is also capped at 0x1ff, even in the case when both first
   1668   /// components are 0, and we'd technically have 29 bits available.
   1669   ///
   1670   /// For precise control over the data being encoded in the discriminator,
   1671   /// use encodeDiscriminator/decodeDiscriminator.
   1672 
   1673   inline unsigned getDiscriminator() const;
   1674 
   1675   // For the regular discriminator, it stands for all empty components if all
   1676   // the lowest 3 bits are non-zero and all higher 29 bits are unused(zero by
   1677   // default). Here we fully leverage the higher 29 bits for pseudo probe use.
   1678   // This is the format:
   1679   // [2:0] - 0x7
   1680   // [31:3] - pseudo probe fields guaranteed to be non-zero as a whole
   1681   // So if the lower 3 bits is non-zero and the others has at least one
   1682   // non-zero bit, it guarantees to be a pseudo probe discriminator
   1683   inline static bool isPseudoProbeDiscriminator(unsigned Discriminator) {
   1684     return ((Discriminator & 0x7) == 0x7) && (Discriminator & 0xFFFFFFF8);
   1685   }
   1686 
   1687   /// Returns a new DILocation with updated \p Discriminator.
   1688   inline const DILocation *cloneWithDiscriminator(unsigned Discriminator) const;
   1689 
   1690   /// Returns a new DILocation with updated base discriminator \p BD. Only the
   1691   /// base discriminator is set in the new DILocation, the other encoded values
   1692   /// are elided.
   1693   /// If the discriminator cannot be encoded, the function returns None.
   1694   inline Optional<const DILocation *> cloneWithBaseDiscriminator(unsigned BD) const;
   1695 
   1696   /// Returns the duplication factor stored in the discriminator, or 1 if no
   1697   /// duplication factor (or 0) is encoded.
   1698   inline unsigned getDuplicationFactor() const;
   1699 
   1700   /// Returns the copy identifier stored in the discriminator.
   1701   inline unsigned getCopyIdentifier() const;
   1702 
   1703   /// Returns the base discriminator stored in the discriminator.
   1704   inline unsigned getBaseDiscriminator() const;
   1705 
   1706   /// Returns a new DILocation with duplication factor \p DF * current
   1707   /// duplication factor encoded in the discriminator. The current duplication
   1708   /// factor is as defined by getDuplicationFactor().
   1709   /// Returns None if encoding failed.
   1710   inline Optional<const DILocation *> cloneByMultiplyingDuplicationFactor(unsigned DF) const;
   1711 
   1712   /// When two instructions are combined into a single instruction we also
   1713   /// need to combine the original locations into a single location.
   1714   ///
   1715   /// When the locations are the same we can use either location. When they
   1716   /// differ, we need a third location which is distinct from either. If they
   1717   /// have the same file/line but have a different discriminator we could
   1718   /// create a location with a new discriminator. If they are from different
   1719   /// files/lines the location is ambiguous and can't be represented in a line
   1720   /// entry. In this case, if \p GenerateLocation is true, we will set the
   1721   /// merged debug location as line 0 of the nearest common scope where the two
   1722   /// locations are inlined from.
   1723   ///
   1724   /// \p GenerateLocation: Whether the merged location can be generated when
   1725   /// \p LocA and \p LocB differ.
   1726   static const DILocation *getMergedLocation(const DILocation *LocA,
   1727                                              const DILocation *LocB);
   1728 
   1729   /// Try to combine the vector of locations passed as input in a single one.
   1730   /// This function applies getMergedLocation() repeatedly left-to-right.
   1731   ///
   1732   /// \p Locs: The locations to be merged.
   1733   static
   1734   const DILocation *getMergedLocations(ArrayRef<const DILocation *> Locs);
   1735 
   1736   /// Return the masked discriminator value for an input discrimnator value D
   1737   /// (i.e. zero out the (B+1)-th and above bits for D (B is 0-base).
   1738   // Example: an input of (0x1FF, 7) returns 0xFF.
   1739   static unsigned getMaskedDiscriminator(unsigned D, unsigned B) {
   1740     return (D & getN1Bits(B));
   1741   }
   1742 
   1743   /// Return the bits used for base discriminators.
   1744   static unsigned getBaseDiscriminatorBits() { return BASE_DIS_BIT_END; }
   1745 
   1746   /// Returns the base discriminator for a given encoded discriminator \p D.
   1747   static unsigned getBaseDiscriminatorFromDiscriminator(unsigned D) {
   1748     if (EnableFSDiscriminator)
   1749       return getMaskedDiscriminator(D, getBaseDiscriminatorBits());
   1750     return getUnsignedFromPrefixEncoding(D);
   1751   }
   1752 
   1753   /// Raw encoding of the discriminator. APIs such as cloneWithDuplicationFactor
   1754   /// have certain special case behavior (e.g. treating empty duplication factor
   1755   /// as the value '1').
   1756   /// This API, in conjunction with cloneWithDiscriminator, may be used to encode
   1757   /// the raw values provided. \p BD: base discriminator \p DF: duplication factor
   1758   /// \p CI: copy index
   1759   /// The return is None if the values cannot be encoded in 32 bits - for
   1760   /// example, values for BD or DF larger than 12 bits. Otherwise, the return
   1761   /// is the encoded value.
   1762   static Optional<unsigned> encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI);
   1763 
   1764   /// Raw decoder for values in an encoded discriminator D.
   1765   static void decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
   1766                                   unsigned &CI);
   1767 
   1768   /// Returns the duplication factor for a given encoded discriminator \p D, or
   1769   /// 1 if no value or 0 is encoded.
   1770   static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
   1771     if (EnableFSDiscriminator)
   1772       return 1;
   1773     D = getNextComponentInDiscriminator(D);
   1774     unsigned Ret = getUnsignedFromPrefixEncoding(D);
   1775     if (Ret == 0)
   1776       return 1;
   1777     return Ret;
   1778   }
   1779 
   1780   /// Returns the copy identifier for a given encoded discriminator \p D.
   1781   static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
   1782     return getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(
   1783         getNextComponentInDiscriminator(D)));
   1784   }
   1785 
   1786 
   1787   Metadata *getRawScope() const { return getOperand(0); }
   1788   Metadata *getRawInlinedAt() const {
   1789     if (getNumOperands() == 2)
   1790       return getOperand(1);
   1791     return nullptr;
   1792   }
   1793 
   1794   static bool classof(const Metadata *MD) {
   1795     return MD->getMetadataID() == DILocationKind;
   1796   }
   1797 };
   1798 
   1799 /// Subprogram description.
   1800 class DISubprogram : public DILocalScope {
   1801   friend class LLVMContextImpl;
   1802   friend class MDNode;
   1803 
   1804   unsigned Line;
   1805   unsigned ScopeLine;
   1806   unsigned VirtualIndex;
   1807 
   1808   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
   1809   /// of method overrides from secondary bases by this amount. It may be
   1810   /// negative.
   1811   int ThisAdjustment;
   1812 
   1813 public:
   1814   /// Debug info subprogram flags.
   1815   enum DISPFlags : uint32_t {
   1816 #define HANDLE_DISP_FLAG(ID, NAME) SPFlag##NAME = ID,
   1817 #define DISP_FLAG_LARGEST_NEEDED
   1818 #include "llvm/IR/DebugInfoFlags.def"
   1819     SPFlagNonvirtual = SPFlagZero,
   1820     SPFlagVirtuality = SPFlagVirtual | SPFlagPureVirtual,
   1821     LLVM_MARK_AS_BITMASK_ENUM(SPFlagLargest)
   1822   };
   1823 
   1824   static DISPFlags getFlag(StringRef Flag);
   1825   static StringRef getFlagString(DISPFlags Flag);
   1826 
   1827   /// Split up a flags bitfield for easier printing.
   1828   ///
   1829   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
   1830   /// any remaining (unrecognized) bits.
   1831   static DISPFlags splitFlags(DISPFlags Flags,
   1832                               SmallVectorImpl<DISPFlags> &SplitFlags);
   1833 
   1834   // Helper for converting old bitfields to new flags word.
   1835   static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition,
   1836                              bool IsOptimized,
   1837                              unsigned Virtuality = SPFlagNonvirtual,
   1838                              bool IsMainSubprogram = false) {
   1839     // We're assuming virtuality is the low-order field.
   1840     static_assert(
   1841         int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) &&
   1842             int(SPFlagPureVirtual) == int(dwarf::DW_VIRTUALITY_pure_virtual),
   1843         "Virtuality constant mismatch");
   1844     return static_cast<DISPFlags>(
   1845         (Virtuality & SPFlagVirtuality) |
   1846         (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) |
   1847         (IsDefinition ? SPFlagDefinition : SPFlagZero) |
   1848         (IsOptimized ? SPFlagOptimized : SPFlagZero) |
   1849         (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero));
   1850   }
   1851 
   1852 private:
   1853   DIFlags Flags;
   1854   DISPFlags SPFlags;
   1855 
   1856   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
   1857                unsigned ScopeLine, unsigned VirtualIndex, int ThisAdjustment,
   1858                DIFlags Flags, DISPFlags SPFlags, ArrayRef<Metadata *> Ops)
   1859       : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram,
   1860                      Ops),
   1861         Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
   1862         ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) {
   1863     static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
   1864   }
   1865   ~DISubprogram() = default;
   1866 
   1867   static DISubprogram *
   1868   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
   1869           StringRef LinkageName, DIFile *File, unsigned Line,
   1870           DISubroutineType *Type, unsigned ScopeLine, DIType *ContainingType,
   1871           unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
   1872           DISPFlags SPFlags, DICompileUnit *Unit,
   1873           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
   1874           DINodeArray RetainedNodes, DITypeArray ThrownTypes,
   1875           StorageType Storage, bool ShouldCreate = true) {
   1876     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
   1877                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
   1878                    ScopeLine, ContainingType, VirtualIndex, ThisAdjustment,
   1879                    Flags, SPFlags, Unit, TemplateParams.get(), Declaration,
   1880                    RetainedNodes.get(), ThrownTypes.get(), Storage,
   1881                    ShouldCreate);
   1882   }
   1883   static DISubprogram *getImpl(LLVMContext &Context, Metadata *Scope,
   1884                                MDString *Name, MDString *LinkageName,
   1885                                Metadata *File, unsigned Line, Metadata *Type,
   1886                                unsigned ScopeLine, Metadata *ContainingType,
   1887                                unsigned VirtualIndex, int ThisAdjustment,
   1888                                DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
   1889                                Metadata *TemplateParams, Metadata *Declaration,
   1890                                Metadata *RetainedNodes, Metadata *ThrownTypes,
   1891                                StorageType Storage, bool ShouldCreate = true);
   1892 
   1893   TempDISubprogram cloneImpl() const {
   1894     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
   1895                         getFile(), getLine(), getType(), getScopeLine(),
   1896                         getContainingType(), getVirtualIndex(),
   1897                         getThisAdjustment(), getFlags(), getSPFlags(),
   1898                         getUnit(), getTemplateParams(), getDeclaration(),
   1899                         getRetainedNodes(), getThrownTypes());
   1900   }
   1901 
   1902 public:
   1903   DEFINE_MDNODE_GET(
   1904       DISubprogram,
   1905       (DIScope * Scope, StringRef Name, StringRef LinkageName, DIFile *File,
   1906        unsigned Line, DISubroutineType *Type, unsigned ScopeLine,
   1907        DIType *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
   1908        DIFlags Flags, DISPFlags SPFlags, DICompileUnit *Unit,
   1909        DITemplateParameterArray TemplateParams = nullptr,
   1910        DISubprogram *Declaration = nullptr, DINodeArray RetainedNodes = nullptr,
   1911        DITypeArray ThrownTypes = nullptr),
   1912       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
   1913        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
   1914        Declaration, RetainedNodes, ThrownTypes))
   1915 
   1916   DEFINE_MDNODE_GET(
   1917       DISubprogram,
   1918       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
   1919        unsigned Line, Metadata *Type, unsigned ScopeLine,
   1920        Metadata *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
   1921        DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
   1922        Metadata *TemplateParams = nullptr, Metadata *Declaration = nullptr,
   1923        Metadata *RetainedNodes = nullptr, Metadata *ThrownTypes = nullptr),
   1924       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
   1925        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
   1926        Declaration, RetainedNodes, ThrownTypes))
   1927 
   1928   TempDISubprogram clone() const { return cloneImpl(); }
   1929 
   1930   /// Returns a new temporary DISubprogram with updated Flags
   1931   TempDISubprogram cloneWithFlags(DIFlags NewFlags) const {
   1932     auto NewSP = clone();
   1933     NewSP->Flags = NewFlags;
   1934     return NewSP;
   1935   }
   1936 
   1937 public:
   1938   unsigned getLine() const { return Line; }
   1939   unsigned getVirtuality() const { return getSPFlags() & SPFlagVirtuality; }
   1940   unsigned getVirtualIndex() const { return VirtualIndex; }
   1941   int getThisAdjustment() const { return ThisAdjustment; }
   1942   unsigned getScopeLine() const { return ScopeLine; }
   1943   void setScopeLine(unsigned L) { assert(isDistinct()); ScopeLine = L; }
   1944   DIFlags getFlags() const { return Flags; }
   1945   DISPFlags getSPFlags() const { return SPFlags; }
   1946   bool isLocalToUnit() const { return getSPFlags() & SPFlagLocalToUnit; }
   1947   bool isDefinition() const { return getSPFlags() & SPFlagDefinition; }
   1948   bool isOptimized() const { return getSPFlags() & SPFlagOptimized; }
   1949   bool isMainSubprogram() const { return getSPFlags() & SPFlagMainSubprogram; }
   1950 
   1951   bool isArtificial() const { return getFlags() & FlagArtificial; }
   1952   bool isPrivate() const {
   1953     return (getFlags() & FlagAccessibility) == FlagPrivate;
   1954   }
   1955   bool isProtected() const {
   1956     return (getFlags() & FlagAccessibility) == FlagProtected;
   1957   }
   1958   bool isPublic() const {
   1959     return (getFlags() & FlagAccessibility) == FlagPublic;
   1960   }
   1961   bool isExplicit() const { return getFlags() & FlagExplicit; }
   1962   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
   1963   bool areAllCallsDescribed() const {
   1964     return getFlags() & FlagAllCallsDescribed;
   1965   }
   1966   bool isPure() const { return getSPFlags() & SPFlagPure; }
   1967   bool isElemental() const { return getSPFlags() & SPFlagElemental; }
   1968   bool isRecursive() const { return getSPFlags() & SPFlagRecursive; }
   1969   bool isObjCDirect() const { return getSPFlags() & SPFlagObjCDirect; }
   1970 
   1971   /// Check if this is deleted member function.
   1972   ///
   1973   /// Return true if this subprogram is a C++11 special
   1974   /// member function declared deleted.
   1975   bool isDeleted() const { return getSPFlags() & SPFlagDeleted; }
   1976 
   1977   /// Check if this is reference-qualified.
   1978   ///
   1979   /// Return true if this subprogram is a C++11 reference-qualified non-static
   1980   /// member function (void foo() &).
   1981   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
   1982 
   1983   /// Check if this is rvalue-reference-qualified.
   1984   ///
   1985   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
   1986   /// non-static member function (void foo() &&).
   1987   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
   1988 
   1989   /// Check if this is marked as noreturn.
   1990   ///
   1991   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
   1992   bool isNoReturn() const { return getFlags() & FlagNoReturn; }
   1993 
   1994   // Check if this routine is a compiler-generated thunk.
   1995   //
   1996   // Returns true if this subprogram is a thunk generated by the compiler.
   1997   bool isThunk() const { return getFlags() & FlagThunk; }
   1998 
   1999   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   2000 
   2001   StringRef getName() const { return getStringOperand(2); }
   2002   StringRef getLinkageName() const { return getStringOperand(3); }
   2003   /// Only used by clients of CloneFunction, and only right after the cloning.
   2004   void replaceLinkageName(MDString *LN) { replaceOperandWith(3, LN); }
   2005 
   2006   DISubroutineType *getType() const {
   2007     return cast_or_null<DISubroutineType>(getRawType());
   2008   }
   2009   DIType *getContainingType() const {
   2010     return cast_or_null<DIType>(getRawContainingType());
   2011   }
   2012 
   2013   DICompileUnit *getUnit() const {
   2014     return cast_or_null<DICompileUnit>(getRawUnit());
   2015   }
   2016   void replaceUnit(DICompileUnit *CU) { replaceOperandWith(5, CU); }
   2017   DITemplateParameterArray getTemplateParams() const {
   2018     return cast_or_null<MDTuple>(getRawTemplateParams());
   2019   }
   2020   DISubprogram *getDeclaration() const {
   2021     return cast_or_null<DISubprogram>(getRawDeclaration());
   2022   }
   2023   DINodeArray getRetainedNodes() const {
   2024     return cast_or_null<MDTuple>(getRawRetainedNodes());
   2025   }
   2026   DITypeArray getThrownTypes() const {
   2027     return cast_or_null<MDTuple>(getRawThrownTypes());
   2028   }
   2029 
   2030   Metadata *getRawScope() const { return getOperand(1); }
   2031   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   2032   MDString *getRawLinkageName() const { return getOperandAs<MDString>(3); }
   2033   Metadata *getRawType() const { return getOperand(4); }
   2034   Metadata *getRawUnit() const { return getOperand(5); }
   2035   Metadata *getRawDeclaration() const { return getOperand(6); }
   2036   Metadata *getRawRetainedNodes() const { return getOperand(7); }
   2037   Metadata *getRawContainingType() const {
   2038     return getNumOperands() > 8 ? getOperandAs<Metadata>(8) : nullptr;
   2039   }
   2040   Metadata *getRawTemplateParams() const {
   2041     return getNumOperands() > 9 ? getOperandAs<Metadata>(9) : nullptr;
   2042   }
   2043   Metadata *getRawThrownTypes() const {
   2044     return getNumOperands() > 10 ? getOperandAs<Metadata>(10) : nullptr;
   2045   }
   2046 
   2047   void replaceRawLinkageName(MDString *LinkageName) {
   2048     replaceOperandWith(3, LinkageName);
   2049   }
   2050 
   2051   /// Check if this subprogram describes the given function.
   2052   ///
   2053   /// FIXME: Should this be looking through bitcasts?
   2054   bool describes(const Function *F) const;
   2055 
   2056   static bool classof(const Metadata *MD) {
   2057     return MD->getMetadataID() == DISubprogramKind;
   2058   }
   2059 };
   2060 
   2061 class DILexicalBlockBase : public DILocalScope {
   2062 protected:
   2063   DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
   2064                      ArrayRef<Metadata *> Ops)
   2065       : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
   2066   ~DILexicalBlockBase() = default;
   2067 
   2068 public:
   2069   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
   2070 
   2071   Metadata *getRawScope() const { return getOperand(1); }
   2072 
   2073   static bool classof(const Metadata *MD) {
   2074     return MD->getMetadataID() == DILexicalBlockKind ||
   2075            MD->getMetadataID() == DILexicalBlockFileKind;
   2076   }
   2077 };
   2078 
   2079 class DILexicalBlock : public DILexicalBlockBase {
   2080   friend class LLVMContextImpl;
   2081   friend class MDNode;
   2082 
   2083   unsigned Line;
   2084   uint16_t Column;
   2085 
   2086   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
   2087                  unsigned Column, ArrayRef<Metadata *> Ops)
   2088       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops), Line(Line),
   2089         Column(Column) {
   2090     assert(Column < (1u << 16) && "Expected 16-bit column");
   2091   }
   2092   ~DILexicalBlock() = default;
   2093 
   2094   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
   2095                                  DIFile *File, unsigned Line, unsigned Column,
   2096                                  StorageType Storage,
   2097                                  bool ShouldCreate = true) {
   2098     return getImpl(Context, static_cast<Metadata *>(Scope),
   2099                    static_cast<Metadata *>(File), Line, Column, Storage,
   2100                    ShouldCreate);
   2101   }
   2102 
   2103   static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
   2104                                  Metadata *File, unsigned Line, unsigned Column,
   2105                                  StorageType Storage, bool ShouldCreate = true);
   2106 
   2107   TempDILexicalBlock cloneImpl() const {
   2108     return getTemporary(getContext(), getScope(), getFile(), getLine(),
   2109                         getColumn());
   2110   }
   2111 
   2112 public:
   2113   DEFINE_MDNODE_GET(DILexicalBlock, (DILocalScope * Scope, DIFile *File,
   2114                                      unsigned Line, unsigned Column),
   2115                     (Scope, File, Line, Column))
   2116   DEFINE_MDNODE_GET(DILexicalBlock, (Metadata * Scope, Metadata *File,
   2117                                      unsigned Line, unsigned Column),
   2118                     (Scope, File, Line, Column))
   2119 
   2120   TempDILexicalBlock clone() const { return cloneImpl(); }
   2121 
   2122   unsigned getLine() const { return Line; }
   2123   unsigned getColumn() const { return Column; }
   2124 
   2125   static bool classof(const Metadata *MD) {
   2126     return MD->getMetadataID() == DILexicalBlockKind;
   2127   }
   2128 };
   2129 
   2130 class DILexicalBlockFile : public DILexicalBlockBase {
   2131   friend class LLVMContextImpl;
   2132   friend class MDNode;
   2133 
   2134   unsigned Discriminator;
   2135 
   2136   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
   2137                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
   2138       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops),
   2139         Discriminator(Discriminator) {}
   2140   ~DILexicalBlockFile() = default;
   2141 
   2142   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
   2143                                      DIFile *File, unsigned Discriminator,
   2144                                      StorageType Storage,
   2145                                      bool ShouldCreate = true) {
   2146     return getImpl(Context, static_cast<Metadata *>(Scope),
   2147                    static_cast<Metadata *>(File), Discriminator, Storage,
   2148                    ShouldCreate);
   2149   }
   2150 
   2151   static DILexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
   2152                                      Metadata *File, unsigned Discriminator,
   2153                                      StorageType Storage,
   2154                                      bool ShouldCreate = true);
   2155 
   2156   TempDILexicalBlockFile cloneImpl() const {
   2157     return getTemporary(getContext(), getScope(), getFile(),
   2158                         getDiscriminator());
   2159   }
   2160 
   2161 public:
   2162   DEFINE_MDNODE_GET(DILexicalBlockFile, (DILocalScope * Scope, DIFile *File,
   2163                                          unsigned Discriminator),
   2164                     (Scope, File, Discriminator))
   2165   DEFINE_MDNODE_GET(DILexicalBlockFile,
   2166                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
   2167                     (Scope, File, Discriminator))
   2168 
   2169   TempDILexicalBlockFile clone() const { return cloneImpl(); }
   2170   unsigned getDiscriminator() const { return Discriminator; }
   2171 
   2172   static bool classof(const Metadata *MD) {
   2173     return MD->getMetadataID() == DILexicalBlockFileKind;
   2174   }
   2175 };
   2176 
   2177 unsigned DILocation::getDiscriminator() const {
   2178   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
   2179     return F->getDiscriminator();
   2180   return 0;
   2181 }
   2182 
   2183 const DILocation *
   2184 DILocation::cloneWithDiscriminator(unsigned Discriminator) const {
   2185   DIScope *Scope = getScope();
   2186   // Skip all parent DILexicalBlockFile that already have a discriminator
   2187   // assigned. We do not want to have nested DILexicalBlockFiles that have
   2188   // mutliple discriminators because only the leaf DILexicalBlockFile's
   2189   // dominator will be used.
   2190   for (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope);
   2191        LBF && LBF->getDiscriminator() != 0;
   2192        LBF = dyn_cast<DILexicalBlockFile>(Scope))
   2193     Scope = LBF->getScope();
   2194   DILexicalBlockFile *NewScope =
   2195       DILexicalBlockFile::get(getContext(), Scope, getFile(), Discriminator);
   2196   return DILocation::get(getContext(), getLine(), getColumn(), NewScope,
   2197                          getInlinedAt());
   2198 }
   2199 
   2200 unsigned DILocation::getBaseDiscriminator() const {
   2201   return getBaseDiscriminatorFromDiscriminator(getDiscriminator());
   2202 }
   2203 
   2204 unsigned DILocation::getDuplicationFactor() const {
   2205   return getDuplicationFactorFromDiscriminator(getDiscriminator());
   2206 }
   2207 
   2208 unsigned DILocation::getCopyIdentifier() const {
   2209   return getCopyIdentifierFromDiscriminator(getDiscriminator());
   2210 }
   2211 
   2212 Optional<const DILocation *> DILocation::cloneWithBaseDiscriminator(unsigned D) const {
   2213   unsigned BD, DF, CI;
   2214 
   2215   if (EnableFSDiscriminator) {
   2216     BD = getBaseDiscriminator();
   2217     if (D == BD)
   2218       return this;
   2219     return cloneWithDiscriminator(D);
   2220   }
   2221 
   2222   decodeDiscriminator(getDiscriminator(), BD, DF, CI);
   2223   if (D == BD)
   2224     return this;
   2225   if (Optional<unsigned> Encoded = encodeDiscriminator(D, DF, CI))
   2226     return cloneWithDiscriminator(*Encoded);
   2227   return None;
   2228 }
   2229 
   2230 Optional<const DILocation *> DILocation::cloneByMultiplyingDuplicationFactor(unsigned DF) const {
   2231   assert(!EnableFSDiscriminator && "FSDiscriminator should not call this.");
   2232 
   2233   DF *= getDuplicationFactor();
   2234   if (DF <= 1)
   2235     return this;
   2236 
   2237   unsigned BD = getBaseDiscriminator();
   2238   unsigned CI = getCopyIdentifier();
   2239   if (Optional<unsigned> D = encodeDiscriminator(BD, DF, CI))
   2240     return cloneWithDiscriminator(*D);
   2241   return None;
   2242 }
   2243 
   2244 class DINamespace : public DIScope {
   2245   friend class LLVMContextImpl;
   2246   friend class MDNode;
   2247 
   2248   unsigned ExportSymbols : 1;
   2249 
   2250   DINamespace(LLVMContext &Context, StorageType Storage, bool ExportSymbols,
   2251               ArrayRef<Metadata *> Ops)
   2252       : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace,
   2253                 Ops),
   2254         ExportSymbols(ExportSymbols) {}
   2255   ~DINamespace() = default;
   2256 
   2257   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
   2258                               StringRef Name, bool ExportSymbols,
   2259                               StorageType Storage, bool ShouldCreate = true) {
   2260     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
   2261                    ExportSymbols, Storage, ShouldCreate);
   2262   }
   2263   static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
   2264                               MDString *Name, bool ExportSymbols,
   2265                               StorageType Storage, bool ShouldCreate = true);
   2266 
   2267   TempDINamespace cloneImpl() const {
   2268     return getTemporary(getContext(), getScope(), getName(),
   2269                         getExportSymbols());
   2270   }
   2271 
   2272 public:
   2273   DEFINE_MDNODE_GET(DINamespace,
   2274                     (DIScope *Scope, StringRef Name, bool ExportSymbols),
   2275                     (Scope, Name, ExportSymbols))
   2276   DEFINE_MDNODE_GET(DINamespace,
   2277                     (Metadata *Scope, MDString *Name, bool ExportSymbols),
   2278                     (Scope, Name, ExportSymbols))
   2279 
   2280   TempDINamespace clone() const { return cloneImpl(); }
   2281 
   2282   bool getExportSymbols() const { return ExportSymbols; }
   2283   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   2284   StringRef getName() const { return getStringOperand(2); }
   2285 
   2286   Metadata *getRawScope() const { return getOperand(1); }
   2287   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   2288 
   2289   static bool classof(const Metadata *MD) {
   2290     return MD->getMetadataID() == DINamespaceKind;
   2291   }
   2292 };
   2293 
   2294 /// Represents a module in the programming language, for example, a Clang
   2295 /// module, or a Fortran module.
   2296 class DIModule : public DIScope {
   2297   friend class LLVMContextImpl;
   2298   friend class MDNode;
   2299   unsigned LineNo;
   2300   bool IsDecl;
   2301 
   2302   DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
   2303            bool IsDecl, ArrayRef<Metadata *> Ops)
   2304       : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops),
   2305         LineNo(LineNo), IsDecl(IsDecl) {}
   2306   ~DIModule() = default;
   2307 
   2308   static DIModule *getImpl(LLVMContext &Context, DIFile *File, DIScope *Scope,
   2309                            StringRef Name, StringRef ConfigurationMacros,
   2310                            StringRef IncludePath, StringRef APINotesFile,
   2311                            unsigned LineNo, bool IsDecl, StorageType Storage,
   2312                            bool ShouldCreate = true) {
   2313     return getImpl(Context, File, Scope, getCanonicalMDString(Context, Name),
   2314                    getCanonicalMDString(Context, ConfigurationMacros),
   2315                    getCanonicalMDString(Context, IncludePath),
   2316                    getCanonicalMDString(Context, APINotesFile), LineNo, IsDecl,
   2317                    Storage, ShouldCreate);
   2318   }
   2319   static DIModule *getImpl(LLVMContext &Context, Metadata *File,
   2320                            Metadata *Scope, MDString *Name,
   2321                            MDString *ConfigurationMacros, MDString *IncludePath,
   2322                            MDString *APINotesFile, unsigned LineNo, bool IsDecl,
   2323                            StorageType Storage, bool ShouldCreate = true);
   2324 
   2325   TempDIModule cloneImpl() const {
   2326     return getTemporary(getContext(), getFile(), getScope(), getName(),
   2327                         getConfigurationMacros(), getIncludePath(),
   2328                         getAPINotesFile(), getLineNo(), getIsDecl());
   2329   }
   2330 
   2331 public:
   2332   DEFINE_MDNODE_GET(DIModule,
   2333                     (DIFile * File, DIScope *Scope, StringRef Name,
   2334                      StringRef ConfigurationMacros, StringRef IncludePath,
   2335                      StringRef APINotesFile, unsigned LineNo,
   2336                      bool IsDecl = false),
   2337                     (File, Scope, Name, ConfigurationMacros, IncludePath,
   2338                      APINotesFile, LineNo, IsDecl))
   2339   DEFINE_MDNODE_GET(DIModule,
   2340                     (Metadata * File, Metadata *Scope, MDString *Name,
   2341                      MDString *ConfigurationMacros, MDString *IncludePath,
   2342                      MDString *APINotesFile, unsigned LineNo,
   2343                      bool IsDecl = false),
   2344                     (File, Scope, Name, ConfigurationMacros, IncludePath,
   2345                      APINotesFile, LineNo, IsDecl))
   2346 
   2347   TempDIModule clone() const { return cloneImpl(); }
   2348 
   2349   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   2350   StringRef getName() const { return getStringOperand(2); }
   2351   StringRef getConfigurationMacros() const { return getStringOperand(3); }
   2352   StringRef getIncludePath() const { return getStringOperand(4); }
   2353   StringRef getAPINotesFile() const { return getStringOperand(5); }
   2354   unsigned getLineNo() const { return LineNo; }
   2355   bool getIsDecl() const { return IsDecl; }
   2356 
   2357   Metadata *getRawScope() const { return getOperand(1); }
   2358   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   2359   MDString *getRawConfigurationMacros() const {
   2360     return getOperandAs<MDString>(3);
   2361   }
   2362   MDString *getRawIncludePath() const { return getOperandAs<MDString>(4); }
   2363   MDString *getRawAPINotesFile() const { return getOperandAs<MDString>(5); }
   2364 
   2365   static bool classof(const Metadata *MD) {
   2366     return MD->getMetadataID() == DIModuleKind;
   2367   }
   2368 };
   2369 
   2370 /// Base class for template parameters.
   2371 class DITemplateParameter : public DINode {
   2372 protected:
   2373   bool IsDefault;
   2374 
   2375   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
   2376                       unsigned Tag, bool IsDefault, ArrayRef<Metadata *> Ops)
   2377       : DINode(Context, ID, Storage, Tag, Ops), IsDefault(IsDefault) {}
   2378   ~DITemplateParameter() = default;
   2379 
   2380 public:
   2381   StringRef getName() const { return getStringOperand(0); }
   2382   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
   2383 
   2384   MDString *getRawName() const { return getOperandAs<MDString>(0); }
   2385   Metadata *getRawType() const { return getOperand(1); }
   2386   bool isDefault() const { return IsDefault; }
   2387 
   2388   static bool classof(const Metadata *MD) {
   2389     return MD->getMetadataID() == DITemplateTypeParameterKind ||
   2390            MD->getMetadataID() == DITemplateValueParameterKind;
   2391   }
   2392 };
   2393 
   2394 class DITemplateTypeParameter : public DITemplateParameter {
   2395   friend class LLVMContextImpl;
   2396   friend class MDNode;
   2397 
   2398   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
   2399                           bool IsDefault, ArrayRef<Metadata *> Ops)
   2400       : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
   2401                             dwarf::DW_TAG_template_type_parameter, IsDefault,
   2402                             Ops) {}
   2403   ~DITemplateTypeParameter() = default;
   2404 
   2405   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
   2406                                           DIType *Type, bool IsDefault,
   2407                                           StorageType Storage,
   2408                                           bool ShouldCreate = true) {
   2409     return getImpl(Context, getCanonicalMDString(Context, Name), Type,
   2410                    IsDefault, Storage, ShouldCreate);
   2411   }
   2412   static DITemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
   2413                                           Metadata *Type, bool IsDefault,
   2414                                           StorageType Storage,
   2415                                           bool ShouldCreate = true);
   2416 
   2417   TempDITemplateTypeParameter cloneImpl() const {
   2418     return getTemporary(getContext(), getName(), getType(), isDefault());
   2419   }
   2420 
   2421 public:
   2422   DEFINE_MDNODE_GET(DITemplateTypeParameter,
   2423                     (StringRef Name, DIType *Type, bool IsDefault),
   2424                     (Name, Type, IsDefault))
   2425   DEFINE_MDNODE_GET(DITemplateTypeParameter,
   2426                     (MDString *Name, Metadata *Type, bool IsDefault),
   2427                     (Name, Type, IsDefault))
   2428 
   2429   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
   2430 
   2431   static bool classof(const Metadata *MD) {
   2432     return MD->getMetadataID() == DITemplateTypeParameterKind;
   2433   }
   2434 };
   2435 
   2436 class DITemplateValueParameter : public DITemplateParameter {
   2437   friend class LLVMContextImpl;
   2438   friend class MDNode;
   2439 
   2440   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
   2441                            unsigned Tag, bool IsDefault,
   2442                            ArrayRef<Metadata *> Ops)
   2443       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
   2444                             IsDefault, Ops) {}
   2445   ~DITemplateValueParameter() = default;
   2446 
   2447   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
   2448                                            StringRef Name, DIType *Type,
   2449                                            bool IsDefault, Metadata *Value,
   2450                                            StorageType Storage,
   2451                                            bool ShouldCreate = true) {
   2452     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
   2453                    IsDefault, Value, Storage, ShouldCreate);
   2454   }
   2455   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
   2456                                            MDString *Name, Metadata *Type,
   2457                                            bool IsDefault, Metadata *Value,
   2458                                            StorageType Storage,
   2459                                            bool ShouldCreate = true);
   2460 
   2461   TempDITemplateValueParameter cloneImpl() const {
   2462     return getTemporary(getContext(), getTag(), getName(), getType(),
   2463                         isDefault(), getValue());
   2464   }
   2465 
   2466 public:
   2467   DEFINE_MDNODE_GET(DITemplateValueParameter,
   2468                     (unsigned Tag, StringRef Name, DIType *Type, bool IsDefault,
   2469                      Metadata *Value),
   2470                     (Tag, Name, Type, IsDefault, Value))
   2471   DEFINE_MDNODE_GET(DITemplateValueParameter,
   2472                     (unsigned Tag, MDString *Name, Metadata *Type,
   2473                      bool IsDefault, Metadata *Value),
   2474                     (Tag, Name, Type, IsDefault, Value))
   2475 
   2476   TempDITemplateValueParameter clone() const { return cloneImpl(); }
   2477 
   2478   Metadata *getValue() const { return getOperand(2); }
   2479 
   2480   static bool classof(const Metadata *MD) {
   2481     return MD->getMetadataID() == DITemplateValueParameterKind;
   2482   }
   2483 };
   2484 
   2485 /// Base class for variables.
   2486 class DIVariable : public DINode {
   2487   unsigned Line;
   2488   uint32_t AlignInBits;
   2489 
   2490 protected:
   2491   DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Line,
   2492              ArrayRef<Metadata *> Ops, uint32_t AlignInBits = 0)
   2493       : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
   2494         AlignInBits(AlignInBits) {}
   2495   ~DIVariable() = default;
   2496 
   2497 public:
   2498   unsigned getLine() const { return Line; }
   2499   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   2500   StringRef getName() const { return getStringOperand(1); }
   2501   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   2502   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
   2503   uint32_t getAlignInBits() const { return AlignInBits; }
   2504   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
   2505   /// Determines the size of the variable's type.
   2506   Optional<uint64_t> getSizeInBits() const;
   2507 
   2508   /// Return the signedness of this variable's type, or None if this type is
   2509   /// neither signed nor unsigned.
   2510   Optional<DIBasicType::Signedness> getSignedness() const {
   2511     if (auto *BT = dyn_cast<DIBasicType>(getType()))
   2512       return BT->getSignedness();
   2513     return None;
   2514   }
   2515 
   2516   StringRef getFilename() const {
   2517     if (auto *F = getFile())
   2518       return F->getFilename();
   2519     return "";
   2520   }
   2521 
   2522   StringRef getDirectory() const {
   2523     if (auto *F = getFile())
   2524       return F->getDirectory();
   2525     return "";
   2526   }
   2527 
   2528   Optional<StringRef> getSource() const {
   2529     if (auto *F = getFile())
   2530       return F->getSource();
   2531     return None;
   2532   }
   2533 
   2534   Metadata *getRawScope() const { return getOperand(0); }
   2535   MDString *getRawName() const { return getOperandAs<MDString>(1); }
   2536   Metadata *getRawFile() const { return getOperand(2); }
   2537   Metadata *getRawType() const { return getOperand(3); }
   2538 
   2539   static bool classof(const Metadata *MD) {
   2540     return MD->getMetadataID() == DILocalVariableKind ||
   2541            MD->getMetadataID() == DIGlobalVariableKind;
   2542   }
   2543 };
   2544 
   2545 /// DWARF expression.
   2546 ///
   2547 /// This is (almost) a DWARF expression that modifies the location of a
   2548 /// variable, or the location of a single piece of a variable, or (when using
   2549 /// DW_OP_stack_value) is the constant variable value.
   2550 ///
   2551 /// TODO: Co-allocate the expression elements.
   2552 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
   2553 /// storage types.
   2554 class DIExpression : public MDNode {
   2555   friend class LLVMContextImpl;
   2556   friend class MDNode;
   2557 
   2558   std::vector<uint64_t> Elements;
   2559 
   2560   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
   2561       : MDNode(C, DIExpressionKind, Storage, None),
   2562         Elements(Elements.begin(), Elements.end()) {}
   2563   ~DIExpression() = default;
   2564 
   2565   static DIExpression *getImpl(LLVMContext &Context,
   2566                                ArrayRef<uint64_t> Elements, StorageType Storage,
   2567                                bool ShouldCreate = true);
   2568 
   2569   TempDIExpression cloneImpl() const {
   2570     return getTemporary(getContext(), getElements());
   2571   }
   2572 
   2573 public:
   2574   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
   2575 
   2576   TempDIExpression clone() const { return cloneImpl(); }
   2577 
   2578   ArrayRef<uint64_t> getElements() const { return Elements; }
   2579 
   2580   unsigned getNumElements() const { return Elements.size(); }
   2581 
   2582   uint64_t getElement(unsigned I) const {
   2583     assert(I < Elements.size() && "Index out of range");
   2584     return Elements[I];
   2585   }
   2586 
   2587   enum SignedOrUnsignedConstant { SignedConstant, UnsignedConstant };
   2588   /// Determine whether this represents a constant value, if so
   2589   // return it's sign information.
   2590   llvm::Optional<SignedOrUnsignedConstant> isConstant() const;
   2591 
   2592   /// Return the number of unique location operands referred to (via
   2593   /// DW_OP_LLVM_arg) in this expression; this is not necessarily the number of
   2594   /// instances of DW_OP_LLVM_arg within the expression.
   2595   /// For example, for the expression:
   2596   ///   (DW_OP_LLVM_arg 0, DW_OP_LLVM_arg 1, DW_OP_plus,
   2597   ///    DW_OP_LLVM_arg 0, DW_OP_mul)
   2598   /// This function would return 2, as there are two unique location operands
   2599   /// (0 and 1).
   2600   uint64_t getNumLocationOperands() const;
   2601 
   2602   using element_iterator = ArrayRef<uint64_t>::iterator;
   2603 
   2604   element_iterator elements_begin() const { return getElements().begin(); }
   2605   element_iterator elements_end() const { return getElements().end(); }
   2606 
   2607   /// A lightweight wrapper around an expression operand.
   2608   ///
   2609   /// TODO: Store arguments directly and change \a DIExpression to store a
   2610   /// range of these.
   2611   class ExprOperand {
   2612     const uint64_t *Op = nullptr;
   2613 
   2614   public:
   2615     ExprOperand() = default;
   2616     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
   2617 
   2618     const uint64_t *get() const { return Op; }
   2619 
   2620     /// Get the operand code.
   2621     uint64_t getOp() const { return *Op; }
   2622 
   2623     /// Get an argument to the operand.
   2624     ///
   2625     /// Never returns the operand itself.
   2626     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
   2627 
   2628     unsigned getNumArgs() const { return getSize() - 1; }
   2629 
   2630     /// Return the size of the operand.
   2631     ///
   2632     /// Return the number of elements in the operand (1 + args).
   2633     unsigned getSize() const;
   2634 
   2635     /// Append the elements of this operand to \p V.
   2636     void appendToVector(SmallVectorImpl<uint64_t> &V) const {
   2637       V.append(get(), get() + getSize());
   2638     }
   2639   };
   2640 
   2641   /// An iterator for expression operands.
   2642   class expr_op_iterator {
   2643     ExprOperand Op;
   2644 
   2645   public:
   2646     using iterator_category = std::input_iterator_tag;
   2647     using value_type = ExprOperand;
   2648     using difference_type = std::ptrdiff_t;
   2649     using pointer = value_type *;
   2650     using reference = value_type &;
   2651 
   2652     expr_op_iterator() = default;
   2653     explicit expr_op_iterator(element_iterator I) : Op(I) {}
   2654 
   2655     element_iterator getBase() const { return Op.get(); }
   2656     const ExprOperand &operator*() const { return Op; }
   2657     const ExprOperand *operator->() const { return &Op; }
   2658 
   2659     expr_op_iterator &operator++() {
   2660       increment();
   2661       return *this;
   2662     }
   2663     expr_op_iterator operator++(int) {
   2664       expr_op_iterator T(*this);
   2665       increment();
   2666       return T;
   2667     }
   2668 
   2669     /// Get the next iterator.
   2670     ///
   2671     /// \a std::next() doesn't work because this is technically an
   2672     /// input_iterator, but it's a perfectly valid operation.  This is an
   2673     /// accessor to provide the same functionality.
   2674     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
   2675 
   2676     bool operator==(const expr_op_iterator &X) const {
   2677       return getBase() == X.getBase();
   2678     }
   2679     bool operator!=(const expr_op_iterator &X) const {
   2680       return getBase() != X.getBase();
   2681     }
   2682 
   2683   private:
   2684     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
   2685   };
   2686 
   2687   /// Visit the elements via ExprOperand wrappers.
   2688   ///
   2689   /// These range iterators visit elements through \a ExprOperand wrappers.
   2690   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
   2691   /// true.
   2692   ///
   2693   /// \pre \a isValid() gives \c true.
   2694   /// @{
   2695   expr_op_iterator expr_op_begin() const {
   2696     return expr_op_iterator(elements_begin());
   2697   }
   2698   expr_op_iterator expr_op_end() const {
   2699     return expr_op_iterator(elements_end());
   2700   }
   2701   iterator_range<expr_op_iterator> expr_ops() const {
   2702     return {expr_op_begin(), expr_op_end()};
   2703   }
   2704   /// @}
   2705 
   2706   bool isValid() const;
   2707 
   2708   static bool classof(const Metadata *MD) {
   2709     return MD->getMetadataID() == DIExpressionKind;
   2710   }
   2711 
   2712   /// Return whether the first element a DW_OP_deref.
   2713   bool startsWithDeref() const {
   2714     return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
   2715   }
   2716 
   2717   /// Holds the characteristics of one fragment of a larger variable.
   2718   struct FragmentInfo {
   2719     uint64_t SizeInBits;
   2720     uint64_t OffsetInBits;
   2721   };
   2722 
   2723   /// Retrieve the details of this fragment expression.
   2724   static Optional<FragmentInfo> getFragmentInfo(expr_op_iterator Start,
   2725                                                 expr_op_iterator End);
   2726 
   2727   /// Retrieve the details of this fragment expression.
   2728   Optional<FragmentInfo> getFragmentInfo() const {
   2729     return getFragmentInfo(expr_op_begin(), expr_op_end());
   2730   }
   2731 
   2732   /// Return whether this is a piece of an aggregate variable.
   2733   bool isFragment() const { return getFragmentInfo().hasValue(); }
   2734 
   2735   /// Return whether this is an implicit location description.
   2736   bool isImplicit() const;
   2737 
   2738   /// Return whether the location is computed on the expression stack, meaning
   2739   /// it cannot be a simple register location.
   2740   bool isComplex() const;
   2741 
   2742   /// Append \p Ops with operations to apply the \p Offset.
   2743   static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset);
   2744 
   2745   /// If this is a constant offset, extract it. If there is no expression,
   2746   /// return true with an offset of zero.
   2747   bool extractIfOffset(int64_t &Offset) const;
   2748 
   2749   /// Returns true iff this DIExpression contains at least one instance of
   2750   /// `DW_OP_LLVM_arg, n` for all n in [0, N).
   2751   bool hasAllLocationOps(unsigned N) const;
   2752 
   2753   /// Checks if the last 4 elements of the expression are DW_OP_constu <DWARF
   2754   /// Address Space> DW_OP_swap DW_OP_xderef and extracts the <DWARF Address
   2755   /// Space>.
   2756   static const DIExpression *extractAddressClass(const DIExpression *Expr,
   2757                                                  unsigned &AddrClass);
   2758 
   2759   /// Used for DIExpression::prepend.
   2760   enum PrependOps : uint8_t {
   2761     ApplyOffset = 0,
   2762     DerefBefore = 1 << 0,
   2763     DerefAfter = 1 << 1,
   2764     StackValue = 1 << 2,
   2765     EntryValue = 1 << 3
   2766   };
   2767 
   2768   /// Prepend \p DIExpr with a deref and offset operation and optionally turn it
   2769   /// into a stack value or/and an entry value.
   2770   static DIExpression *prepend(const DIExpression *Expr, uint8_t Flags,
   2771                                int64_t Offset = 0);
   2772 
   2773   /// Prepend \p DIExpr with the given opcodes and optionally turn it into a
   2774   /// stack value.
   2775   static DIExpression *prependOpcodes(const DIExpression *Expr,
   2776                                       SmallVectorImpl<uint64_t> &Ops,
   2777                                       bool StackValue = false,
   2778                                       bool EntryValue = false);
   2779 
   2780   /// Append the opcodes \p Ops to \p DIExpr. Unlike \ref appendToStack, the
   2781   /// returned expression is a stack value only if \p DIExpr is a stack value.
   2782   /// If \p DIExpr describes a fragment, the returned expression will describe
   2783   /// the same fragment.
   2784   static DIExpression *append(const DIExpression *Expr, ArrayRef<uint64_t> Ops);
   2785 
   2786   /// Convert \p DIExpr into a stack value if it isn't one already by appending
   2787   /// DW_OP_deref if needed, and appending \p Ops to the resulting expression.
   2788   /// If \p DIExpr describes a fragment, the returned expression will describe
   2789   /// the same fragment.
   2790   static DIExpression *appendToStack(const DIExpression *Expr,
   2791                                      ArrayRef<uint64_t> Ops);
   2792 
   2793   /// Create a copy of \p Expr by appending the given list of \p Ops to each
   2794   /// instance of the operand `DW_OP_LLVM_arg, \p ArgNo`. This is used to
   2795   /// modify a specific location used by \p Expr, such as when salvaging that
   2796   /// location.
   2797   static DIExpression *appendOpsToArg(const DIExpression *Expr,
   2798                                       ArrayRef<uint64_t> Ops, unsigned ArgNo,
   2799                                       bool StackValue = false);
   2800 
   2801   /// Create a copy of \p Expr with each instance of
   2802   /// `DW_OP_LLVM_arg, \p OldArg` replaced with `DW_OP_LLVM_arg, \p NewArg`,
   2803   /// and each instance of `DW_OP_LLVM_arg, Arg` with `DW_OP_LLVM_arg, Arg - 1`
   2804   /// for all Arg > \p OldArg.
   2805   /// This is used when replacing one of the operands of a debug value list
   2806   /// with another operand in the same list and deleting the old operand.
   2807   static DIExpression *replaceArg(const DIExpression *Expr, uint64_t OldArg,
   2808                                   uint64_t NewArg);
   2809 
   2810   /// Create a DIExpression to describe one part of an aggregate variable that
   2811   /// is fragmented across multiple Values. The DW_OP_LLVM_fragment operation
   2812   /// will be appended to the elements of \c Expr. If \c Expr already contains
   2813   /// a \c DW_OP_LLVM_fragment \c OffsetInBits is interpreted as an offset
   2814   /// into the existing fragment.
   2815   ///
   2816   /// \param OffsetInBits Offset of the piece in bits.
   2817   /// \param SizeInBits   Size of the piece in bits.
   2818   /// \return             Creating a fragment expression may fail if \c Expr
   2819   ///                     contains arithmetic operations that would be truncated.
   2820   static Optional<DIExpression *>
   2821   createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits,
   2822                            unsigned SizeInBits);
   2823 
   2824   /// Determine the relative position of the fragments passed in.
   2825   /// Returns -1 if this is entirely before Other, 0 if this and Other overlap,
   2826   /// 1 if this is entirely after Other.
   2827   static int fragmentCmp(const FragmentInfo &A, const FragmentInfo &B) {
   2828     uint64_t l1 = A.OffsetInBits;
   2829     uint64_t l2 = B.OffsetInBits;
   2830     uint64_t r1 = l1 + A.SizeInBits;
   2831     uint64_t r2 = l2 + B.SizeInBits;
   2832     if (r1 <= l2)
   2833       return -1;
   2834     else if (r2 <= l1)
   2835       return 1;
   2836     else
   2837       return 0;
   2838   }
   2839 
   2840   using ExtOps = std::array<uint64_t, 6>;
   2841 
   2842   /// Returns the ops for a zero- or sign-extension in a DIExpression.
   2843   static ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed);
   2844 
   2845   /// Append a zero- or sign-extension to \p Expr. Converts the expression to a
   2846   /// stack value if it isn't one already.
   2847   static DIExpression *appendExt(const DIExpression *Expr, unsigned FromSize,
   2848                                  unsigned ToSize, bool Signed);
   2849 
   2850   /// Check if fragments overlap between a pair of FragmentInfos.
   2851   static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B) {
   2852     return fragmentCmp(A, B) == 0;
   2853   }
   2854 
   2855   /// Determine the relative position of the fragments described by this
   2856   /// DIExpression and \p Other. Calls static fragmentCmp implementation.
   2857   int fragmentCmp(const DIExpression *Other) const {
   2858     auto Fragment1 = *getFragmentInfo();
   2859     auto Fragment2 = *Other->getFragmentInfo();
   2860     return fragmentCmp(Fragment1, Fragment2);
   2861   }
   2862 
   2863   /// Check if fragments overlap between this DIExpression and \p Other.
   2864   bool fragmentsOverlap(const DIExpression *Other) const {
   2865     if (!isFragment() || !Other->isFragment())
   2866       return true;
   2867     return fragmentCmp(Other) == 0;
   2868   }
   2869 
   2870   /// Check if the expression consists of exactly one entry value operand.
   2871   /// (This is the only configuration of entry values that is supported.)
   2872   bool isEntryValue() const {
   2873     return getNumElements() > 0 &&
   2874            getElement(0) == dwarf::DW_OP_LLVM_entry_value;
   2875   }
   2876 };
   2877 
   2878 inline bool operator==(const DIExpression::FragmentInfo &A,
   2879                        const DIExpression::FragmentInfo &B) {
   2880   return std::tie(A.SizeInBits, A.OffsetInBits) ==
   2881          std::tie(B.SizeInBits, B.OffsetInBits);
   2882 }
   2883 
   2884 inline bool operator<(const DIExpression::FragmentInfo &A,
   2885                       const DIExpression::FragmentInfo &B) {
   2886   return std::tie(A.SizeInBits, A.OffsetInBits) <
   2887          std::tie(B.SizeInBits, B.OffsetInBits);
   2888 }
   2889 
   2890 template <> struct DenseMapInfo<DIExpression::FragmentInfo> {
   2891   using FragInfo = DIExpression::FragmentInfo;
   2892   static const uint64_t MaxVal = std::numeric_limits<uint64_t>::max();
   2893 
   2894   static inline FragInfo getEmptyKey() { return {MaxVal, MaxVal}; }
   2895 
   2896   static inline FragInfo getTombstoneKey() { return {MaxVal - 1, MaxVal - 1}; }
   2897 
   2898   static unsigned getHashValue(const FragInfo &Frag) {
   2899     return (Frag.SizeInBits & 0xffff) << 16 | (Frag.OffsetInBits & 0xffff);
   2900   }
   2901 
   2902   static bool isEqual(const FragInfo &A, const FragInfo &B) { return A == B; }
   2903 };
   2904 
   2905 /// Global variables.
   2906 ///
   2907 /// TODO: Remove DisplayName.  It's always equal to Name.
   2908 class DIGlobalVariable : public DIVariable {
   2909   friend class LLVMContextImpl;
   2910   friend class MDNode;
   2911 
   2912   bool IsLocalToUnit;
   2913   bool IsDefinition;
   2914 
   2915   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
   2916                    bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
   2917                    ArrayRef<Metadata *> Ops)
   2918       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops, AlignInBits),
   2919         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
   2920   ~DIGlobalVariable() = default;
   2921 
   2922   static DIGlobalVariable *
   2923   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
   2924           StringRef LinkageName, DIFile *File, unsigned Line, DIType *Type,
   2925           bool IsLocalToUnit, bool IsDefinition,
   2926           DIDerivedType *StaticDataMemberDeclaration, MDTuple *TemplateParams,
   2927           uint32_t AlignInBits, StorageType Storage, bool ShouldCreate = true) {
   2928     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
   2929                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
   2930                    IsLocalToUnit, IsDefinition, StaticDataMemberDeclaration,
   2931                    cast_or_null<Metadata>(TemplateParams), AlignInBits, Storage,
   2932                    ShouldCreate);
   2933   }
   2934   static DIGlobalVariable *
   2935   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
   2936           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
   2937           bool IsLocalToUnit, bool IsDefinition,
   2938           Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
   2939           uint32_t AlignInBits, StorageType Storage, bool ShouldCreate = true);
   2940 
   2941   TempDIGlobalVariable cloneImpl() const {
   2942     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
   2943                         getFile(), getLine(), getType(), isLocalToUnit(),
   2944                         isDefinition(), getStaticDataMemberDeclaration(),
   2945                         getTemplateParams(), getAlignInBits());
   2946   }
   2947 
   2948 public:
   2949   DEFINE_MDNODE_GET(DIGlobalVariable,
   2950                     (DIScope * Scope, StringRef Name, StringRef LinkageName,
   2951                      DIFile *File, unsigned Line, DIType *Type,
   2952                      bool IsLocalToUnit, bool IsDefinition,
   2953                      DIDerivedType *StaticDataMemberDeclaration,
   2954                      MDTuple *TemplateParams, uint32_t AlignInBits),
   2955                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
   2956                      IsDefinition, StaticDataMemberDeclaration, TemplateParams,
   2957                      AlignInBits))
   2958   DEFINE_MDNODE_GET(DIGlobalVariable,
   2959                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
   2960                      Metadata *File, unsigned Line, Metadata *Type,
   2961                      bool IsLocalToUnit, bool IsDefinition,
   2962                      Metadata *StaticDataMemberDeclaration,
   2963                      Metadata *TemplateParams, uint32_t AlignInBits),
   2964                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
   2965                      IsDefinition, StaticDataMemberDeclaration, TemplateParams,
   2966                      AlignInBits))
   2967 
   2968   TempDIGlobalVariable clone() const { return cloneImpl(); }
   2969 
   2970   bool isLocalToUnit() const { return IsLocalToUnit; }
   2971   bool isDefinition() const { return IsDefinition; }
   2972   StringRef getDisplayName() const { return getStringOperand(4); }
   2973   StringRef getLinkageName() const { return getStringOperand(5); }
   2974   DIDerivedType *getStaticDataMemberDeclaration() const {
   2975     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
   2976   }
   2977 
   2978   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
   2979   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(6); }
   2980   Metadata *getRawTemplateParams() const { return getOperand(7); }
   2981   MDTuple *getTemplateParams() const { return getOperandAs<MDTuple>(7); }
   2982 
   2983   static bool classof(const Metadata *MD) {
   2984     return MD->getMetadataID() == DIGlobalVariableKind;
   2985   }
   2986 };
   2987 
   2988 class DICommonBlock : public DIScope {
   2989   unsigned LineNo;
   2990 
   2991   friend class LLVMContextImpl;
   2992   friend class MDNode;
   2993 
   2994   DICommonBlock(LLVMContext &Context, StorageType Storage, unsigned LineNo,
   2995                 ArrayRef<Metadata *> Ops)
   2996       : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block,
   2997                 Ops), LineNo(LineNo) {}
   2998 
   2999   static DICommonBlock *getImpl(LLVMContext &Context, DIScope *Scope,
   3000                                 DIGlobalVariable *Decl, StringRef Name,
   3001                                 DIFile *File, unsigned LineNo,
   3002                                 StorageType Storage,
   3003                                 bool ShouldCreate = true) {
   3004     return getImpl(Context, Scope, Decl, getCanonicalMDString(Context, Name),
   3005                    File, LineNo, Storage, ShouldCreate);
   3006   }
   3007   static DICommonBlock *getImpl(LLVMContext &Context, Metadata *Scope,
   3008                                 Metadata *Decl, MDString *Name, Metadata *File,
   3009                                 unsigned LineNo,
   3010                                 StorageType Storage, bool ShouldCreate = true);
   3011 
   3012   TempDICommonBlock cloneImpl() const {
   3013     return getTemporary(getContext(), getScope(), getDecl(), getName(),
   3014                         getFile(), getLineNo());
   3015   }
   3016 
   3017 public:
   3018   DEFINE_MDNODE_GET(DICommonBlock,
   3019                     (DIScope *Scope, DIGlobalVariable *Decl, StringRef Name,
   3020                      DIFile *File, unsigned LineNo),
   3021                     (Scope, Decl, Name, File, LineNo))
   3022   DEFINE_MDNODE_GET(DICommonBlock,
   3023                     (Metadata *Scope, Metadata *Decl, MDString *Name,
   3024                      Metadata *File, unsigned LineNo),
   3025                     (Scope, Decl, Name, File, LineNo))
   3026 
   3027   TempDICommonBlock clone() const { return cloneImpl(); }
   3028 
   3029   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   3030   DIGlobalVariable *getDecl() const {
   3031     return cast_or_null<DIGlobalVariable>(getRawDecl());
   3032   }
   3033   StringRef getName() const { return getStringOperand(2); }
   3034   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   3035   unsigned getLineNo() const { return LineNo; }
   3036 
   3037   Metadata *getRawScope() const { return getOperand(0); }
   3038   Metadata *getRawDecl() const { return getOperand(1); }
   3039   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   3040   Metadata *getRawFile() const { return getOperand(3); }
   3041 
   3042   static bool classof(const Metadata *MD) {
   3043     return MD->getMetadataID() == DICommonBlockKind;
   3044   }
   3045 };
   3046 
   3047 /// Local variable.
   3048 ///
   3049 /// TODO: Split up flags.
   3050 class DILocalVariable : public DIVariable {
   3051   friend class LLVMContextImpl;
   3052   friend class MDNode;
   3053 
   3054   unsigned Arg : 16;
   3055   DIFlags Flags;
   3056 
   3057   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
   3058                   unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
   3059                   ArrayRef<Metadata *> Ops)
   3060       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops, AlignInBits),
   3061         Arg(Arg), Flags(Flags) {
   3062     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
   3063   }
   3064   ~DILocalVariable() = default;
   3065 
   3066   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
   3067                                   StringRef Name, DIFile *File, unsigned Line,
   3068                                   DIType *Type, unsigned Arg, DIFlags Flags,
   3069                                   uint32_t AlignInBits, StorageType Storage,
   3070                                   bool ShouldCreate = true) {
   3071     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
   3072                    Line, Type, Arg, Flags, AlignInBits, Storage, ShouldCreate);
   3073   }
   3074   static DILocalVariable *getImpl(LLVMContext &Context, Metadata *Scope,
   3075                                   MDString *Name, Metadata *File, unsigned Line,
   3076                                   Metadata *Type, unsigned Arg, DIFlags Flags,
   3077                                   uint32_t AlignInBits, StorageType Storage,
   3078                                   bool ShouldCreate = true);
   3079 
   3080   TempDILocalVariable cloneImpl() const {
   3081     return getTemporary(getContext(), getScope(), getName(), getFile(),
   3082                         getLine(), getType(), getArg(), getFlags(),
   3083                         getAlignInBits());
   3084   }
   3085 
   3086 public:
   3087   DEFINE_MDNODE_GET(DILocalVariable,
   3088                     (DILocalScope * Scope, StringRef Name, DIFile *File,
   3089                      unsigned Line, DIType *Type, unsigned Arg, DIFlags Flags,
   3090                      uint32_t AlignInBits),
   3091                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
   3092   DEFINE_MDNODE_GET(DILocalVariable,
   3093                     (Metadata * Scope, MDString *Name, Metadata *File,
   3094                      unsigned Line, Metadata *Type, unsigned Arg,
   3095                      DIFlags Flags, uint32_t AlignInBits),
   3096                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
   3097 
   3098   TempDILocalVariable clone() const { return cloneImpl(); }
   3099 
   3100   /// Get the local scope for this variable.
   3101   ///
   3102   /// Variables must be defined in a local scope.
   3103   DILocalScope *getScope() const {
   3104     return cast<DILocalScope>(DIVariable::getScope());
   3105   }
   3106 
   3107   bool isParameter() const { return Arg; }
   3108   unsigned getArg() const { return Arg; }
   3109   DIFlags getFlags() const { return Flags; }
   3110 
   3111   bool isArtificial() const { return getFlags() & FlagArtificial; }
   3112   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
   3113 
   3114   /// Check that a location is valid for this variable.
   3115   ///
   3116   /// Check that \c DL exists, is in the same subprogram, and has the same
   3117   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
   3118   /// to a \a DbgInfoIntrinsic.)
   3119   bool isValidLocationForIntrinsic(const DILocation *DL) const {
   3120     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
   3121   }
   3122 
   3123   static bool classof(const Metadata *MD) {
   3124     return MD->getMetadataID() == DILocalVariableKind;
   3125   }
   3126 };
   3127 
   3128 /// Label.
   3129 ///
   3130 class DILabel : public DINode {
   3131   friend class LLVMContextImpl;
   3132   friend class MDNode;
   3133 
   3134   unsigned Line;
   3135 
   3136   DILabel(LLVMContext &C, StorageType Storage, unsigned Line,
   3137           ArrayRef<Metadata *> Ops)
   3138       : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {}
   3139   ~DILabel() = default;
   3140 
   3141   static DILabel *getImpl(LLVMContext &Context, DIScope *Scope,
   3142                           StringRef Name, DIFile *File, unsigned Line,
   3143                           StorageType Storage,
   3144                           bool ShouldCreate = true) {
   3145     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
   3146                    Line, Storage, ShouldCreate);
   3147   }
   3148   static DILabel *getImpl(LLVMContext &Context, Metadata *Scope,
   3149                           MDString *Name, Metadata *File, unsigned Line,
   3150                           StorageType Storage,
   3151                           bool ShouldCreate = true);
   3152 
   3153   TempDILabel cloneImpl() const {
   3154     return getTemporary(getContext(), getScope(), getName(), getFile(),
   3155                         getLine());
   3156   }
   3157 
   3158 public:
   3159   DEFINE_MDNODE_GET(DILabel,
   3160                     (DILocalScope * Scope, StringRef Name, DIFile *File,
   3161                      unsigned Line),
   3162                     (Scope, Name, File, Line))
   3163   DEFINE_MDNODE_GET(DILabel,
   3164                     (Metadata * Scope, MDString *Name, Metadata *File,
   3165                      unsigned Line),
   3166                     (Scope, Name, File, Line))
   3167 
   3168   TempDILabel clone() const { return cloneImpl(); }
   3169 
   3170   /// Get the local scope for this label.
   3171   ///
   3172   /// Labels must be defined in a local scope.
   3173   DILocalScope *getScope() const {
   3174     return cast_or_null<DILocalScope>(getRawScope());
   3175   }
   3176   unsigned getLine() const { return Line; }
   3177   StringRef getName() const { return getStringOperand(1); }
   3178   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   3179 
   3180   Metadata *getRawScope() const { return getOperand(0); }
   3181   MDString *getRawName() const { return getOperandAs<MDString>(1); }
   3182   Metadata *getRawFile() const { return getOperand(2); }
   3183 
   3184   /// Check that a location is valid for this label.
   3185   ///
   3186   /// Check that \c DL exists, is in the same subprogram, and has the same
   3187   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
   3188   /// to a \a DbgInfoIntrinsic.)
   3189   bool isValidLocationForIntrinsic(const DILocation *DL) const {
   3190     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
   3191   }
   3192 
   3193   static bool classof(const Metadata *MD) {
   3194     return MD->getMetadataID() == DILabelKind;
   3195   }
   3196 };
   3197 
   3198 class DIObjCProperty : public DINode {
   3199   friend class LLVMContextImpl;
   3200   friend class MDNode;
   3201 
   3202   unsigned Line;
   3203   unsigned Attributes;
   3204 
   3205   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
   3206                  unsigned Attributes, ArrayRef<Metadata *> Ops)
   3207       : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
   3208                Ops),
   3209         Line(Line), Attributes(Attributes) {}
   3210   ~DIObjCProperty() = default;
   3211 
   3212   static DIObjCProperty *
   3213   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
   3214           StringRef GetterName, StringRef SetterName, unsigned Attributes,
   3215           DIType *Type, StorageType Storage, bool ShouldCreate = true) {
   3216     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
   3217                    getCanonicalMDString(Context, GetterName),
   3218                    getCanonicalMDString(Context, SetterName), Attributes, Type,
   3219                    Storage, ShouldCreate);
   3220   }
   3221   static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
   3222                                  Metadata *File, unsigned Line,
   3223                                  MDString *GetterName, MDString *SetterName,
   3224                                  unsigned Attributes, Metadata *Type,
   3225                                  StorageType Storage, bool ShouldCreate = true);
   3226 
   3227   TempDIObjCProperty cloneImpl() const {
   3228     return getTemporary(getContext(), getName(), getFile(), getLine(),
   3229                         getGetterName(), getSetterName(), getAttributes(),
   3230                         getType());
   3231   }
   3232 
   3233 public:
   3234   DEFINE_MDNODE_GET(DIObjCProperty,
   3235                     (StringRef Name, DIFile *File, unsigned Line,
   3236                      StringRef GetterName, StringRef SetterName,
   3237                      unsigned Attributes, DIType *Type),
   3238                     (Name, File, Line, GetterName, SetterName, Attributes,
   3239                      Type))
   3240   DEFINE_MDNODE_GET(DIObjCProperty,
   3241                     (MDString * Name, Metadata *File, unsigned Line,
   3242                      MDString *GetterName, MDString *SetterName,
   3243                      unsigned Attributes, Metadata *Type),
   3244                     (Name, File, Line, GetterName, SetterName, Attributes,
   3245                      Type))
   3246 
   3247   TempDIObjCProperty clone() const { return cloneImpl(); }
   3248 
   3249   unsigned getLine() const { return Line; }
   3250   unsigned getAttributes() const { return Attributes; }
   3251   StringRef getName() const { return getStringOperand(0); }
   3252   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   3253   StringRef getGetterName() const { return getStringOperand(2); }
   3254   StringRef getSetterName() const { return getStringOperand(3); }
   3255   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
   3256 
   3257   StringRef getFilename() const {
   3258     if (auto *F = getFile())
   3259       return F->getFilename();
   3260     return "";
   3261   }
   3262 
   3263   StringRef getDirectory() const {
   3264     if (auto *F = getFile())
   3265       return F->getDirectory();
   3266     return "";
   3267   }
   3268 
   3269   MDString *getRawName() const { return getOperandAs<MDString>(0); }
   3270   Metadata *getRawFile() const { return getOperand(1); }
   3271   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
   3272   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
   3273   Metadata *getRawType() const { return getOperand(4); }
   3274 
   3275   static bool classof(const Metadata *MD) {
   3276     return MD->getMetadataID() == DIObjCPropertyKind;
   3277   }
   3278 };
   3279 
   3280 /// An imported module (C++ using directive or similar).
   3281 class DIImportedEntity : public DINode {
   3282   friend class LLVMContextImpl;
   3283   friend class MDNode;
   3284 
   3285   unsigned Line;
   3286 
   3287   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
   3288                    unsigned Line, ArrayRef<Metadata *> Ops)
   3289       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
   3290   ~DIImportedEntity() = default;
   3291 
   3292   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
   3293                                    DIScope *Scope, DINode *Entity, DIFile *File,
   3294                                    unsigned Line, StringRef Name,
   3295                                    StorageType Storage,
   3296                                    bool ShouldCreate = true) {
   3297     return getImpl(Context, Tag, Scope, Entity, File, Line,
   3298                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
   3299   }
   3300   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
   3301                                    Metadata *Scope, Metadata *Entity,
   3302                                    Metadata *File, unsigned Line,
   3303                                    MDString *Name, StorageType Storage,
   3304                                    bool ShouldCreate = true);
   3305 
   3306   TempDIImportedEntity cloneImpl() const {
   3307     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
   3308                         getFile(), getLine(), getName());
   3309   }
   3310 
   3311 public:
   3312   DEFINE_MDNODE_GET(DIImportedEntity,
   3313                     (unsigned Tag, DIScope *Scope, DINode *Entity, DIFile *File,
   3314                      unsigned Line, StringRef Name = ""),
   3315                     (Tag, Scope, Entity, File, Line, Name))
   3316   DEFINE_MDNODE_GET(DIImportedEntity,
   3317                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
   3318                      Metadata *File, unsigned Line, MDString *Name),
   3319                     (Tag, Scope, Entity, File, Line, Name))
   3320 
   3321   TempDIImportedEntity clone() const { return cloneImpl(); }
   3322 
   3323   unsigned getLine() const { return Line; }
   3324   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   3325   DINode *getEntity() const { return cast_or_null<DINode>(getRawEntity()); }
   3326   StringRef getName() const { return getStringOperand(2); }
   3327   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   3328 
   3329   Metadata *getRawScope() const { return getOperand(0); }
   3330   Metadata *getRawEntity() const { return getOperand(1); }
   3331   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   3332   Metadata *getRawFile() const { return getOperand(3); }
   3333 
   3334   static bool classof(const Metadata *MD) {
   3335     return MD->getMetadataID() == DIImportedEntityKind;
   3336   }
   3337 };
   3338 
   3339 /// A pair of DIGlobalVariable and DIExpression.
   3340 class DIGlobalVariableExpression : public MDNode {
   3341   friend class LLVMContextImpl;
   3342   friend class MDNode;
   3343 
   3344   DIGlobalVariableExpression(LLVMContext &C, StorageType Storage,
   3345                              ArrayRef<Metadata *> Ops)
   3346       : MDNode(C, DIGlobalVariableExpressionKind, Storage, Ops) {}
   3347   ~DIGlobalVariableExpression() = default;
   3348 
   3349   static DIGlobalVariableExpression *
   3350   getImpl(LLVMContext &Context, Metadata *Variable, Metadata *Expression,
   3351           StorageType Storage, bool ShouldCreate = true);
   3352 
   3353   TempDIGlobalVariableExpression cloneImpl() const {
   3354     return getTemporary(getContext(), getVariable(), getExpression());
   3355   }
   3356 
   3357 public:
   3358   DEFINE_MDNODE_GET(DIGlobalVariableExpression,
   3359                     (Metadata * Variable, Metadata *Expression),
   3360                     (Variable, Expression))
   3361 
   3362   TempDIGlobalVariableExpression clone() const { return cloneImpl(); }
   3363 
   3364   Metadata *getRawVariable() const { return getOperand(0); }
   3365 
   3366   DIGlobalVariable *getVariable() const {
   3367     return cast_or_null<DIGlobalVariable>(getRawVariable());
   3368   }
   3369 
   3370   Metadata *getRawExpression() const { return getOperand(1); }
   3371 
   3372   DIExpression *getExpression() const {
   3373     return cast<DIExpression>(getRawExpression());
   3374   }
   3375 
   3376   static bool classof(const Metadata *MD) {
   3377     return MD->getMetadataID() == DIGlobalVariableExpressionKind;
   3378   }
   3379 };
   3380 
   3381 /// Macro Info DWARF-like metadata node.
   3382 ///
   3383 /// A metadata node with a DWARF macro info (i.e., a constant named
   3384 /// \c DW_MACINFO_*, defined in llvm/BinaryFormat/Dwarf.h).  Called \a
   3385 /// DIMacroNode
   3386 /// because it's potentially used for non-DWARF output.
   3387 class DIMacroNode : public MDNode {
   3388   friend class LLVMContextImpl;
   3389   friend class MDNode;
   3390 
   3391 protected:
   3392   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
   3393               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
   3394       : MDNode(C, ID, Storage, Ops1, Ops2) {
   3395     assert(MIType < 1u << 16);
   3396     SubclassData16 = MIType;
   3397   }
   3398   ~DIMacroNode() = default;
   3399 
   3400   template <class Ty> Ty *getOperandAs(unsigned I) const {
   3401     return cast_or_null<Ty>(getOperand(I));
   3402   }
   3403 
   3404   StringRef getStringOperand(unsigned I) const {
   3405     if (auto *S = getOperandAs<MDString>(I))
   3406       return S->getString();
   3407     return StringRef();
   3408   }
   3409 
   3410   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
   3411     if (S.empty())
   3412       return nullptr;
   3413     return MDString::get(Context, S);
   3414   }
   3415 
   3416 public:
   3417   unsigned getMacinfoType() const { return SubclassData16; }
   3418 
   3419   static bool classof(const Metadata *MD) {
   3420     switch (MD->getMetadataID()) {
   3421     default:
   3422       return false;
   3423     case DIMacroKind:
   3424     case DIMacroFileKind:
   3425       return true;
   3426     }
   3427   }
   3428 };
   3429 
   3430 class DIMacro : public DIMacroNode {
   3431   friend class LLVMContextImpl;
   3432   friend class MDNode;
   3433 
   3434   unsigned Line;
   3435 
   3436   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
   3437           ArrayRef<Metadata *> Ops)
   3438       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops), Line(Line) {}
   3439   ~DIMacro() = default;
   3440 
   3441   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
   3442                           StringRef Name, StringRef Value, StorageType Storage,
   3443                           bool ShouldCreate = true) {
   3444     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
   3445                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
   3446   }
   3447   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
   3448                           MDString *Name, MDString *Value, StorageType Storage,
   3449                           bool ShouldCreate = true);
   3450 
   3451   TempDIMacro cloneImpl() const {
   3452     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
   3453                         getValue());
   3454   }
   3455 
   3456 public:
   3457   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, StringRef Name,
   3458                               StringRef Value = ""),
   3459                     (MIType, Line, Name, Value))
   3460   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, MDString *Name,
   3461                               MDString *Value),
   3462                     (MIType, Line, Name, Value))
   3463 
   3464   TempDIMacro clone() const { return cloneImpl(); }
   3465 
   3466   unsigned getLine() const { return Line; }
   3467 
   3468   StringRef getName() const { return getStringOperand(0); }
   3469   StringRef getValue() const { return getStringOperand(1); }
   3470 
   3471   MDString *getRawName() const { return getOperandAs<MDString>(0); }
   3472   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
   3473 
   3474   static bool classof(const Metadata *MD) {
   3475     return MD->getMetadataID() == DIMacroKind;
   3476   }
   3477 };
   3478 
   3479 class DIMacroFile : public DIMacroNode {
   3480   friend class LLVMContextImpl;
   3481   friend class MDNode;
   3482 
   3483   unsigned Line;
   3484 
   3485   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
   3486               unsigned Line, ArrayRef<Metadata *> Ops)
   3487       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops), Line(Line) {}
   3488   ~DIMacroFile() = default;
   3489 
   3490   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
   3491                               unsigned Line, DIFile *File,
   3492                               DIMacroNodeArray Elements, StorageType Storage,
   3493                               bool ShouldCreate = true) {
   3494     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
   3495                    Elements.get(), Storage, ShouldCreate);
   3496   }
   3497 
   3498   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
   3499                               unsigned Line, Metadata *File, Metadata *Elements,
   3500                               StorageType Storage, bool ShouldCreate = true);
   3501 
   3502   TempDIMacroFile cloneImpl() const {
   3503     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
   3504                         getElements());
   3505   }
   3506 
   3507 public:
   3508   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line, DIFile *File,
   3509                                   DIMacroNodeArray Elements),
   3510                     (MIType, Line, File, Elements))
   3511   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line,
   3512                                   Metadata *File, Metadata *Elements),
   3513                     (MIType, Line, File, Elements))
   3514 
   3515   TempDIMacroFile clone() const { return cloneImpl(); }
   3516 
   3517   void replaceElements(DIMacroNodeArray Elements) {
   3518 #ifndef NDEBUG
   3519     for (DIMacroNode *Op : getElements())
   3520       assert(is_contained(Elements->operands(), Op) &&
   3521              "Lost a macro node during macro node list replacement");
   3522 #endif
   3523     replaceOperandWith(1, Elements.get());
   3524   }
   3525 
   3526   unsigned getLine() const { return Line; }
   3527   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   3528 
   3529   DIMacroNodeArray getElements() const {
   3530     return cast_or_null<MDTuple>(getRawElements());
   3531   }
   3532 
   3533   Metadata *getRawFile() const { return getOperand(0); }
   3534   Metadata *getRawElements() const { return getOperand(1); }
   3535 
   3536   static bool classof(const Metadata *MD) {
   3537     return MD->getMetadataID() == DIMacroFileKind;
   3538   }
   3539 };
   3540 
   3541 /// List of ValueAsMetadata, to be used as an argument to a dbg.value
   3542 /// intrinsic.
   3543 class DIArgList : public MDNode {
   3544   friend class LLVMContextImpl;
   3545   friend class MDNode;
   3546   using iterator = SmallVectorImpl<ValueAsMetadata *>::iterator;
   3547 
   3548   SmallVector<ValueAsMetadata *, 4> Args;
   3549 
   3550   DIArgList(LLVMContext &C, StorageType Storage,
   3551             ArrayRef<ValueAsMetadata *> Args)
   3552       : MDNode(C, DIArgListKind, Storage, None),
   3553         Args(Args.begin(), Args.end()) {
   3554     track();
   3555   }
   3556   ~DIArgList() { untrack(); }
   3557 
   3558   static DIArgList *getImpl(LLVMContext &Context,
   3559                             ArrayRef<ValueAsMetadata *> Args,
   3560                             StorageType Storage, bool ShouldCreate = true);
   3561 
   3562   TempDIArgList cloneImpl() const {
   3563     return getTemporary(getContext(), getArgs());
   3564   }
   3565 
   3566   void track();
   3567   void untrack();
   3568   void dropAllReferences();
   3569 
   3570 public:
   3571   DEFINE_MDNODE_GET(DIArgList, (ArrayRef<ValueAsMetadata *> Args), (Args))
   3572 
   3573   TempDIArgList clone() const { return cloneImpl(); }
   3574 
   3575   ArrayRef<ValueAsMetadata *> getArgs() const { return Args; }
   3576 
   3577   iterator args_begin() { return Args.begin(); }
   3578   iterator args_end() { return Args.end(); }
   3579 
   3580   static bool classof(const Metadata *MD) {
   3581     return MD->getMetadataID() == DIArgListKind;
   3582   }
   3583 
   3584   void handleChangedOperand(void *Ref, Metadata *New);
   3585 };
   3586 
   3587 /// Identifies a unique instance of a variable.
   3588 ///
   3589 /// Storage for identifying a potentially inlined instance of a variable,
   3590 /// or a fragment thereof. This guarantees that exactly one variable instance
   3591 /// may be identified by this class, even when that variable is a fragment of
   3592 /// an aggregate variable and/or there is another inlined instance of the same
   3593 /// source code variable nearby.
   3594 /// This class does not necessarily uniquely identify that variable: it is
   3595 /// possible that a DebugVariable with different parameters may point to the
   3596 /// same variable instance, but not that one DebugVariable points to multiple
   3597 /// variable instances.
   3598 class DebugVariable {
   3599   using FragmentInfo = DIExpression::FragmentInfo;
   3600 
   3601   const DILocalVariable *Variable;
   3602   Optional<FragmentInfo> Fragment;
   3603   const DILocation *InlinedAt;
   3604 
   3605   /// Fragment that will overlap all other fragments. Used as default when
   3606   /// caller demands a fragment.
   3607   static const FragmentInfo DefaultFragment;
   3608 
   3609 public:
   3610   DebugVariable(const DILocalVariable *Var, Optional<FragmentInfo> FragmentInfo,
   3611                 const DILocation *InlinedAt)
   3612       : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
   3613 
   3614   DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
   3615                 const DILocation *InlinedAt)
   3616       : Variable(Var),
   3617         Fragment(DIExpr ? DIExpr->getFragmentInfo() : NoneType()),
   3618         InlinedAt(InlinedAt) {}
   3619 
   3620   const DILocalVariable *getVariable() const { return Variable; }
   3621   Optional<FragmentInfo> getFragment() const { return Fragment; }
   3622   const DILocation *getInlinedAt() const { return InlinedAt; }
   3623 
   3624   FragmentInfo getFragmentOrDefault() const {
   3625     return Fragment.getValueOr(DefaultFragment);
   3626   }
   3627 
   3628   static bool isDefaultFragment(const FragmentInfo F) {
   3629     return F == DefaultFragment;
   3630   }
   3631 
   3632   bool operator==(const DebugVariable &Other) const {
   3633     return std::tie(Variable, Fragment, InlinedAt) ==
   3634            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
   3635   }
   3636 
   3637   bool operator<(const DebugVariable &Other) const {
   3638     return std::tie(Variable, Fragment, InlinedAt) <
   3639            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
   3640   }
   3641 };
   3642 
   3643 template <> struct DenseMapInfo<DebugVariable> {
   3644   using FragmentInfo = DIExpression::FragmentInfo;
   3645 
   3646   /// Empty key: no key should be generated that has no DILocalVariable.
   3647   static inline DebugVariable getEmptyKey() {
   3648     return DebugVariable(nullptr, NoneType(), nullptr);
   3649   }
   3650 
   3651   /// Difference in tombstone is that the Optional is meaningful.
   3652   static inline DebugVariable getTombstoneKey() {
   3653     return DebugVariable(nullptr, {{0, 0}}, nullptr);
   3654   }
   3655 
   3656   static unsigned getHashValue(const DebugVariable &D) {
   3657     unsigned HV = 0;
   3658     const Optional<FragmentInfo> Fragment = D.getFragment();
   3659     if (Fragment)
   3660       HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
   3661 
   3662     return hash_combine(D.getVariable(), HV, D.getInlinedAt());
   3663   }
   3664 
   3665   static bool isEqual(const DebugVariable &A, const DebugVariable &B) {
   3666     return A == B;
   3667   }
   3668 };
   3669 
   3670 } // end namespace llvm
   3671 
   3672 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
   3673 #undef DEFINE_MDNODE_GET_UNPACK
   3674 #undef DEFINE_MDNODE_GET
   3675 
   3676 #endif // LLVM_IR_DEBUGINFOMETADATA_H
   3677