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