1 //===- LLVMContextImpl.h - The LLVMContextImpl opaque class -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file declares LLVMContextImpl, the opaque implementation
10 //  of LLVMContext.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_IR_LLVMCONTEXTIMPL_H
15 #define LLVM_LIB_IR_LLVMCONTEXTIMPL_H
16 
17 #include "AttributeImpl.h"
18 #include "ConstantsContext.h"
19 #include "llvm/ADT/APFloat.h"
20 #include "llvm/ADT/APInt.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/DenseMapInfo.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/Hashing.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfoMetadata.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/LLVMRemarkStreamer.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/TrackingMDRef.h"
40 #include "llvm/Support/Allocator.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/StringSaver.h"
43 #include "llvm/Support/YAMLTraits.h"
44 #include <algorithm>
45 #include <cassert>
46 #include <cstddef>
47 #include <cstdint>
48 #include <memory>
49 #include <string>
50 #include <utility>
51 #include <vector>
52 
53 namespace llvm {
54 
55 class StringRef;
56 class Type;
57 class Value;
58 class ValueHandleBase;
59 
60 struct DenseMapAPIntKeyInfo {
61   static inline APInt getEmptyKey() {
62     APInt V(nullptr, 0);
63     V.U.VAL = 0;
64     return V;
65   }
66 
67   static inline APInt getTombstoneKey() {
68     APInt V(nullptr, 0);
69     V.U.VAL = 1;
70     return V;
71   }
72 
73   static unsigned getHashValue(const APInt &Key) {
74     return static_cast<unsigned>(hash_value(Key));
75   }
76 
77   static bool isEqual(const APInt &LHS, const APInt &RHS) {
78     return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;
79   }
80 };
81 
82 struct DenseMapAPFloatKeyInfo {
83   static inline APFloat getEmptyKey() { return APFloat(APFloat::Bogus(), 1); }
84   static inline APFloat getTombstoneKey() { return APFloat(APFloat::Bogus(), 2); }
85 
86   static unsigned getHashValue(const APFloat &Key) {
87     return static_cast<unsigned>(hash_value(Key));
88   }
89 
90   static bool isEqual(const APFloat &LHS, const APFloat &RHS) {
91     return LHS.bitwiseIsEqual(RHS);
92   }
93 };
94 
95 struct AnonStructTypeKeyInfo {
96   struct KeyTy {
97     ArrayRef<Type*> ETypes;
98     bool isPacked;
99 
100     KeyTy(const ArrayRef<Type*>& E, bool P) :
101       ETypes(E), isPacked(P) {}
102 
103     KeyTy(const StructType *ST)
104         : ETypes(ST->elements()), isPacked(ST->isPacked()) {}
105 
106     bool operator==(const KeyTy& that) const {
107       if (isPacked != that.isPacked)
108         return false;
109       if (ETypes != that.ETypes)
110         return false;
111       return true;
112     }
113     bool operator!=(const KeyTy& that) const {
114       return !this->operator==(that);
115     }
116   };
117 
118   static inline StructType* getEmptyKey() {
119     return DenseMapInfo<StructType*>::getEmptyKey();
120   }
121 
122   static inline StructType* getTombstoneKey() {
123     return DenseMapInfo<StructType*>::getTombstoneKey();
124   }
125 
126   static unsigned getHashValue(const KeyTy& Key) {
127     return hash_combine(hash_combine_range(Key.ETypes.begin(),
128                                            Key.ETypes.end()),
129                         Key.isPacked);
130   }
131 
132   static unsigned getHashValue(const StructType *ST) {
133     return getHashValue(KeyTy(ST));
134   }
135 
136   static bool isEqual(const KeyTy& LHS, const StructType *RHS) {
137     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
138       return false;
139     return LHS == KeyTy(RHS);
140   }
141 
142   static bool isEqual(const StructType *LHS, const StructType *RHS) {
143     return LHS == RHS;
144   }
145 };
146 
147 struct FunctionTypeKeyInfo {
148   struct KeyTy {
149     const Type *ReturnType;
150     ArrayRef<Type*> Params;
151     bool isVarArg;
152 
153     KeyTy(const Type* R, const ArrayRef<Type*>& P, bool V) :
154       ReturnType(R), Params(P), isVarArg(V) {}
155     KeyTy(const FunctionType *FT)
156         : ReturnType(FT->getReturnType()), Params(FT->params()),
157           isVarArg(FT->isVarArg()) {}
158 
159     bool operator==(const KeyTy& that) const {
160       if (ReturnType != that.ReturnType)
161         return false;
162       if (isVarArg != that.isVarArg)
163         return false;
164       if (Params != that.Params)
165         return false;
166       return true;
167     }
168     bool operator!=(const KeyTy& that) const {
169       return !this->operator==(that);
170     }
171   };
172 
173   static inline FunctionType* getEmptyKey() {
174     return DenseMapInfo<FunctionType*>::getEmptyKey();
175   }
176 
177   static inline FunctionType* getTombstoneKey() {
178     return DenseMapInfo<FunctionType*>::getTombstoneKey();
179   }
180 
181   static unsigned getHashValue(const KeyTy& Key) {
182     return hash_combine(Key.ReturnType,
183                         hash_combine_range(Key.Params.begin(),
184                                            Key.Params.end()),
185                         Key.isVarArg);
186   }
187 
188   static unsigned getHashValue(const FunctionType *FT) {
189     return getHashValue(KeyTy(FT));
190   }
191 
192   static bool isEqual(const KeyTy& LHS, const FunctionType *RHS) {
193     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
194       return false;
195     return LHS == KeyTy(RHS);
196   }
197 
198   static bool isEqual(const FunctionType *LHS, const FunctionType *RHS) {
199     return LHS == RHS;
200   }
201 };
202 
203 /// Structure for hashing arbitrary MDNode operands.
204 class MDNodeOpsKey {
205   ArrayRef<Metadata *> RawOps;
206   ArrayRef<MDOperand> Ops;
207   unsigned Hash;
208 
209 protected:
210   MDNodeOpsKey(ArrayRef<Metadata *> Ops)
211       : RawOps(Ops), Hash(calculateHash(Ops)) {}
212 
213   template <class NodeTy>
214   MDNodeOpsKey(const NodeTy *N, unsigned Offset = 0)
215       : Ops(N->op_begin() + Offset, N->op_end()), Hash(N->getHash()) {}
216 
217   template <class NodeTy>
218   bool compareOps(const NodeTy *RHS, unsigned Offset = 0) const {
219     if (getHash() != RHS->getHash())
220       return false;
221 
222     assert((RawOps.empty() || Ops.empty()) && "Two sets of operands?");
223     return RawOps.empty() ? compareOps(Ops, RHS, Offset)
224                           : compareOps(RawOps, RHS, Offset);
225   }
226 
227   static unsigned calculateHash(MDNode *N, unsigned Offset = 0);
228 
229 private:
230   template <class T>
231   static bool compareOps(ArrayRef<T> Ops, const MDNode *RHS, unsigned Offset) {
232     if (Ops.size() != RHS->getNumOperands() - Offset)
233       return false;
234     return std::equal(Ops.begin(), Ops.end(), RHS->op_begin() + Offset);
235   }
236 
237   static unsigned calculateHash(ArrayRef<Metadata *> Ops);
238 
239 public:
240   unsigned getHash() const { return Hash; }
241 };
242 
243 template <class NodeTy> struct MDNodeKeyImpl;
244 
245 /// Configuration point for MDNodeInfo::isEqual().
246 template <class NodeTy> struct MDNodeSubsetEqualImpl {
247   using KeyTy = MDNodeKeyImpl<NodeTy>;
248 
249   static bool isSubsetEqual(const KeyTy &LHS, const NodeTy *RHS) {
250     return false;
251   }
252 
253   static bool isSubsetEqual(const NodeTy *LHS, const NodeTy *RHS) {
254     return false;
255   }
256 };
257 
258 /// DenseMapInfo for MDTuple.
259 ///
260 /// Note that we don't need the is-function-local bit, since that's implicit in
261 /// the operands.
262 template <> struct MDNodeKeyImpl<MDTuple> : MDNodeOpsKey {
263   MDNodeKeyImpl(ArrayRef<Metadata *> Ops) : MDNodeOpsKey(Ops) {}
264   MDNodeKeyImpl(const MDTuple *N) : MDNodeOpsKey(N) {}
265 
266   bool isKeyOf(const MDTuple *RHS) const { return compareOps(RHS); }
267 
268   unsigned getHashValue() const { return getHash(); }
269 
270   static unsigned calculateHash(MDTuple *N) {
271     return MDNodeOpsKey::calculateHash(N);
272   }
273 };
274 
275 /// DenseMapInfo for DILocation.
276 template <> struct MDNodeKeyImpl<DILocation> {
277   unsigned Line;
278   unsigned Column;
279   Metadata *Scope;
280   Metadata *InlinedAt;
281   bool ImplicitCode;
282 
283   MDNodeKeyImpl(unsigned Line, unsigned Column, Metadata *Scope,
284                 Metadata *InlinedAt, bool ImplicitCode)
285       : Line(Line), Column(Column), Scope(Scope), InlinedAt(InlinedAt),
286         ImplicitCode(ImplicitCode) {}
287   MDNodeKeyImpl(const DILocation *L)
288       : Line(L->getLine()), Column(L->getColumn()), Scope(L->getRawScope()),
289         InlinedAt(L->getRawInlinedAt()), ImplicitCode(L->isImplicitCode()) {}
290 
291   bool isKeyOf(const DILocation *RHS) const {
292     return Line == RHS->getLine() && Column == RHS->getColumn() &&
293            Scope == RHS->getRawScope() && InlinedAt == RHS->getRawInlinedAt() &&
294            ImplicitCode == RHS->isImplicitCode();
295   }
296 
297   unsigned getHashValue() const {
298     return hash_combine(Line, Column, Scope, InlinedAt, ImplicitCode);
299   }
300 };
301 
302 /// DenseMapInfo for GenericDINode.
303 template <> struct MDNodeKeyImpl<GenericDINode> : MDNodeOpsKey {
304   unsigned Tag;
305   MDString *Header;
306 
307   MDNodeKeyImpl(unsigned Tag, MDString *Header, ArrayRef<Metadata *> DwarfOps)
308       : MDNodeOpsKey(DwarfOps), Tag(Tag), Header(Header) {}
309   MDNodeKeyImpl(const GenericDINode *N)
310       : MDNodeOpsKey(N, 1), Tag(N->getTag()), Header(N->getRawHeader()) {}
311 
312   bool isKeyOf(const GenericDINode *RHS) const {
313     return Tag == RHS->getTag() && Header == RHS->getRawHeader() &&
314            compareOps(RHS, 1);
315   }
316 
317   unsigned getHashValue() const { return hash_combine(getHash(), Tag, Header); }
318 
319   static unsigned calculateHash(GenericDINode *N) {
320     return MDNodeOpsKey::calculateHash(N, 1);
321   }
322 };
323 
324 template <> struct MDNodeKeyImpl<DISubrange> {
325   Metadata *CountNode;
326   int64_t LowerBound;
327 
328   MDNodeKeyImpl(Metadata *CountNode, int64_t LowerBound)
329       : CountNode(CountNode), LowerBound(LowerBound) {}
330   MDNodeKeyImpl(const DISubrange *N)
331       : CountNode(N->getRawCountNode()),
332         LowerBound(N->getLowerBound()) {}
333 
334   bool isKeyOf(const DISubrange *RHS) const {
335     if (LowerBound != RHS->getLowerBound())
336       return false;
337 
338     if (auto *RHSCount = RHS->getCount().dyn_cast<ConstantInt*>())
339       if (auto *MD = dyn_cast<ConstantAsMetadata>(CountNode))
340         if (RHSCount->getSExtValue() ==
341             cast<ConstantInt>(MD->getValue())->getSExtValue())
342           return true;
343 
344     return CountNode == RHS->getRawCountNode();
345   }
346 
347   unsigned getHashValue() const {
348     if (auto *MD = dyn_cast<ConstantAsMetadata>(CountNode))
349       return hash_combine(cast<ConstantInt>(MD->getValue())->getSExtValue(),
350                           LowerBound);
351     return hash_combine(CountNode, LowerBound);
352   }
353 };
354 
355 template <> struct MDNodeKeyImpl<DIEnumerator> {
356   APInt Value;
357   MDString *Name;
358   bool IsUnsigned;
359 
360   MDNodeKeyImpl(APInt Value, bool IsUnsigned, MDString *Name)
361       : Value(Value), Name(Name), IsUnsigned(IsUnsigned) {}
362   MDNodeKeyImpl(int64_t Value, bool IsUnsigned, MDString *Name)
363       : Value(APInt(64, Value, !IsUnsigned)), Name(Name),
364         IsUnsigned(IsUnsigned) {}
365   MDNodeKeyImpl(const DIEnumerator *N)
366       : Value(N->getValue()), Name(N->getRawName()),
367         IsUnsigned(N->isUnsigned()) {}
368 
369   bool isKeyOf(const DIEnumerator *RHS) const {
370     return APInt::isSameValue(Value, RHS->getValue()) &&
371            IsUnsigned == RHS->isUnsigned() && Name == RHS->getRawName();
372   }
373 
374   unsigned getHashValue() const { return hash_combine(Value, Name); }
375 };
376 
377 template <> struct MDNodeKeyImpl<DIBasicType> {
378   unsigned Tag;
379   MDString *Name;
380   uint64_t SizeInBits;
381   uint32_t AlignInBits;
382   unsigned Encoding;
383   unsigned Flags;
384 
385   MDNodeKeyImpl(unsigned Tag, MDString *Name, uint64_t SizeInBits,
386                 uint32_t AlignInBits, unsigned Encoding, unsigned Flags)
387       : Tag(Tag), Name(Name), SizeInBits(SizeInBits), AlignInBits(AlignInBits),
388         Encoding(Encoding), Flags(Flags) {}
389   MDNodeKeyImpl(const DIBasicType *N)
390       : Tag(N->getTag()), Name(N->getRawName()), SizeInBits(N->getSizeInBits()),
391         AlignInBits(N->getAlignInBits()), Encoding(N->getEncoding()), Flags(N->getFlags()) {}
392 
393   bool isKeyOf(const DIBasicType *RHS) const {
394     return Tag == RHS->getTag() && Name == RHS->getRawName() &&
395            SizeInBits == RHS->getSizeInBits() &&
396            AlignInBits == RHS->getAlignInBits() &&
397            Encoding == RHS->getEncoding() &&
398            Flags == RHS->getFlags();
399   }
400 
401   unsigned getHashValue() const {
402     return hash_combine(Tag, Name, SizeInBits, AlignInBits, Encoding);
403   }
404 };
405 
406 template <> struct MDNodeKeyImpl<DIDerivedType> {
407   unsigned Tag;
408   MDString *Name;
409   Metadata *File;
410   unsigned Line;
411   Metadata *Scope;
412   Metadata *BaseType;
413   uint64_t SizeInBits;
414   uint64_t OffsetInBits;
415   uint32_t AlignInBits;
416   Optional<unsigned> DWARFAddressSpace;
417   unsigned Flags;
418   Metadata *ExtraData;
419 
420   MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
421                 Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
422                 uint32_t AlignInBits, uint64_t OffsetInBits,
423                 Optional<unsigned> DWARFAddressSpace, unsigned Flags,
424                 Metadata *ExtraData)
425       : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
426         BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
427         AlignInBits(AlignInBits), DWARFAddressSpace(DWARFAddressSpace),
428         Flags(Flags), ExtraData(ExtraData) {}
429   MDNodeKeyImpl(const DIDerivedType *N)
430       : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
431         Line(N->getLine()), Scope(N->getRawScope()),
432         BaseType(N->getRawBaseType()), SizeInBits(N->getSizeInBits()),
433         OffsetInBits(N->getOffsetInBits()), AlignInBits(N->getAlignInBits()),
434         DWARFAddressSpace(N->getDWARFAddressSpace()), Flags(N->getFlags()),
435         ExtraData(N->getRawExtraData()) {}
436 
437   bool isKeyOf(const DIDerivedType *RHS) const {
438     return Tag == RHS->getTag() && Name == RHS->getRawName() &&
439            File == RHS->getRawFile() && Line == RHS->getLine() &&
440            Scope == RHS->getRawScope() && BaseType == RHS->getRawBaseType() &&
441            SizeInBits == RHS->getSizeInBits() &&
442            AlignInBits == RHS->getAlignInBits() &&
443            OffsetInBits == RHS->getOffsetInBits() &&
444            DWARFAddressSpace == RHS->getDWARFAddressSpace() &&
445            Flags == RHS->getFlags() &&
446            ExtraData == RHS->getRawExtraData();
447   }
448 
449   unsigned getHashValue() const {
450     // If this is a member inside an ODR type, only hash the type and the name.
451     // Otherwise the hash will be stronger than
452     // MDNodeSubsetEqualImpl::isODRMember().
453     if (Tag == dwarf::DW_TAG_member && Name)
454       if (auto *CT = dyn_cast_or_null<DICompositeType>(Scope))
455         if (CT->getRawIdentifier())
456           return hash_combine(Name, Scope);
457 
458     // Intentionally computes the hash on a subset of the operands for
459     // performance reason. The subset has to be significant enough to avoid
460     // collision "most of the time". There is no correctness issue in case of
461     // collision because of the full check above.
462     return hash_combine(Tag, Name, File, Line, Scope, BaseType, Flags);
463   }
464 };
465 
466 template <> struct MDNodeSubsetEqualImpl<DIDerivedType> {
467   using KeyTy = MDNodeKeyImpl<DIDerivedType>;
468 
469   static bool isSubsetEqual(const KeyTy &LHS, const DIDerivedType *RHS) {
470     return isODRMember(LHS.Tag, LHS.Scope, LHS.Name, RHS);
471   }
472 
473   static bool isSubsetEqual(const DIDerivedType *LHS, const DIDerivedType *RHS) {
474     return isODRMember(LHS->getTag(), LHS->getRawScope(), LHS->getRawName(),
475                        RHS);
476   }
477 
478   /// Subprograms compare equal if they declare the same function in an ODR
479   /// type.
480   static bool isODRMember(unsigned Tag, const Metadata *Scope,
481                           const MDString *Name, const DIDerivedType *RHS) {
482     // Check whether the LHS is eligible.
483     if (Tag != dwarf::DW_TAG_member || !Name)
484       return false;
485 
486     auto *CT = dyn_cast_or_null<DICompositeType>(Scope);
487     if (!CT || !CT->getRawIdentifier())
488       return false;
489 
490     // Compare to the RHS.
491     return Tag == RHS->getTag() && Name == RHS->getRawName() &&
492            Scope == RHS->getRawScope();
493   }
494 };
495 
496 template <> struct MDNodeKeyImpl<DICompositeType> {
497   unsigned Tag;
498   MDString *Name;
499   Metadata *File;
500   unsigned Line;
501   Metadata *Scope;
502   Metadata *BaseType;
503   uint64_t SizeInBits;
504   uint64_t OffsetInBits;
505   uint32_t AlignInBits;
506   unsigned Flags;
507   Metadata *Elements;
508   unsigned RuntimeLang;
509   Metadata *VTableHolder;
510   Metadata *TemplateParams;
511   MDString *Identifier;
512   Metadata *Discriminator;
513 
514   MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
515                 Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
516                 uint32_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
517                 Metadata *Elements, unsigned RuntimeLang,
518                 Metadata *VTableHolder, Metadata *TemplateParams,
519                 MDString *Identifier, Metadata *Discriminator)
520       : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
521         BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
522         AlignInBits(AlignInBits), Flags(Flags), Elements(Elements),
523         RuntimeLang(RuntimeLang), VTableHolder(VTableHolder),
524         TemplateParams(TemplateParams), Identifier(Identifier),
525         Discriminator(Discriminator) {}
526   MDNodeKeyImpl(const DICompositeType *N)
527       : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
528         Line(N->getLine()), Scope(N->getRawScope()),
529         BaseType(N->getRawBaseType()), SizeInBits(N->getSizeInBits()),
530         OffsetInBits(N->getOffsetInBits()), AlignInBits(N->getAlignInBits()),
531         Flags(N->getFlags()), Elements(N->getRawElements()),
532         RuntimeLang(N->getRuntimeLang()), VTableHolder(N->getRawVTableHolder()),
533         TemplateParams(N->getRawTemplateParams()),
534         Identifier(N->getRawIdentifier()),
535         Discriminator(N->getRawDiscriminator()) {}
536 
537   bool isKeyOf(const DICompositeType *RHS) const {
538     return Tag == RHS->getTag() && Name == RHS->getRawName() &&
539            File == RHS->getRawFile() && Line == RHS->getLine() &&
540            Scope == RHS->getRawScope() && BaseType == RHS->getRawBaseType() &&
541            SizeInBits == RHS->getSizeInBits() &&
542            AlignInBits == RHS->getAlignInBits() &&
543            OffsetInBits == RHS->getOffsetInBits() && Flags == RHS->getFlags() &&
544            Elements == RHS->getRawElements() &&
545            RuntimeLang == RHS->getRuntimeLang() &&
546            VTableHolder == RHS->getRawVTableHolder() &&
547            TemplateParams == RHS->getRawTemplateParams() &&
548            Identifier == RHS->getRawIdentifier() &&
549            Discriminator == RHS->getRawDiscriminator();
550   }
551 
552   unsigned getHashValue() const {
553     // Intentionally computes the hash on a subset of the operands for
554     // performance reason. The subset has to be significant enough to avoid
555     // collision "most of the time". There is no correctness issue in case of
556     // collision because of the full check above.
557     return hash_combine(Name, File, Line, BaseType, Scope, Elements,
558                         TemplateParams);
559   }
560 };
561 
562 template <> struct MDNodeKeyImpl<DISubroutineType> {
563   unsigned Flags;
564   uint8_t CC;
565   Metadata *TypeArray;
566 
567   MDNodeKeyImpl(unsigned Flags, uint8_t CC, Metadata *TypeArray)
568       : Flags(Flags), CC(CC), TypeArray(TypeArray) {}
569   MDNodeKeyImpl(const DISubroutineType *N)
570       : Flags(N->getFlags()), CC(N->getCC()), TypeArray(N->getRawTypeArray()) {}
571 
572   bool isKeyOf(const DISubroutineType *RHS) const {
573     return Flags == RHS->getFlags() && CC == RHS->getCC() &&
574            TypeArray == RHS->getRawTypeArray();
575   }
576 
577   unsigned getHashValue() const { return hash_combine(Flags, CC, TypeArray); }
578 };
579 
580 template <> struct MDNodeKeyImpl<DIFile> {
581   MDString *Filename;
582   MDString *Directory;
583   Optional<DIFile::ChecksumInfo<MDString *>> Checksum;
584   Optional<MDString *> Source;
585 
586   MDNodeKeyImpl(MDString *Filename, MDString *Directory,
587                 Optional<DIFile::ChecksumInfo<MDString *>> Checksum,
588                 Optional<MDString *> Source)
589       : Filename(Filename), Directory(Directory), Checksum(Checksum),
590         Source(Source) {}
591   MDNodeKeyImpl(const DIFile *N)
592       : Filename(N->getRawFilename()), Directory(N->getRawDirectory()),
593         Checksum(N->getRawChecksum()), Source(N->getRawSource()) {}
594 
595   bool isKeyOf(const DIFile *RHS) const {
596     return Filename == RHS->getRawFilename() &&
597            Directory == RHS->getRawDirectory() &&
598            Checksum == RHS->getRawChecksum() &&
599            Source == RHS->getRawSource();
600   }
601 
602   unsigned getHashValue() const {
603     return hash_combine(
604         Filename, Directory, Checksum ? Checksum->Kind : 0,
605         Checksum ? Checksum->Value : nullptr, Source.getValueOr(nullptr));
606   }
607 };
608 
609 template <> struct MDNodeKeyImpl<DISubprogram> {
610   Metadata *Scope;
611   MDString *Name;
612   MDString *LinkageName;
613   Metadata *File;
614   unsigned Line;
615   Metadata *Type;
616   unsigned ScopeLine;
617   Metadata *ContainingType;
618   unsigned VirtualIndex;
619   int ThisAdjustment;
620   unsigned Flags;
621   unsigned SPFlags;
622   Metadata *Unit;
623   Metadata *TemplateParams;
624   Metadata *Declaration;
625   Metadata *RetainedNodes;
626   Metadata *ThrownTypes;
627 
628   MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *LinkageName,
629                 Metadata *File, unsigned Line, Metadata *Type,
630                 unsigned ScopeLine, Metadata *ContainingType,
631                 unsigned VirtualIndex, int ThisAdjustment, unsigned Flags,
632                 unsigned SPFlags, Metadata *Unit, Metadata *TemplateParams,
633                 Metadata *Declaration, Metadata *RetainedNodes,
634                 Metadata *ThrownTypes)
635       : Scope(Scope), Name(Name), LinkageName(LinkageName), File(File),
636         Line(Line), Type(Type), ScopeLine(ScopeLine),
637         ContainingType(ContainingType), VirtualIndex(VirtualIndex),
638         ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags),
639         Unit(Unit), TemplateParams(TemplateParams), Declaration(Declaration),
640         RetainedNodes(RetainedNodes), ThrownTypes(ThrownTypes) {}
641   MDNodeKeyImpl(const DISubprogram *N)
642       : Scope(N->getRawScope()), Name(N->getRawName()),
643         LinkageName(N->getRawLinkageName()), File(N->getRawFile()),
644         Line(N->getLine()), Type(N->getRawType()), ScopeLine(N->getScopeLine()),
645         ContainingType(N->getRawContainingType()),
646         VirtualIndex(N->getVirtualIndex()),
647         ThisAdjustment(N->getThisAdjustment()), Flags(N->getFlags()),
648         SPFlags(N->getSPFlags()), Unit(N->getRawUnit()),
649         TemplateParams(N->getRawTemplateParams()),
650         Declaration(N->getRawDeclaration()),
651         RetainedNodes(N->getRawRetainedNodes()),
652         ThrownTypes(N->getRawThrownTypes()) {}
653 
654   bool isKeyOf(const DISubprogram *RHS) const {
655     return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
656            LinkageName == RHS->getRawLinkageName() &&
657            File == RHS->getRawFile() && Line == RHS->getLine() &&
658            Type == RHS->getRawType() && ScopeLine == RHS->getScopeLine() &&
659            ContainingType == RHS->getRawContainingType() &&
660            VirtualIndex == RHS->getVirtualIndex() &&
661            ThisAdjustment == RHS->getThisAdjustment() &&
662            Flags == RHS->getFlags() && SPFlags == RHS->getSPFlags() &&
663            Unit == RHS->getUnit() &&
664            TemplateParams == RHS->getRawTemplateParams() &&
665            Declaration == RHS->getRawDeclaration() &&
666            RetainedNodes == RHS->getRawRetainedNodes() &&
667            ThrownTypes == RHS->getRawThrownTypes();
668   }
669 
670   bool isDefinition() const { return SPFlags & DISubprogram::SPFlagDefinition; }
671 
672   unsigned getHashValue() const {
673     // If this is a declaration inside an ODR type, only hash the type and the
674     // name.  Otherwise the hash will be stronger than
675     // MDNodeSubsetEqualImpl::isDeclarationOfODRMember().
676     if (!isDefinition() && LinkageName)
677       if (auto *CT = dyn_cast_or_null<DICompositeType>(Scope))
678         if (CT->getRawIdentifier())
679           return hash_combine(LinkageName, Scope);
680 
681     // Intentionally computes the hash on a subset of the operands for
682     // performance reason. The subset has to be significant enough to avoid
683     // collision "most of the time". There is no correctness issue in case of
684     // collision because of the full check above.
685     return hash_combine(Name, Scope, File, Type, Line);
686   }
687 };
688 
689 template <> struct MDNodeSubsetEqualImpl<DISubprogram> {
690   using KeyTy = MDNodeKeyImpl<DISubprogram>;
691 
692   static bool isSubsetEqual(const KeyTy &LHS, const DISubprogram *RHS) {
693     return isDeclarationOfODRMember(LHS.isDefinition(), LHS.Scope,
694                                     LHS.LinkageName, LHS.TemplateParams, RHS);
695   }
696 
697   static bool isSubsetEqual(const DISubprogram *LHS, const DISubprogram *RHS) {
698     return isDeclarationOfODRMember(LHS->isDefinition(), LHS->getRawScope(),
699                                     LHS->getRawLinkageName(),
700                                     LHS->getRawTemplateParams(), RHS);
701   }
702 
703   /// Subprograms compare equal if they declare the same function in an ODR
704   /// type.
705   static bool isDeclarationOfODRMember(bool IsDefinition, const Metadata *Scope,
706                                        const MDString *LinkageName,
707                                        const Metadata *TemplateParams,
708                                        const DISubprogram *RHS) {
709     // Check whether the LHS is eligible.
710     if (IsDefinition || !Scope || !LinkageName)
711       return false;
712 
713     auto *CT = dyn_cast_or_null<DICompositeType>(Scope);
714     if (!CT || !CT->getRawIdentifier())
715       return false;
716 
717     // Compare to the RHS.
718     // FIXME: We need to compare template parameters here to avoid incorrect
719     // collisions in mapMetadata when RF_MoveDistinctMDs and a ODR-DISubprogram
720     // has a non-ODR template parameter (i.e., a DICompositeType that does not
721     // have an identifier). Eventually we should decouple ODR logic from
722     // uniquing logic.
723     return IsDefinition == RHS->isDefinition() && Scope == RHS->getRawScope() &&
724            LinkageName == RHS->getRawLinkageName() &&
725            TemplateParams == RHS->getRawTemplateParams();
726   }
727 };
728 
729 template <> struct MDNodeKeyImpl<DILexicalBlock> {
730   Metadata *Scope;
731   Metadata *File;
732   unsigned Line;
733   unsigned Column;
734 
735   MDNodeKeyImpl(Metadata *Scope, Metadata *File, unsigned Line, unsigned Column)
736       : Scope(Scope), File(File), Line(Line), Column(Column) {}
737   MDNodeKeyImpl(const DILexicalBlock *N)
738       : Scope(N->getRawScope()), File(N->getRawFile()), Line(N->getLine()),
739         Column(N->getColumn()) {}
740 
741   bool isKeyOf(const DILexicalBlock *RHS) const {
742     return Scope == RHS->getRawScope() && File == RHS->getRawFile() &&
743            Line == RHS->getLine() && Column == RHS->getColumn();
744   }
745 
746   unsigned getHashValue() const {
747     return hash_combine(Scope, File, Line, Column);
748   }
749 };
750 
751 template <> struct MDNodeKeyImpl<DILexicalBlockFile> {
752   Metadata *Scope;
753   Metadata *File;
754   unsigned Discriminator;
755 
756   MDNodeKeyImpl(Metadata *Scope, Metadata *File, unsigned Discriminator)
757       : Scope(Scope), File(File), Discriminator(Discriminator) {}
758   MDNodeKeyImpl(const DILexicalBlockFile *N)
759       : Scope(N->getRawScope()), File(N->getRawFile()),
760         Discriminator(N->getDiscriminator()) {}
761 
762   bool isKeyOf(const DILexicalBlockFile *RHS) const {
763     return Scope == RHS->getRawScope() && File == RHS->getRawFile() &&
764            Discriminator == RHS->getDiscriminator();
765   }
766 
767   unsigned getHashValue() const {
768     return hash_combine(Scope, File, Discriminator);
769   }
770 };
771 
772 template <> struct MDNodeKeyImpl<DINamespace> {
773   Metadata *Scope;
774   MDString *Name;
775   bool ExportSymbols;
776 
777   MDNodeKeyImpl(Metadata *Scope, MDString *Name, bool ExportSymbols)
778       : Scope(Scope), Name(Name), ExportSymbols(ExportSymbols) {}
779   MDNodeKeyImpl(const DINamespace *N)
780       : Scope(N->getRawScope()), Name(N->getRawName()),
781         ExportSymbols(N->getExportSymbols()) {}
782 
783   bool isKeyOf(const DINamespace *RHS) const {
784     return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
785            ExportSymbols == RHS->getExportSymbols();
786   }
787 
788   unsigned getHashValue() const {
789     return hash_combine(Scope, Name);
790   }
791 };
792 
793 template <> struct MDNodeKeyImpl<DICommonBlock> {
794   Metadata *Scope;
795   Metadata *Decl;
796   MDString *Name;
797   Metadata *File;
798   unsigned LineNo;
799 
800   MDNodeKeyImpl(Metadata *Scope, Metadata *Decl, MDString *Name,
801                 Metadata *File, unsigned LineNo)
802       : Scope(Scope), Decl(Decl), Name(Name), File(File), LineNo(LineNo) {}
803   MDNodeKeyImpl(const DICommonBlock *N)
804       : Scope(N->getRawScope()), Decl(N->getRawDecl()), Name(N->getRawName()),
805         File(N->getRawFile()), LineNo(N->getLineNo()) {}
806 
807   bool isKeyOf(const DICommonBlock *RHS) const {
808     return Scope == RHS->getRawScope() && Decl == RHS->getRawDecl() &&
809       Name == RHS->getRawName() && File == RHS->getRawFile() &&
810       LineNo == RHS->getLineNo();
811   }
812 
813   unsigned getHashValue() const {
814     return hash_combine(Scope, Decl, Name, File, LineNo);
815   }
816 };
817 
818 template <> struct MDNodeKeyImpl<DIModule> {
819   Metadata *Scope;
820   MDString *Name;
821   MDString *ConfigurationMacros;
822   MDString *IncludePath;
823   MDString *APINotesFile;
824 
825   MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *ConfigurationMacros,
826                 MDString *IncludePath, MDString *APINotesFile)
827       : Scope(Scope), Name(Name), ConfigurationMacros(ConfigurationMacros),
828         IncludePath(IncludePath), APINotesFile(APINotesFile) {}
829   MDNodeKeyImpl(const DIModule *N)
830       : Scope(N->getRawScope()), Name(N->getRawName()),
831         ConfigurationMacros(N->getRawConfigurationMacros()),
832         IncludePath(N->getRawIncludePath()),
833         APINotesFile(N->getRawAPINotesFile()) {}
834 
835   bool isKeyOf(const DIModule *RHS) const {
836     return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
837            ConfigurationMacros == RHS->getRawConfigurationMacros() &&
838            IncludePath == RHS->getRawIncludePath() &&
839            APINotesFile == RHS->getRawAPINotesFile();
840   }
841 
842   unsigned getHashValue() const {
843     return hash_combine(Scope, Name, ConfigurationMacros, IncludePath);
844   }
845 };
846 
847 template <> struct MDNodeKeyImpl<DITemplateTypeParameter> {
848   MDString *Name;
849   Metadata *Type;
850   bool IsDefault;
851 
852   MDNodeKeyImpl(MDString *Name, Metadata *Type, bool IsDefault)
853       : Name(Name), Type(Type), IsDefault(IsDefault) {}
854   MDNodeKeyImpl(const DITemplateTypeParameter *N)
855       : Name(N->getRawName()), Type(N->getRawType()),
856         IsDefault(N->isDefault()) {}
857 
858   bool isKeyOf(const DITemplateTypeParameter *RHS) const {
859     return Name == RHS->getRawName() && Type == RHS->getRawType() &&
860            IsDefault == RHS->isDefault();
861   }
862 
863   unsigned getHashValue() const { return hash_combine(Name, Type, IsDefault); }
864 };
865 
866 template <> struct MDNodeKeyImpl<DITemplateValueParameter> {
867   unsigned Tag;
868   MDString *Name;
869   Metadata *Type;
870   bool IsDefault;
871   Metadata *Value;
872 
873   MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *Type, bool IsDefault,
874                 Metadata *Value)
875       : Tag(Tag), Name(Name), Type(Type), IsDefault(IsDefault), Value(Value) {}
876   MDNodeKeyImpl(const DITemplateValueParameter *N)
877       : Tag(N->getTag()), Name(N->getRawName()), Type(N->getRawType()),
878         IsDefault(N->isDefault()), Value(N->getValue()) {}
879 
880   bool isKeyOf(const DITemplateValueParameter *RHS) const {
881     return Tag == RHS->getTag() && Name == RHS->getRawName() &&
882            Type == RHS->getRawType() && IsDefault == RHS->isDefault() &&
883            Value == RHS->getValue();
884   }
885 
886   unsigned getHashValue() const {
887     return hash_combine(Tag, Name, Type, IsDefault, Value);
888   }
889 };
890 
891 template <> struct MDNodeKeyImpl<DIGlobalVariable> {
892   Metadata *Scope;
893   MDString *Name;
894   MDString *LinkageName;
895   Metadata *File;
896   unsigned Line;
897   Metadata *Type;
898   bool IsLocalToUnit;
899   bool IsDefinition;
900   Metadata *StaticDataMemberDeclaration;
901   Metadata *TemplateParams;
902   uint32_t AlignInBits;
903 
904   MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *LinkageName,
905                 Metadata *File, unsigned Line, Metadata *Type,
906                 bool IsLocalToUnit, bool IsDefinition,
907                 Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
908                 uint32_t AlignInBits)
909       : Scope(Scope), Name(Name), LinkageName(LinkageName), File(File),
910         Line(Line), Type(Type), IsLocalToUnit(IsLocalToUnit),
911         IsDefinition(IsDefinition),
912         StaticDataMemberDeclaration(StaticDataMemberDeclaration),
913         TemplateParams(TemplateParams), AlignInBits(AlignInBits) {}
914   MDNodeKeyImpl(const DIGlobalVariable *N)
915       : Scope(N->getRawScope()), Name(N->getRawName()),
916         LinkageName(N->getRawLinkageName()), File(N->getRawFile()),
917         Line(N->getLine()), Type(N->getRawType()),
918         IsLocalToUnit(N->isLocalToUnit()), IsDefinition(N->isDefinition()),
919         StaticDataMemberDeclaration(N->getRawStaticDataMemberDeclaration()),
920         TemplateParams(N->getRawTemplateParams()),
921         AlignInBits(N->getAlignInBits()) {}
922 
923   bool isKeyOf(const DIGlobalVariable *RHS) const {
924     return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
925            LinkageName == RHS->getRawLinkageName() &&
926            File == RHS->getRawFile() && Line == RHS->getLine() &&
927            Type == RHS->getRawType() && IsLocalToUnit == RHS->isLocalToUnit() &&
928            IsDefinition == RHS->isDefinition() &&
929            StaticDataMemberDeclaration ==
930                RHS->getRawStaticDataMemberDeclaration() &&
931            TemplateParams == RHS->getRawTemplateParams() &&
932            AlignInBits == RHS->getAlignInBits();
933   }
934 
935   unsigned getHashValue() const {
936     // We do not use AlignInBits in hashing function here on purpose:
937     // in most cases this param for local variable is zero (for function param
938     // it is always zero). This leads to lots of hash collisions and errors on
939     // cases with lots of similar variables.
940     // clang/test/CodeGen/debug-info-257-args.c is an example of this problem,
941     // generated IR is random for each run and test fails with Align included.
942     // TODO: make hashing work fine with such situations
943     return hash_combine(Scope, Name, LinkageName, File, Line, Type,
944                         IsLocalToUnit, IsDefinition, /* AlignInBits, */
945                         StaticDataMemberDeclaration);
946   }
947 };
948 
949 template <> struct MDNodeKeyImpl<DILocalVariable> {
950   Metadata *Scope;
951   MDString *Name;
952   Metadata *File;
953   unsigned Line;
954   Metadata *Type;
955   unsigned Arg;
956   unsigned Flags;
957   uint32_t AlignInBits;
958 
959   MDNodeKeyImpl(Metadata *Scope, MDString *Name, Metadata *File, unsigned Line,
960                 Metadata *Type, unsigned Arg, unsigned Flags,
961                 uint32_t AlignInBits)
962       : Scope(Scope), Name(Name), File(File), Line(Line), Type(Type), Arg(Arg),
963         Flags(Flags), AlignInBits(AlignInBits) {}
964   MDNodeKeyImpl(const DILocalVariable *N)
965       : Scope(N->getRawScope()), Name(N->getRawName()), File(N->getRawFile()),
966         Line(N->getLine()), Type(N->getRawType()), Arg(N->getArg()),
967         Flags(N->getFlags()), AlignInBits(N->getAlignInBits()) {}
968 
969   bool isKeyOf(const DILocalVariable *RHS) const {
970     return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
971            File == RHS->getRawFile() && Line == RHS->getLine() &&
972            Type == RHS->getRawType() && Arg == RHS->getArg() &&
973            Flags == RHS->getFlags() && AlignInBits == RHS->getAlignInBits();
974   }
975 
976   unsigned getHashValue() const {
977     // We do not use AlignInBits in hashing function here on purpose:
978     // in most cases this param for local variable is zero (for function param
979     // it is always zero). This leads to lots of hash collisions and errors on
980     // cases with lots of similar variables.
981     // clang/test/CodeGen/debug-info-257-args.c is an example of this problem,
982     // generated IR is random for each run and test fails with Align included.
983     // TODO: make hashing work fine with such situations
984     return hash_combine(Scope, Name, File, Line, Type, Arg, Flags);
985   }
986 };
987 
988 template <> struct MDNodeKeyImpl<DILabel> {
989   Metadata *Scope;
990   MDString *Name;
991   Metadata *File;
992   unsigned Line;
993 
994   MDNodeKeyImpl(Metadata *Scope, MDString *Name, Metadata *File, unsigned Line)
995       : Scope(Scope), Name(Name), File(File), Line(Line) {}
996   MDNodeKeyImpl(const DILabel *N)
997       : Scope(N->getRawScope()), Name(N->getRawName()), File(N->getRawFile()),
998         Line(N->getLine()) {}
999 
1000   bool isKeyOf(const DILabel *RHS) const {
1001     return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1002            File == RHS->getRawFile() && Line == RHS->getLine();
1003   }
1004 
1005   /// Using name and line to get hash value. It should already be mostly unique.
1006   unsigned getHashValue() const {
1007     return hash_combine(Scope, Name, Line);
1008   }
1009 };
1010 
1011 template <> struct MDNodeKeyImpl<DIExpression> {
1012   ArrayRef<uint64_t> Elements;
1013 
1014   MDNodeKeyImpl(ArrayRef<uint64_t> Elements) : Elements(Elements) {}
1015   MDNodeKeyImpl(const DIExpression *N) : Elements(N->getElements()) {}
1016 
1017   bool isKeyOf(const DIExpression *RHS) const {
1018     return Elements == RHS->getElements();
1019   }
1020 
1021   unsigned getHashValue() const {
1022     return hash_combine_range(Elements.begin(), Elements.end());
1023   }
1024 };
1025 
1026 template <> struct MDNodeKeyImpl<DIGlobalVariableExpression> {
1027   Metadata *Variable;
1028   Metadata *Expression;
1029 
1030   MDNodeKeyImpl(Metadata *Variable, Metadata *Expression)
1031       : Variable(Variable), Expression(Expression) {}
1032   MDNodeKeyImpl(const DIGlobalVariableExpression *N)
1033       : Variable(N->getRawVariable()), Expression(N->getRawExpression()) {}
1034 
1035   bool isKeyOf(const DIGlobalVariableExpression *RHS) const {
1036     return Variable == RHS->getRawVariable() &&
1037            Expression == RHS->getRawExpression();
1038   }
1039 
1040   unsigned getHashValue() const { return hash_combine(Variable, Expression); }
1041 };
1042 
1043 template <> struct MDNodeKeyImpl<DIObjCProperty> {
1044   MDString *Name;
1045   Metadata *File;
1046   unsigned Line;
1047   MDString *GetterName;
1048   MDString *SetterName;
1049   unsigned Attributes;
1050   Metadata *Type;
1051 
1052   MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line,
1053                 MDString *GetterName, MDString *SetterName, unsigned Attributes,
1054                 Metadata *Type)
1055       : Name(Name), File(File), Line(Line), GetterName(GetterName),
1056         SetterName(SetterName), Attributes(Attributes), Type(Type) {}
1057   MDNodeKeyImpl(const DIObjCProperty *N)
1058       : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
1059         GetterName(N->getRawGetterName()), SetterName(N->getRawSetterName()),
1060         Attributes(N->getAttributes()), Type(N->getRawType()) {}
1061 
1062   bool isKeyOf(const DIObjCProperty *RHS) const {
1063     return Name == RHS->getRawName() && File == RHS->getRawFile() &&
1064            Line == RHS->getLine() && GetterName == RHS->getRawGetterName() &&
1065            SetterName == RHS->getRawSetterName() &&
1066            Attributes == RHS->getAttributes() && Type == RHS->getRawType();
1067   }
1068 
1069   unsigned getHashValue() const {
1070     return hash_combine(Name, File, Line, GetterName, SetterName, Attributes,
1071                         Type);
1072   }
1073 };
1074 
1075 template <> struct MDNodeKeyImpl<DIImportedEntity> {
1076   unsigned Tag;
1077   Metadata *Scope;
1078   Metadata *Entity;
1079   Metadata *File;
1080   unsigned Line;
1081   MDString *Name;
1082 
1083   MDNodeKeyImpl(unsigned Tag, Metadata *Scope, Metadata *Entity, Metadata *File,
1084                 unsigned Line, MDString *Name)
1085       : Tag(Tag), Scope(Scope), Entity(Entity), File(File), Line(Line),
1086         Name(Name) {}
1087   MDNodeKeyImpl(const DIImportedEntity *N)
1088       : Tag(N->getTag()), Scope(N->getRawScope()), Entity(N->getRawEntity()),
1089         File(N->getRawFile()), Line(N->getLine()), Name(N->getRawName()) {}
1090 
1091   bool isKeyOf(const DIImportedEntity *RHS) const {
1092     return Tag == RHS->getTag() && Scope == RHS->getRawScope() &&
1093            Entity == RHS->getRawEntity() && File == RHS->getFile() &&
1094            Line == RHS->getLine() && Name == RHS->getRawName();
1095   }
1096 
1097   unsigned getHashValue() const {
1098     return hash_combine(Tag, Scope, Entity, File, Line, Name);
1099   }
1100 };
1101 
1102 template <> struct MDNodeKeyImpl<DIMacro> {
1103   unsigned MIType;
1104   unsigned Line;
1105   MDString *Name;
1106   MDString *Value;
1107 
1108   MDNodeKeyImpl(unsigned MIType, unsigned Line, MDString *Name, MDString *Value)
1109       : MIType(MIType), Line(Line), Name(Name), Value(Value) {}
1110   MDNodeKeyImpl(const DIMacro *N)
1111       : MIType(N->getMacinfoType()), Line(N->getLine()), Name(N->getRawName()),
1112         Value(N->getRawValue()) {}
1113 
1114   bool isKeyOf(const DIMacro *RHS) const {
1115     return MIType == RHS->getMacinfoType() && Line == RHS->getLine() &&
1116            Name == RHS->getRawName() && Value == RHS->getRawValue();
1117   }
1118 
1119   unsigned getHashValue() const {
1120     return hash_combine(MIType, Line, Name, Value);
1121   }
1122 };
1123 
1124 template <> struct MDNodeKeyImpl<DIMacroFile> {
1125   unsigned MIType;
1126   unsigned Line;
1127   Metadata *File;
1128   Metadata *Elements;
1129 
1130   MDNodeKeyImpl(unsigned MIType, unsigned Line, Metadata *File,
1131                 Metadata *Elements)
1132       : MIType(MIType), Line(Line), File(File), Elements(Elements) {}
1133   MDNodeKeyImpl(const DIMacroFile *N)
1134       : MIType(N->getMacinfoType()), Line(N->getLine()), File(N->getRawFile()),
1135         Elements(N->getRawElements()) {}
1136 
1137   bool isKeyOf(const DIMacroFile *RHS) const {
1138     return MIType == RHS->getMacinfoType() && Line == RHS->getLine() &&
1139            File == RHS->getRawFile() && Elements == RHS->getRawElements();
1140   }
1141 
1142   unsigned getHashValue() const {
1143     return hash_combine(MIType, Line, File, Elements);
1144   }
1145 };
1146 
1147 /// DenseMapInfo for MDNode subclasses.
1148 template <class NodeTy> struct MDNodeInfo {
1149   using KeyTy = MDNodeKeyImpl<NodeTy>;
1150   using SubsetEqualTy = MDNodeSubsetEqualImpl<NodeTy>;
1151 
1152   static inline NodeTy *getEmptyKey() {
1153     return DenseMapInfo<NodeTy *>::getEmptyKey();
1154   }
1155 
1156   static inline NodeTy *getTombstoneKey() {
1157     return DenseMapInfo<NodeTy *>::getTombstoneKey();
1158   }
1159 
1160   static unsigned getHashValue(const KeyTy &Key) { return Key.getHashValue(); }
1161 
1162   static unsigned getHashValue(const NodeTy *N) {
1163     return KeyTy(N).getHashValue();
1164   }
1165 
1166   static bool isEqual(const KeyTy &LHS, const NodeTy *RHS) {
1167     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1168       return false;
1169     return SubsetEqualTy::isSubsetEqual(LHS, RHS) || LHS.isKeyOf(RHS);
1170   }
1171 
1172   static bool isEqual(const NodeTy *LHS, const NodeTy *RHS) {
1173     if (LHS == RHS)
1174       return true;
1175     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1176       return false;
1177     return SubsetEqualTy::isSubsetEqual(LHS, RHS);
1178   }
1179 };
1180 
1181 #define HANDLE_MDNODE_LEAF(CLASS) using CLASS##Info = MDNodeInfo<CLASS>;
1182 #include "llvm/IR/Metadata.def"
1183 
1184 /// Map-like storage for metadata attachments.
1185 class MDAttachmentMap {
1186   SmallVector<std::pair<unsigned, TrackingMDNodeRef>, 2> Attachments;
1187 
1188 public:
1189   bool empty() const { return Attachments.empty(); }
1190   size_t size() const { return Attachments.size(); }
1191 
1192   /// Get a particular attachment (if any).
1193   MDNode *lookup(unsigned ID) const;
1194 
1195   /// Set an attachment to a particular node.
1196   ///
1197   /// Set the \c ID attachment to \c MD, replacing the current attachment at \c
1198   /// ID (if anyway).
1199   void set(unsigned ID, MDNode &MD);
1200 
1201   /// Remove an attachment.
1202   ///
1203   /// Remove the attachment at \c ID, if any.
1204   bool erase(unsigned ID);
1205 
1206   /// Copy out all the attachments.
1207   ///
1208   /// Copies all the current attachments into \c Result, sorting by attachment
1209   /// ID.  This function does \em not clear \c Result.
1210   void getAll(SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const;
1211 
1212   /// Erase matching attachments.
1213   ///
1214   /// Erases all attachments matching the \c shouldRemove predicate.
1215   template <class PredTy> void remove_if(PredTy shouldRemove) {
1216     Attachments.erase(llvm::remove_if(Attachments, shouldRemove),
1217                       Attachments.end());
1218   }
1219 };
1220 
1221 /// Multimap-like storage for metadata attachments for globals. This differs
1222 /// from MDAttachmentMap in that it allows multiple attachments per metadata
1223 /// kind.
1224 class MDGlobalAttachmentMap {
1225   struct Attachment {
1226     unsigned MDKind;
1227     TrackingMDNodeRef Node;
1228   };
1229   SmallVector<Attachment, 1> Attachments;
1230 
1231 public:
1232   bool empty() const { return Attachments.empty(); }
1233 
1234   /// Appends all attachments with the given ID to \c Result in insertion order.
1235   /// If the global has no attachments with the given ID, or if ID is invalid,
1236   /// leaves Result unchanged.
1237   void get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const;
1238 
1239   /// Returns the first attachment with the given ID or nullptr if no such
1240   /// attachment exists.
1241   MDNode *lookup(unsigned ID) const;
1242 
1243   void insert(unsigned ID, MDNode &MD);
1244   bool erase(unsigned ID);
1245 
1246   /// Appends all attachments for the global to \c Result, sorting by attachment
1247   /// ID. Attachments with the same ID appear in insertion order. This function
1248   /// does \em not clear \c Result.
1249   void getAll(SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const;
1250 };
1251 
1252 class LLVMContextImpl {
1253 public:
1254   /// OwnedModules - The set of modules instantiated in this context, and which
1255   /// will be automatically deleted if this context is deleted.
1256   SmallPtrSet<Module*, 4> OwnedModules;
1257 
1258   LLVMContext::InlineAsmDiagHandlerTy InlineAsmDiagHandler = nullptr;
1259   void *InlineAsmDiagContext = nullptr;
1260 
1261   /// The main remark streamer used by all the other streamers (e.g. IR, MIR,
1262   /// frontends, etc.). This should only be used by the specific streamers, and
1263   /// never directly.
1264   std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer;
1265 
1266   std::unique_ptr<DiagnosticHandler> DiagHandler;
1267   bool RespectDiagnosticFilters = false;
1268   bool DiagnosticsHotnessRequested = false;
1269   uint64_t DiagnosticsHotnessThreshold = 0;
1270   /// The specialized remark streamer used by LLVM's OptimizationRemarkEmitter.
1271   std::unique_ptr<LLVMRemarkStreamer> LLVMRS;
1272 
1273   LLVMContext::YieldCallbackTy YieldCallback = nullptr;
1274   void *YieldOpaqueHandle = nullptr;
1275 
1276   using IntMapTy =
1277       DenseMap<APInt, std::unique_ptr<ConstantInt>, DenseMapAPIntKeyInfo>;
1278   IntMapTy IntConstants;
1279 
1280   using FPMapTy =
1281       DenseMap<APFloat, std::unique_ptr<ConstantFP>, DenseMapAPFloatKeyInfo>;
1282   FPMapTy FPConstants;
1283 
1284   FoldingSet<AttributeImpl> AttrsSet;
1285   FoldingSet<AttributeListImpl> AttrsLists;
1286   FoldingSet<AttributeSetNode> AttrsSetNodes;
1287 
1288   StringMap<MDString, BumpPtrAllocator> MDStringCache;
1289   DenseMap<Value *, ValueAsMetadata *> ValuesAsMetadata;
1290   DenseMap<Metadata *, MetadataAsValue *> MetadataAsValues;
1291 
1292   DenseMap<const Value*, ValueName*> ValueNames;
1293 
1294 #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
1295   DenseSet<CLASS *, CLASS##Info> CLASS##s;
1296 #include "llvm/IR/Metadata.def"
1297 
1298   // Optional map for looking up composite types by identifier.
1299   Optional<DenseMap<const MDString *, DICompositeType *>> DITypeMap;
1300 
1301   // MDNodes may be uniqued or not uniqued.  When they're not uniqued, they
1302   // aren't in the MDNodeSet, but they're still shared between objects, so no
1303   // one object can destroy them.  Keep track of them here so we can delete
1304   // them on context teardown.
1305   std::vector<MDNode *> DistinctMDNodes;
1306 
1307   DenseMap<Type *, std::unique_ptr<ConstantAggregateZero>> CAZConstants;
1308 
1309   using ArrayConstantsTy = ConstantUniqueMap<ConstantArray>;
1310   ArrayConstantsTy ArrayConstants;
1311 
1312   using StructConstantsTy = ConstantUniqueMap<ConstantStruct>;
1313   StructConstantsTy StructConstants;
1314 
1315   using VectorConstantsTy = ConstantUniqueMap<ConstantVector>;
1316   VectorConstantsTy VectorConstants;
1317 
1318   DenseMap<PointerType *, std::unique_ptr<ConstantPointerNull>> CPNConstants;
1319 
1320   DenseMap<Type *, std::unique_ptr<UndefValue>> UVConstants;
1321 
1322   StringMap<ConstantDataSequential*> CDSConstants;
1323 
1324   DenseMap<std::pair<const Function *, const BasicBlock *>, BlockAddress *>
1325     BlockAddresses;
1326   ConstantUniqueMap<ConstantExpr> ExprConstants;
1327 
1328   ConstantUniqueMap<InlineAsm> InlineAsms;
1329 
1330   ConstantInt *TheTrueVal = nullptr;
1331   ConstantInt *TheFalseVal = nullptr;
1332 
1333   std::unique_ptr<ConstantTokenNone> TheNoneToken;
1334 
1335   // Basic type instances.
1336   Type VoidTy, LabelTy, HalfTy, FloatTy, DoubleTy, MetadataTy, TokenTy;
1337   Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_MMXTy;
1338   IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty, Int128Ty;
1339 
1340   BumpPtrAllocator Alloc;
1341   UniqueStringSaver Saver{Alloc};
1342 
1343   DenseMap<unsigned, IntegerType*> IntegerTypes;
1344 
1345   using FunctionTypeSet = DenseSet<FunctionType *, FunctionTypeKeyInfo>;
1346   FunctionTypeSet FunctionTypes;
1347   using StructTypeSet = DenseSet<StructType *, AnonStructTypeKeyInfo>;
1348   StructTypeSet AnonStructTypes;
1349   StringMap<StructType*> NamedStructTypes;
1350   unsigned NamedStructTypesUniqueID = 0;
1351 
1352   DenseMap<std::pair<Type *, uint64_t>, ArrayType*> ArrayTypes;
1353   DenseMap<std::pair<Type *, ElementCount>, VectorType*> VectorTypes;
1354   DenseMap<Type*, PointerType*> PointerTypes;  // Pointers in AddrSpace = 0
1355   DenseMap<std::pair<Type*, unsigned>, PointerType*> ASPointerTypes;
1356 
1357   /// ValueHandles - This map keeps track of all of the value handles that are
1358   /// watching a Value*.  The Value::HasValueHandle bit is used to know
1359   /// whether or not a value has an entry in this map.
1360   using ValueHandlesTy = DenseMap<Value *, ValueHandleBase *>;
1361   ValueHandlesTy ValueHandles;
1362 
1363   /// CustomMDKindNames - Map to hold the metadata string to ID mapping.
1364   StringMap<unsigned> CustomMDKindNames;
1365 
1366   /// Collection of per-instruction metadata used in this context.
1367   DenseMap<const Instruction *, MDAttachmentMap> InstructionMetadata;
1368 
1369   /// Collection of per-GlobalObject metadata used in this context.
1370   DenseMap<const GlobalObject *, MDGlobalAttachmentMap> GlobalObjectMetadata;
1371 
1372   /// Collection of per-GlobalObject sections used in this context.
1373   DenseMap<const GlobalObject *, StringRef> GlobalObjectSections;
1374 
1375   /// Collection of per-GlobalValue partitions used in this context.
1376   DenseMap<const GlobalValue *, StringRef> GlobalValuePartitions;
1377 
1378   /// DiscriminatorTable - This table maps file:line locations to an
1379   /// integer representing the next DWARF path discriminator to assign to
1380   /// instructions in different blocks at the same location.
1381   DenseMap<std::pair<const char *, unsigned>, unsigned> DiscriminatorTable;
1382 
1383   /// A set of interned tags for operand bundles.  The StringMap maps
1384   /// bundle tags to their IDs.
1385   ///
1386   /// \see LLVMContext::getOperandBundleTagID
1387   StringMap<uint32_t> BundleTagCache;
1388 
1389   StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef Tag);
1390   void getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const;
1391   uint32_t getOperandBundleTagID(StringRef Tag) const;
1392 
1393   /// A set of interned synchronization scopes.  The StringMap maps
1394   /// synchronization scope names to their respective synchronization scope IDs.
1395   StringMap<SyncScope::ID> SSC;
1396 
1397   /// getOrInsertSyncScopeID - Maps synchronization scope name to
1398   /// synchronization scope ID.  Every synchronization scope registered with
1399   /// LLVMContext has unique ID except pre-defined ones.
1400   SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
1401 
1402   /// getSyncScopeNames - Populates client supplied SmallVector with
1403   /// synchronization scope names registered with LLVMContext.  Synchronization
1404   /// scope names are ordered by increasing synchronization scope IDs.
1405   void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
1406 
1407   /// Maintain the GC name for each function.
1408   ///
1409   /// This saves allocating an additional word in Function for programs which
1410   /// do not use GC (i.e., most programs) at the cost of increased overhead for
1411   /// clients which do use GC.
1412   DenseMap<const Function*, std::string> GCNames;
1413 
1414   /// Flag to indicate if Value (other than GlobalValue) retains their name or
1415   /// not.
1416   bool DiscardValueNames = false;
1417 
1418   LLVMContextImpl(LLVMContext &C);
1419   ~LLVMContextImpl();
1420 
1421   /// Destroy the ConstantArrays if they are not used.
1422   void dropTriviallyDeadConstantArrays();
1423 
1424   mutable OptPassGate *OPG = nullptr;
1425 
1426   /// Access the object which can disable optional passes and individual
1427   /// optimizations at compile time.
1428   OptPassGate &getOptPassGate() const;
1429 
1430   /// Set the object which can disable optional passes and individual
1431   /// optimizations at compile time.
1432   ///
1433   /// The lifetime of the object must be guaranteed to extend as long as the
1434   /// LLVMContext is used by compilation.
1435   void setOptPassGate(OptPassGate&);
1436 };
1437 
1438 } // end namespace llvm
1439 
1440 #endif // LLVM_LIB_IR_LLVMCONTEXTIMPL_H
1441