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/STLExtras.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/BinaryFormat/Dwarf.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DebugInfoMetadata.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/TrackingMDRef.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Support/Allocator.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/LibraryOptionsContext.h"
44#include "llvm/Support/StringSaver.h"
45#include "llvm/Support/VirtualFileSystem.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdint>
50#include <memory>
51#include <optional>
52#include <string>
53#include <utility>
54#include <vector>
55
56namespace llvm {
57
58class BasicBlock;
59struct DiagnosticHandler;
60class DbgMarker;
61class ElementCount;
62class Function;
63class GlobalObject;
64class GlobalValue;
65class InlineAsm;
66class LLVMRemarkStreamer;
67class OptPassGate;
68namespace remarks {
69class RemarkStreamer;
70}
71template <typename T> class StringMapEntry;
72class StringRef;
73class TypedPointerType;
74class ValueHandleBase;
75
76template <> struct DenseMapInfo<APFloat> {
77 static unsigned getHashValue(const APFloat &Key) {
78 return static_cast<unsigned>(hash_value(Arg: Key));
79 }
80
81 static bool isEqual(const APFloat &LHS, const APFloat &RHS) {
82 return LHS.bitwiseIsEqual(RHS);
83 }
84};
85
86struct AnonStructTypeKeyInfo {
87 struct KeyTy {
88 ArrayRef<Type *> ETypes;
89 bool isPacked;
90
91 KeyTy(const ArrayRef<Type *> &E, bool P) : ETypes(E), isPacked(P) {}
92
93 KeyTy(const StructType *ST)
94 : ETypes(ST->elements()), isPacked(ST->isPacked()) {}
95
96 bool operator==(const KeyTy &that) const {
97 if (isPacked != that.isPacked)
98 return false;
99 if (ETypes != that.ETypes)
100 return false;
101 return true;
102 }
103 bool operator!=(const KeyTy &that) const { return !this->operator==(that); }
104 };
105
106 static unsigned getHashValue(const KeyTy &Key) {
107 return hash_combine(args: hash_combine_range(R: Key.ETypes), args: Key.isPacked);
108 }
109
110 static unsigned getHashValue(const StructType *ST) {
111 return getHashValue(Key: KeyTy(ST));
112 }
113
114 static bool isEqual(const KeyTy &LHS, const StructType *RHS) {
115 return LHS == KeyTy(RHS);
116 }
117
118 static bool isEqual(const StructType *LHS, const StructType *RHS) {
119 return LHS == RHS;
120 }
121};
122
123struct FunctionTypeKeyInfo {
124 struct KeyTy {
125 const Type *ReturnType;
126 ArrayRef<Type *> Params;
127 bool isVarArg;
128
129 KeyTy(const Type *R, const ArrayRef<Type *> &P, bool V)
130 : ReturnType(R), Params(P), isVarArg(V) {}
131 KeyTy(const FunctionType *FT)
132 : ReturnType(FT->getReturnType()), Params(FT->params()),
133 isVarArg(FT->isVarArg()) {}
134
135 bool operator==(const KeyTy &that) const {
136 if (ReturnType != that.ReturnType)
137 return false;
138 if (isVarArg != that.isVarArg)
139 return false;
140 if (Params != that.Params)
141 return false;
142 return true;
143 }
144 bool operator!=(const KeyTy &that) const { return !this->operator==(that); }
145 };
146
147 static unsigned getHashValue(const KeyTy &Key) {
148 return hash_combine(args: Key.ReturnType, args: hash_combine_range(R: Key.Params),
149 args: Key.isVarArg);
150 }
151
152 static unsigned getHashValue(const FunctionType *FT) {
153 return getHashValue(Key: KeyTy(FT));
154 }
155
156 static bool isEqual(const KeyTy &LHS, const FunctionType *RHS) {
157 return LHS == KeyTy(RHS);
158 }
159
160 static bool isEqual(const FunctionType *LHS, const FunctionType *RHS) {
161 return LHS == RHS;
162 }
163};
164
165struct TargetExtTypeKeyInfo {
166 struct KeyTy {
167 StringRef Name;
168 ArrayRef<Type *> TypeParams;
169 ArrayRef<unsigned> IntParams;
170
171 KeyTy(StringRef N, const ArrayRef<Type *> &TP, const ArrayRef<unsigned> &IP)
172 : Name(N), TypeParams(TP), IntParams(IP) {}
173 KeyTy(const TargetExtType *TT)
174 : Name(TT->getName()), TypeParams(TT->type_params()),
175 IntParams(TT->int_params()) {}
176
177 bool operator==(const KeyTy &that) const {
178 return Name == that.Name && TypeParams == that.TypeParams &&
179 IntParams == that.IntParams;
180 }
181 bool operator!=(const KeyTy &that) const { return !this->operator==(that); }
182 };
183
184 static unsigned getHashValue(const KeyTy &Key) {
185 return hash_combine(args: Key.Name, args: hash_combine_range(R: Key.TypeParams),
186 args: hash_combine_range(R: Key.IntParams));
187 }
188
189 static unsigned getHashValue(const TargetExtType *FT) {
190 return getHashValue(Key: KeyTy(FT));
191 }
192
193 static bool isEqual(const KeyTy &LHS, const TargetExtType *RHS) {
194 return LHS == KeyTy(RHS);
195 }
196
197 static bool isEqual(const TargetExtType *LHS, const TargetExtType *RHS) {
198 return LHS == RHS;
199 }
200};
201
202/// Structure for hashing arbitrary MDNode operands.
203class MDNodeOpsKey {
204 ArrayRef<Metadata *> RawOps;
205 ArrayRef<MDOperand> Ops;
206 unsigned Hash;
207
208protected:
209 MDNodeOpsKey(ArrayRef<Metadata *> Ops)
210 : RawOps(Ops), Hash(calculateHash(Ops)) {}
211
212 template <class NodeTy>
213 MDNodeOpsKey(const NodeTy *N, unsigned Offset = 0)
214 : Ops(N->op_begin() + Offset, N->op_end()), Hash(N->getHash()) {}
215
216 template <class NodeTy>
217 bool compareOps(const NodeTy *RHS, unsigned Offset = 0) const {
218 if (getHash() != RHS->getHash())
219 return false;
220
221 assert((RawOps.empty() || Ops.empty()) && "Two sets of operands?");
222 return RawOps.empty() ? compareOps(Ops, RHS, Offset)
223 : compareOps(RawOps, RHS, Offset);
224 }
225
226 static unsigned calculateHash(MDNode *N, unsigned Offset = 0);
227
228private:
229 template <class T>
230 static bool compareOps(ArrayRef<T> Ops, const MDNode *RHS, unsigned Offset) {
231 if (Ops.size() != RHS->getNumOperands() - Offset)
232 return false;
233 return std::equal(Ops.begin(), Ops.end(), RHS->op_begin() + Offset);
234 }
235
236 static unsigned calculateHash(ArrayRef<Metadata *> Ops);
237
238public:
239 unsigned getHash() const { return Hash; }
240};
241
242template <class NodeTy> struct MDNodeKeyImpl;
243
244/// Configuration point for MDNodeInfo::isEqual().
245template <class NodeTy> struct MDNodeSubsetEqualImpl {
246 using KeyTy = MDNodeKeyImpl<NodeTy>;
247
248 static bool isSubsetEqual(const KeyTy &LHS, const NodeTy *RHS) {
249 return false;
250 }
251
252 static bool isSubsetEqual(const NodeTy *LHS, const NodeTy *RHS) {
253 return false;
254 }
255};
256
257/// DenseMapInfo for MDTuple.
258///
259/// Note that we don't need the is-function-local bit, since that's implicit in
260/// the operands.
261template <> struct MDNodeKeyImpl<MDTuple> : MDNodeOpsKey {
262 MDNodeKeyImpl(ArrayRef<Metadata *> Ops) : MDNodeOpsKey(Ops) {}
263 MDNodeKeyImpl(const MDTuple *N) : MDNodeOpsKey(N) {}
264
265 bool isKeyOf(const MDTuple *RHS) const { return compareOps(RHS); }
266
267 unsigned getHashValue() const { return getHash(); }
268
269 static unsigned calculateHash(MDTuple *N) {
270 return MDNodeOpsKey::calculateHash(N);
271 }
272};
273
274/// DenseMapInfo for DILocation.
275template <> struct MDNodeKeyImpl<DILocation> {
276 Metadata *Scope;
277 Metadata *InlinedAt;
278 Metadata *IRLayers;
279 uint64_t AtomGroup : 60;
280 uint64_t AtomRank : 3;
281 unsigned Line;
282 uint16_t Column;
283 bool ImplicitCode;
284
285 MDNodeKeyImpl(unsigned Line, uint16_t Column, Metadata *Scope,
286 Metadata *InlinedAt, bool ImplicitCode, uint64_t AtomGroup,
287 uint8_t AtomRank, Metadata *IRLayers)
288 : Scope(Scope), InlinedAt(InlinedAt), IRLayers(IRLayers),
289 AtomGroup(AtomGroup), AtomRank(AtomRank), Line(Line), Column(Column),
290 ImplicitCode(ImplicitCode) {}
291
292 MDNodeKeyImpl(const DILocation *L)
293 : Scope(L->getRawScope()), InlinedAt(L->getRawInlinedAt()),
294 IRLayers(L->getRawIRLayers()), AtomGroup(L->getAtomGroup()),
295 AtomRank(L->getAtomRank()), Line(L->getLine()), Column(L->getColumn()),
296 ImplicitCode(L->isImplicitCode()) {}
297
298 bool isKeyOf(const DILocation *RHS) const {
299 return Line == RHS->getLine() && Column == RHS->getColumn() &&
300 Scope == RHS->getRawScope() && InlinedAt == RHS->getRawInlinedAt() &&
301 ImplicitCode == RHS->isImplicitCode() &&
302 AtomGroup == RHS->getAtomGroup() && AtomRank == RHS->getAtomRank() &&
303 IRLayers == RHS->getRawIRLayers();
304 }
305
306 unsigned getHashValue() const {
307 uint64_t LineColumnAndImplicitCode =
308 Line | (uint64_t(Column) << 32) | (uint64_t(ImplicitCode) << 48);
309 // Hashing AtomGroup and AtomRank substantially impacts performance whether
310 // Key Instructions is enabled or not. We can't detect whether it's enabled
311 // here cheaply; avoiding hashing zero values is a good approximation. This
312 // affects Key Instruction builds too, but any potential costs incurred by
313 // messing with the hash distribution* appear to still be massively
314 // outweighed by the overall compile time savings by performing this check.
315 // * (hash_combine(x) != hash_combine(x, 0))
316 // irlayers is likewise rare, so it is only mixed in when present to keep
317 // the common no-layers hashes unchanged.
318 if (AtomGroup || AtomRank) {
319 if (IRLayers)
320 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt,
321 args: AtomGroup | (uint64_t(AtomRank) << 61), args: IRLayers);
322 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt,
323 args: AtomGroup | (uint64_t(AtomRank) << 61));
324 }
325 if (IRLayers)
326 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt,
327 args: IRLayers);
328 return hash_combine(args: LineColumnAndImplicitCode, args: Scope, args: InlinedAt);
329 }
330};
331
332/// DenseMapInfo for DILayerLoc.
333template <> struct MDNodeKeyImpl<DILayerLoc> {
334 Metadata *Kind;
335 Metadata *File;
336 unsigned Line;
337 uint16_t Column;
338
339 MDNodeKeyImpl(Metadata *Kind, Metadata *File, unsigned Line, uint16_t Column)
340 : Kind(Kind), File(File), Line(Line), Column(Column) {}
341 MDNodeKeyImpl(const DILayerLoc *N)
342 : Kind(N->getRawKind()), File(N->getRawFile()), Line(N->getLine()),
343 Column(N->getColumn()) {}
344
345 bool isKeyOf(const DILayerLoc *RHS) const {
346 return Kind == RHS->getRawKind() && File == RHS->getRawFile() &&
347 Line == RHS->getLine() && Column == RHS->getColumn();
348 }
349
350 unsigned getHashValue() const {
351 return hash_combine(args: Kind, args: File, args: Line, args: Column);
352 }
353};
354
355/// DenseMapInfo for DILayerLocList.
356template <> struct MDNodeKeyImpl<DILayerLocList> : MDNodeOpsKey {
357 MDNodeKeyImpl(ArrayRef<Metadata *> Ops) : MDNodeOpsKey(Ops) {}
358 MDNodeKeyImpl(const DILayerLocList *N) : MDNodeOpsKey(N) {}
359
360 bool isKeyOf(const DILayerLocList *RHS) const { return compareOps(RHS); }
361
362 unsigned getHashValue() const { return getHash(); }
363
364 static unsigned calculateHash(DILayerLocList *N) {
365 return MDNodeOpsKey::calculateHash(N);
366 }
367};
368
369/// DenseMapInfo for GenericDINode.
370template <> struct MDNodeKeyImpl<GenericDINode> : MDNodeOpsKey {
371 unsigned Tag;
372 MDString *Header;
373
374 MDNodeKeyImpl(unsigned Tag, MDString *Header, ArrayRef<Metadata *> DwarfOps)
375 : MDNodeOpsKey(DwarfOps), Tag(Tag), Header(Header) {}
376 MDNodeKeyImpl(const GenericDINode *N)
377 : MDNodeOpsKey(N, 1), Tag(N->getTag()), Header(N->getRawHeader()) {}
378
379 bool isKeyOf(const GenericDINode *RHS) const {
380 return Tag == RHS->getTag() && Header == RHS->getRawHeader() &&
381 compareOps(RHS, Offset: 1);
382 }
383
384 unsigned getHashValue() const { return hash_combine(args: getHash(), args: Tag, args: Header); }
385
386 static unsigned calculateHash(GenericDINode *N) {
387 return MDNodeOpsKey::calculateHash(N, Offset: 1);
388 }
389};
390
391template <> struct MDNodeKeyImpl<DISubrange> {
392 Metadata *CountNode;
393 Metadata *LowerBound;
394 Metadata *UpperBound;
395 Metadata *Stride;
396
397 MDNodeKeyImpl(Metadata *CountNode, Metadata *LowerBound, Metadata *UpperBound,
398 Metadata *Stride)
399 : CountNode(CountNode), LowerBound(LowerBound), UpperBound(UpperBound),
400 Stride(Stride) {}
401 MDNodeKeyImpl(const DISubrange *N)
402 : CountNode(N->getRawCountNode()), LowerBound(N->getRawLowerBound()),
403 UpperBound(N->getRawUpperBound()), Stride(N->getRawStride()) {}
404
405 bool isKeyOf(const DISubrange *RHS) const {
406 auto BoundsEqual = [=](Metadata *Node1, Metadata *Node2) -> bool {
407 if (Node1 == Node2)
408 return true;
409
410 ConstantAsMetadata *MD1 = dyn_cast_or_null<ConstantAsMetadata>(Val: Node1);
411 ConstantAsMetadata *MD2 = dyn_cast_or_null<ConstantAsMetadata>(Val: Node2);
412 if (MD1 && MD2) {
413 ConstantInt *CV1 = cast<ConstantInt>(Val: MD1->getValue());
414 ConstantInt *CV2 = cast<ConstantInt>(Val: MD2->getValue());
415 if (CV1->getSExtValue() == CV2->getSExtValue())
416 return true;
417 }
418 return false;
419 };
420
421 return BoundsEqual(CountNode, RHS->getRawCountNode()) &&
422 BoundsEqual(LowerBound, RHS->getRawLowerBound()) &&
423 BoundsEqual(UpperBound, RHS->getRawUpperBound()) &&
424 BoundsEqual(Stride, RHS->getRawStride());
425 }
426
427 unsigned getHashValue() const {
428 if (CountNode)
429 if (auto *MD = dyn_cast<ConstantAsMetadata>(Val: CountNode))
430 return hash_combine(args: cast<ConstantInt>(Val: MD->getValue())->getSExtValue(),
431 args: LowerBound, args: UpperBound, args: Stride);
432 return hash_combine(args: CountNode, args: LowerBound, args: UpperBound, args: Stride);
433 }
434};
435
436template <> struct MDNodeKeyImpl<DIGenericSubrange> {
437 Metadata *CountNode;
438 Metadata *LowerBound;
439 Metadata *UpperBound;
440 Metadata *Stride;
441
442 MDNodeKeyImpl(Metadata *CountNode, Metadata *LowerBound, Metadata *UpperBound,
443 Metadata *Stride)
444 : CountNode(CountNode), LowerBound(LowerBound), UpperBound(UpperBound),
445 Stride(Stride) {}
446 MDNodeKeyImpl(const DIGenericSubrange *N)
447 : CountNode(N->getRawCountNode()), LowerBound(N->getRawLowerBound()),
448 UpperBound(N->getRawUpperBound()), Stride(N->getRawStride()) {}
449
450 bool isKeyOf(const DIGenericSubrange *RHS) const {
451 return (CountNode == RHS->getRawCountNode()) &&
452 (LowerBound == RHS->getRawLowerBound()) &&
453 (UpperBound == RHS->getRawUpperBound()) &&
454 (Stride == RHS->getRawStride());
455 }
456
457 unsigned getHashValue() const {
458 auto *MD = dyn_cast_or_null<ConstantAsMetadata>(Val: CountNode);
459 if (CountNode && MD)
460 return hash_combine(args: cast<ConstantInt>(Val: MD->getValue())->getSExtValue(),
461 args: LowerBound, args: UpperBound, args: Stride);
462 return hash_combine(args: CountNode, args: LowerBound, args: UpperBound, args: Stride);
463 }
464};
465
466template <> struct MDNodeKeyImpl<DIEnumerator> {
467 APInt Value;
468 MDString *Name;
469 bool IsUnsigned;
470
471 MDNodeKeyImpl(APInt Value, bool IsUnsigned, MDString *Name)
472 : Value(std::move(Value)), Name(Name), IsUnsigned(IsUnsigned) {}
473 MDNodeKeyImpl(int64_t Value, bool IsUnsigned, MDString *Name)
474 : Value(APInt(64, Value, !IsUnsigned)), Name(Name),
475 IsUnsigned(IsUnsigned) {}
476 MDNodeKeyImpl(const DIEnumerator *N)
477 : Value(N->getValue()), Name(N->getRawName()),
478 IsUnsigned(N->isUnsigned()) {}
479
480 bool isKeyOf(const DIEnumerator *RHS) const {
481 return Value.getBitWidth() == RHS->getValue().getBitWidth() &&
482 Value == RHS->getValue() && IsUnsigned == RHS->isUnsigned() &&
483 Name == RHS->getRawName();
484 }
485
486 unsigned getHashValue() const { return hash_combine(args: Value, args: Name); }
487};
488
489template <> struct MDNodeKeyImpl<DIBasicType> {
490 unsigned Tag;
491 MDString *Name;
492 Metadata *File;
493 unsigned LineNo;
494 Metadata *Scope;
495 Metadata *SizeInBits;
496 uint32_t AlignInBits;
497 unsigned Encoding;
498 uint32_t NumExtraInhabitants;
499 uint32_t DataSizeInBits;
500 unsigned Flags;
501
502 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned LineNo,
503 Metadata *Scope, Metadata *SizeInBits, uint32_t AlignInBits,
504 unsigned Encoding, uint32_t NumExtraInhabitants,
505 uint32_t DataSizeInBits, unsigned Flags)
506 : Tag(Tag), Name(Name), File(File), LineNo(LineNo), Scope(Scope),
507 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Encoding(Encoding),
508 NumExtraInhabitants(NumExtraInhabitants),
509 DataSizeInBits(DataSizeInBits), Flags(Flags) {}
510 MDNodeKeyImpl(const DIBasicType *N)
511 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
512 LineNo(N->getLine()), Scope(N->getRawScope()),
513 SizeInBits(N->getRawSizeInBits()), AlignInBits(N->getAlignInBits()),
514 Encoding(N->getEncoding()),
515 NumExtraInhabitants(N->getNumExtraInhabitants()),
516 DataSizeInBits(N->getDataSizeInBits()), Flags(N->getFlags()) {}
517
518 bool isKeyOf(const DIBasicType *RHS) const {
519 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
520 File == RHS->getRawFile() && LineNo == RHS->getLine() &&
521 Scope == RHS->getRawScope() &&
522 SizeInBits == RHS->getRawSizeInBits() &&
523 AlignInBits == RHS->getAlignInBits() &&
524 Encoding == RHS->getEncoding() &&
525 NumExtraInhabitants == RHS->getNumExtraInhabitants() &&
526 DataSizeInBits == RHS->getDataSizeInBits() &&
527 Flags == RHS->getFlags();
528 }
529
530 unsigned getHashValue() const {
531 return hash_combine(args: Tag, args: Name, args: File, args: LineNo, args: Scope, args: SizeInBits, args: AlignInBits,
532 args: Encoding);
533 }
534};
535
536template <> struct MDNodeKeyImpl<DIFixedPointType> {
537 unsigned Tag;
538 MDString *Name;
539 Metadata *File;
540 unsigned LineNo;
541 Metadata *Scope;
542 Metadata *SizeInBits;
543 uint32_t AlignInBits;
544 unsigned Encoding;
545 unsigned Flags;
546 unsigned Kind;
547 int Factor;
548 APInt Numerator;
549 APInt Denominator;
550
551 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned LineNo,
552 Metadata *Scope, Metadata *SizeInBits, uint32_t AlignInBits,
553 unsigned Encoding, unsigned Flags, unsigned Kind, int Factor,
554 APInt Numerator, APInt Denominator)
555 : Tag(Tag), Name(Name), File(File), LineNo(LineNo), Scope(Scope),
556 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Encoding(Encoding),
557 Flags(Flags), Kind(Kind), Factor(Factor), Numerator(Numerator),
558 Denominator(Denominator) {}
559 MDNodeKeyImpl(const DIFixedPointType *N)
560 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
561 LineNo(N->getLine()), Scope(N->getRawScope()),
562 SizeInBits(N->getRawSizeInBits()), AlignInBits(N->getAlignInBits()),
563 Encoding(N->getEncoding()), Flags(N->getFlags()), Kind(N->getKind()),
564 Factor(N->getFactorRaw()), Numerator(N->getNumeratorRaw()),
565 Denominator(N->getDenominatorRaw()) {}
566
567 bool isKeyOf(const DIFixedPointType *RHS) const {
568 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
569 LineNo == RHS->getLine() && Scope == RHS->getRawScope() &&
570 SizeInBits == RHS->getRawSizeInBits() &&
571 AlignInBits == RHS->getAlignInBits() && Kind == RHS->getKind() &&
572 (RHS->isRational() ? (Numerator == RHS->getNumerator() &&
573 Denominator == RHS->getDenominator())
574 : Factor == RHS->getFactor());
575 }
576
577 unsigned getHashValue() const {
578 return hash_combine(args: Name, args: File, args: LineNo, args: Scope, args: Flags, args: Kind, args: Factor,
579 args: Numerator, args: Denominator);
580 }
581};
582
583template <> struct MDNodeKeyImpl<DIStringType> {
584 unsigned Tag;
585 MDString *Name;
586 Metadata *StringLength;
587 Metadata *StringLengthExp;
588 Metadata *StringLocationExp;
589 Metadata *SizeInBits;
590 uint32_t AlignInBits;
591 unsigned Encoding;
592 Metadata *CharType;
593
594 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *StringLength,
595 Metadata *StringLengthExp, Metadata *StringLocationExp,
596 Metadata *SizeInBits, uint32_t AlignInBits, unsigned Encoding,
597 Metadata *CharType)
598 : Tag(Tag), Name(Name), StringLength(StringLength),
599 StringLengthExp(StringLengthExp), StringLocationExp(StringLocationExp),
600 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Encoding(Encoding),
601 CharType(CharType) {}
602 MDNodeKeyImpl(const DIStringType *N)
603 : Tag(N->getTag()), Name(N->getRawName()),
604 StringLength(N->getRawStringLength()),
605 StringLengthExp(N->getRawStringLengthExp()),
606 StringLocationExp(N->getRawStringLocationExp()),
607 SizeInBits(N->getRawSizeInBits()), AlignInBits(N->getAlignInBits()),
608 Encoding(N->getEncoding()), CharType(N->getRawCharType()) {}
609
610 bool isKeyOf(const DIStringType *RHS) const {
611 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
612 StringLength == RHS->getRawStringLength() &&
613 StringLengthExp == RHS->getRawStringLengthExp() &&
614 StringLocationExp == RHS->getRawStringLocationExp() &&
615 SizeInBits == RHS->getRawSizeInBits() &&
616 AlignInBits == RHS->getAlignInBits() &&
617 Encoding == RHS->getEncoding() && CharType == RHS->getRawCharType();
618 }
619 unsigned getHashValue() const {
620 // Intentionally computes the hash on a subset of the operands for
621 // performance reason. The subset has to be significant enough to avoid
622 // collision "most of the time". There is no correctness issue in case of
623 // collision because of the full check above.
624 return hash_combine(args: Tag, args: Name, args: StringLength, args: Encoding, args: CharType);
625 }
626};
627
628template <> struct MDNodeKeyImpl<DIDerivedType> {
629 unsigned Tag;
630 MDString *Name;
631 Metadata *File;
632 unsigned Line;
633 Metadata *Scope;
634 Metadata *BaseType;
635 Metadata *SizeInBits;
636 Metadata *OffsetInBits;
637 uint32_t AlignInBits;
638 std::optional<unsigned> DWARFAddressSpace;
639 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
640 unsigned Flags;
641 Metadata *ExtraData;
642 Metadata *Annotations;
643
644 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
645 Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits,
646 uint32_t AlignInBits, Metadata *OffsetInBits,
647 std::optional<unsigned> DWARFAddressSpace,
648 std::optional<DIDerivedType::PtrAuthData> PtrAuthData,
649 unsigned Flags, Metadata *ExtraData, Metadata *Annotations)
650 : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
651 BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
652 AlignInBits(AlignInBits), DWARFAddressSpace(DWARFAddressSpace),
653 PtrAuthData(PtrAuthData), Flags(Flags), ExtraData(ExtraData),
654 Annotations(Annotations) {}
655 MDNodeKeyImpl(const DIDerivedType *N)
656 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
657 Line(N->getLine()), Scope(N->getRawScope()),
658 BaseType(N->getRawBaseType()), SizeInBits(N->getRawSizeInBits()),
659 OffsetInBits(N->getRawOffsetInBits()), AlignInBits(N->getAlignInBits()),
660 DWARFAddressSpace(N->getDWARFAddressSpace()),
661 PtrAuthData(N->getPtrAuthData()), Flags(N->getFlags()),
662 ExtraData(N->getRawExtraData()), Annotations(N->getRawAnnotations()) {}
663
664 bool isKeyOf(const DIDerivedType *RHS) const {
665 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
666 File == RHS->getRawFile() && Line == RHS->getLine() &&
667 Scope == RHS->getRawScope() && BaseType == RHS->getRawBaseType() &&
668 SizeInBits == RHS->getRawSizeInBits() &&
669 AlignInBits == RHS->getAlignInBits() &&
670 OffsetInBits == RHS->getRawOffsetInBits() &&
671 DWARFAddressSpace == RHS->getDWARFAddressSpace() &&
672 PtrAuthData == RHS->getPtrAuthData() && Flags == RHS->getFlags() &&
673 ExtraData == RHS->getRawExtraData() &&
674 Annotations == RHS->getRawAnnotations();
675 }
676
677 unsigned getHashValue() const {
678 // If this is a member inside an ODR type, only hash the type and the name.
679 // Otherwise the hash will be stronger than
680 // MDNodeSubsetEqualImpl::isODRMember().
681 if (Tag == dwarf::DW_TAG_member && Name)
682 if (auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope))
683 if (CT->getRawIdentifier())
684 return hash_combine(args: Name, args: Scope);
685
686 // Intentionally computes the hash on a subset of the operands for
687 // performance reason. The subset has to be significant enough to avoid
688 // collision "most of the time". There is no correctness issue in case of
689 // collision because of the full check above.
690 return hash_combine(args: Tag, args: Name, args: File, args: Line, args: Scope, args: BaseType, args: Flags);
691 }
692};
693
694template <> struct MDNodeKeyImpl<DISubrangeType> {
695 MDString *Name;
696 Metadata *File;
697 unsigned Line;
698 Metadata *Scope;
699 Metadata *SizeInBits;
700 uint32_t AlignInBits;
701 unsigned Flags;
702 Metadata *BaseType;
703 Metadata *LowerBound;
704 Metadata *UpperBound;
705 Metadata *Stride;
706 Metadata *Bias;
707
708 MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
709 Metadata *SizeInBits, uint32_t AlignInBits, unsigned Flags,
710 Metadata *BaseType, Metadata *LowerBound, Metadata *UpperBound,
711 Metadata *Stride, Metadata *Bias)
712 : Name(Name), File(File), Line(Line), Scope(Scope),
713 SizeInBits(SizeInBits), AlignInBits(AlignInBits), Flags(Flags),
714 BaseType(BaseType), LowerBound(LowerBound), UpperBound(UpperBound),
715 Stride(Stride), Bias(Bias) {}
716 MDNodeKeyImpl(const DISubrangeType *N)
717 : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
718 Scope(N->getRawScope()), SizeInBits(N->getRawSizeInBits()),
719 AlignInBits(N->getAlignInBits()), Flags(N->getFlags()),
720 BaseType(N->getRawBaseType()), LowerBound(N->getRawLowerBound()),
721 UpperBound(N->getRawUpperBound()), Stride(N->getRawStride()),
722 Bias(N->getRawBias()) {}
723
724 bool isKeyOf(const DISubrangeType *RHS) const {
725 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
726 Line == RHS->getLine() && Scope == RHS->getRawScope() &&
727 SizeInBits == RHS->getRawSizeInBits() &&
728 AlignInBits == RHS->getAlignInBits() && Flags == RHS->getFlags() &&
729 BaseType == RHS->getRawBaseType() &&
730 LowerBound == RHS->getRawLowerBound() &&
731 UpperBound == RHS->getRawUpperBound() &&
732 Stride == RHS->getRawStride() && Bias == RHS->getRawBias();
733 }
734
735 unsigned getHashValue() const {
736 return hash_combine(args: Name, args: File, args: Line, args: Scope, args: BaseType, args: Flags, args: LowerBound,
737 args: UpperBound, args: Stride, args: Bias);
738 }
739};
740
741template <> struct MDNodeSubsetEqualImpl<DIDerivedType> {
742 using KeyTy = MDNodeKeyImpl<DIDerivedType>;
743
744 static bool isSubsetEqual(const KeyTy &LHS, const DIDerivedType *RHS) {
745 return isODRMember(Tag: LHS.Tag, Scope: LHS.Scope, Name: LHS.Name, RHS);
746 }
747
748 static bool isSubsetEqual(const DIDerivedType *LHS,
749 const DIDerivedType *RHS) {
750 return isODRMember(Tag: LHS->getTag(), Scope: LHS->getRawScope(), Name: LHS->getRawName(),
751 RHS);
752 }
753
754 /// Subprograms compare equal if they declare the same function in an ODR
755 /// type.
756 static bool isODRMember(unsigned Tag, const Metadata *Scope,
757 const MDString *Name, const DIDerivedType *RHS) {
758 // Check whether the LHS is eligible.
759 if (Tag != dwarf::DW_TAG_member || !Name)
760 return false;
761
762 auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope);
763 if (!CT || !CT->getRawIdentifier())
764 return false;
765
766 // Compare to the RHS.
767 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
768 Scope == RHS->getRawScope();
769 }
770};
771
772template <> struct MDNodeKeyImpl<DICompositeType> {
773 unsigned Tag;
774 MDString *Name;
775 Metadata *File;
776 unsigned Line;
777 Metadata *Scope;
778 Metadata *BaseType;
779 Metadata *SizeInBits;
780 Metadata *OffsetInBits;
781 uint32_t AlignInBits;
782 unsigned Flags;
783 Metadata *Elements;
784 unsigned RuntimeLang;
785 Metadata *VTableHolder;
786 Metadata *TemplateParams;
787 MDString *Identifier;
788 Metadata *Discriminator;
789 Metadata *DataLocation;
790 Metadata *Associated;
791 Metadata *Allocated;
792 Metadata *Rank;
793 Metadata *Annotations;
794 Metadata *Specification;
795 uint32_t NumExtraInhabitants;
796 Metadata *BitStride;
797
798 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
799 Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits,
800 uint32_t AlignInBits, Metadata *OffsetInBits, unsigned Flags,
801 Metadata *Elements, unsigned RuntimeLang,
802 Metadata *VTableHolder, Metadata *TemplateParams,
803 MDString *Identifier, Metadata *Discriminator,
804 Metadata *DataLocation, Metadata *Associated,
805 Metadata *Allocated, Metadata *Rank, Metadata *Annotations,
806 Metadata *Specification, uint32_t NumExtraInhabitants,
807 Metadata *BitStride)
808 : Tag(Tag), Name(Name), File(File), Line(Line), Scope(Scope),
809 BaseType(BaseType), SizeInBits(SizeInBits), OffsetInBits(OffsetInBits),
810 AlignInBits(AlignInBits), Flags(Flags), Elements(Elements),
811 RuntimeLang(RuntimeLang), VTableHolder(VTableHolder),
812 TemplateParams(TemplateParams), Identifier(Identifier),
813 Discriminator(Discriminator), DataLocation(DataLocation),
814 Associated(Associated), Allocated(Allocated), Rank(Rank),
815 Annotations(Annotations), Specification(Specification),
816 NumExtraInhabitants(NumExtraInhabitants), BitStride(BitStride) {}
817 MDNodeKeyImpl(const DICompositeType *N)
818 : Tag(N->getTag()), Name(N->getRawName()), File(N->getRawFile()),
819 Line(N->getLine()), Scope(N->getRawScope()),
820 BaseType(N->getRawBaseType()), SizeInBits(N->getRawSizeInBits()),
821 OffsetInBits(N->getRawOffsetInBits()), AlignInBits(N->getAlignInBits()),
822 Flags(N->getFlags()), Elements(N->getRawElements()),
823 RuntimeLang(N->getRuntimeLang()), VTableHolder(N->getRawVTableHolder()),
824 TemplateParams(N->getRawTemplateParams()),
825 Identifier(N->getRawIdentifier()),
826 Discriminator(N->getRawDiscriminator()),
827 DataLocation(N->getRawDataLocation()),
828 Associated(N->getRawAssociated()), Allocated(N->getRawAllocated()),
829 Rank(N->getRawRank()), Annotations(N->getRawAnnotations()),
830 Specification(N->getSpecification()),
831 NumExtraInhabitants(N->getNumExtraInhabitants()),
832 BitStride(N->getRawBitStride()) {}
833
834 bool isKeyOf(const DICompositeType *RHS) const {
835 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
836 File == RHS->getRawFile() && Line == RHS->getLine() &&
837 Scope == RHS->getRawScope() && BaseType == RHS->getRawBaseType() &&
838 SizeInBits == RHS->getRawSizeInBits() &&
839 AlignInBits == RHS->getAlignInBits() &&
840 OffsetInBits == RHS->getRawOffsetInBits() &&
841 Flags == RHS->getFlags() && Elements == RHS->getRawElements() &&
842 RuntimeLang == RHS->getRuntimeLang() &&
843 VTableHolder == RHS->getRawVTableHolder() &&
844 TemplateParams == RHS->getRawTemplateParams() &&
845 Identifier == RHS->getRawIdentifier() &&
846 Discriminator == RHS->getRawDiscriminator() &&
847 DataLocation == RHS->getRawDataLocation() &&
848 Associated == RHS->getRawAssociated() &&
849 Allocated == RHS->getRawAllocated() && Rank == RHS->getRawRank() &&
850 Annotations == RHS->getRawAnnotations() &&
851 Specification == RHS->getSpecification() &&
852 NumExtraInhabitants == RHS->getNumExtraInhabitants() &&
853 BitStride == RHS->getRawBitStride();
854 }
855
856 unsigned getHashValue() const {
857 // Intentionally computes the hash on a subset of the operands for
858 // performance reason. The subset has to be significant enough to avoid
859 // collision "most of the time". There is no correctness issue in case of
860 // collision because of the full check above.
861 return hash_combine(args: Name, args: File, args: Line, args: BaseType, args: Scope, args: Elements,
862 args: TemplateParams, args: Annotations);
863 }
864};
865
866template <> struct MDNodeKeyImpl<DISubroutineType> {
867 unsigned Flags;
868 uint8_t CC;
869 Metadata *TypeArray;
870
871 MDNodeKeyImpl(unsigned Flags, uint8_t CC, Metadata *TypeArray)
872 : Flags(Flags), CC(CC), TypeArray(TypeArray) {}
873 MDNodeKeyImpl(const DISubroutineType *N)
874 : Flags(N->getFlags()), CC(N->getCC()), TypeArray(N->getRawTypeArray()) {}
875
876 bool isKeyOf(const DISubroutineType *RHS) const {
877 return Flags == RHS->getFlags() && CC == RHS->getCC() &&
878 TypeArray == RHS->getRawTypeArray();
879 }
880
881 unsigned getHashValue() const { return hash_combine(args: Flags, args: CC, args: TypeArray); }
882};
883
884template <> struct MDNodeKeyImpl<DIFile> {
885 MDString *Filename;
886 MDString *Directory;
887 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
888 MDString *Source;
889
890 MDNodeKeyImpl(MDString *Filename, MDString *Directory,
891 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum,
892 MDString *Source)
893 : Filename(Filename), Directory(Directory), Checksum(Checksum),
894 Source(Source) {}
895 MDNodeKeyImpl(const DIFile *N)
896 : Filename(N->getRawFilename()), Directory(N->getRawDirectory()),
897 Checksum(N->getRawChecksum()), Source(N->getRawSource()) {}
898
899 bool isKeyOf(const DIFile *RHS) const {
900 return Filename == RHS->getRawFilename() &&
901 Directory == RHS->getRawDirectory() &&
902 Checksum == RHS->getRawChecksum() && Source == RHS->getRawSource();
903 }
904
905 unsigned getHashValue() const {
906 return hash_combine(args: Filename, args: Directory, args: Checksum ? Checksum->Kind : 0,
907 args: Checksum ? Checksum->Value : nullptr, args: Source);
908 }
909};
910
911template <> struct MDNodeKeyImpl<DISubprogram> {
912 Metadata *Scope;
913 MDString *Name;
914 MDString *LinkageName;
915 Metadata *File;
916 unsigned Line;
917 unsigned ScopeLine;
918 Metadata *Type;
919 Metadata *ContainingType;
920 unsigned VirtualIndex;
921 int ThisAdjustment;
922 unsigned Flags;
923 unsigned SPFlags;
924 Metadata *Unit;
925 Metadata *TemplateParams;
926 Metadata *Declaration;
927 Metadata *RetainedNodes;
928 Metadata *ThrownTypes;
929 Metadata *Annotations;
930 MDString *TargetFuncName;
931 bool UsesKeyInstructions;
932
933 MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *LinkageName,
934 Metadata *File, unsigned Line, Metadata *Type,
935 unsigned ScopeLine, Metadata *ContainingType,
936 unsigned VirtualIndex, int ThisAdjustment, unsigned Flags,
937 unsigned SPFlags, Metadata *Unit, Metadata *TemplateParams,
938 Metadata *Declaration, Metadata *RetainedNodes,
939 Metadata *ThrownTypes, Metadata *Annotations,
940 MDString *TargetFuncName, bool UsesKeyInstructions)
941 : Scope(Scope), Name(Name), LinkageName(LinkageName), File(File),
942 Line(Line), ScopeLine(ScopeLine), Type(Type),
943 ContainingType(ContainingType), VirtualIndex(VirtualIndex),
944 ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags),
945 Unit(Unit), TemplateParams(TemplateParams), Declaration(Declaration),
946 RetainedNodes(RetainedNodes), ThrownTypes(ThrownTypes),
947 Annotations(Annotations), TargetFuncName(TargetFuncName),
948 UsesKeyInstructions(UsesKeyInstructions) {}
949 MDNodeKeyImpl(const DISubprogram *N)
950 : Scope(N->getRawScope()), Name(N->getRawName()),
951 LinkageName(N->getRawLinkageName()), File(N->getRawFile()),
952 Line(N->getLine()), ScopeLine(N->getScopeLine()), Type(N->getRawType()),
953 ContainingType(N->getRawContainingType()),
954 VirtualIndex(N->getVirtualIndex()),
955 ThisAdjustment(N->getThisAdjustment()), Flags(N->getFlags()),
956 SPFlags(N->getSPFlags()), Unit(N->getRawUnit()),
957 TemplateParams(N->getRawTemplateParams()),
958 Declaration(N->getRawDeclaration()),
959 RetainedNodes(N->getRawRetainedNodes()),
960 ThrownTypes(N->getRawThrownTypes()),
961 Annotations(N->getRawAnnotations()),
962 TargetFuncName(N->getRawTargetFuncName()),
963 UsesKeyInstructions(N->getKeyInstructionsEnabled()) {}
964
965 bool isKeyOf(const DISubprogram *RHS) const {
966 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
967 LinkageName == RHS->getRawLinkageName() &&
968 File == RHS->getRawFile() && Line == RHS->getLine() &&
969 Type == RHS->getRawType() && ScopeLine == RHS->getScopeLine() &&
970 ContainingType == RHS->getRawContainingType() &&
971 VirtualIndex == RHS->getVirtualIndex() &&
972 ThisAdjustment == RHS->getThisAdjustment() &&
973 Flags == RHS->getFlags() && SPFlags == RHS->getSPFlags() &&
974 Unit == RHS->getUnit() &&
975 TemplateParams == RHS->getRawTemplateParams() &&
976 Declaration == RHS->getRawDeclaration() &&
977 RetainedNodes == RHS->getRawRetainedNodes() &&
978 ThrownTypes == RHS->getRawThrownTypes() &&
979 Annotations == RHS->getRawAnnotations() &&
980 TargetFuncName == RHS->getRawTargetFuncName() &&
981 UsesKeyInstructions == RHS->getKeyInstructionsEnabled();
982 }
983
984 bool isDefinition() const { return SPFlags & DISubprogram::SPFlagDefinition; }
985
986 unsigned getHashValue() const {
987 // Use the Scope's linkage name instead of using the scope directly, as the
988 // scope may be a temporary one which can replaced, which would produce a
989 // different hash for the same DISubprogram.
990 llvm::StringRef ScopeLinkageName;
991 if (auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope))
992 if (auto *ID = CT->getRawIdentifier())
993 ScopeLinkageName = ID->getString();
994
995 // If this is a declaration inside an ODR type, only hash the type and the
996 // name. Otherwise the hash will be stronger than
997 // MDNodeSubsetEqualImpl::isDeclarationOfODRMember().
998 if (!isDefinition() && LinkageName &&
999 isa_and_nonnull<DICompositeType>(Val: Scope))
1000 return hash_combine(args: LinkageName, args: ScopeLinkageName);
1001
1002 // Intentionally computes the hash on a subset of the operands for
1003 // performance reason. The subset has to be significant enough to avoid
1004 // collision "most of the time". There is no correctness issue in case of
1005 // collision because of the full check above.
1006 return hash_combine(args: Name, args: ScopeLinkageName, args: File, args: Type, args: Line);
1007 }
1008};
1009
1010template <> struct MDNodeSubsetEqualImpl<DISubprogram> {
1011 using KeyTy = MDNodeKeyImpl<DISubprogram>;
1012
1013 static bool isSubsetEqual(const KeyTy &LHS, const DISubprogram *RHS) {
1014 return isDeclarationOfODRMember(IsDefinition: LHS.isDefinition(), Scope: LHS.Scope,
1015 LinkageName: LHS.LinkageName, TemplateParams: LHS.TemplateParams, RHS);
1016 }
1017
1018 static bool isSubsetEqual(const DISubprogram *LHS, const DISubprogram *RHS) {
1019 return isDeclarationOfODRMember(IsDefinition: LHS->isDefinition(), Scope: LHS->getRawScope(),
1020 LinkageName: LHS->getRawLinkageName(),
1021 TemplateParams: LHS->getRawTemplateParams(), RHS);
1022 }
1023
1024 /// Subprograms compare equal if they declare the same function in an ODR
1025 /// type.
1026 static bool isDeclarationOfODRMember(bool IsDefinition, const Metadata *Scope,
1027 const MDString *LinkageName,
1028 const Metadata *TemplateParams,
1029 const DISubprogram *RHS) {
1030 // Check whether the LHS is eligible.
1031 if (IsDefinition || !Scope || !LinkageName)
1032 return false;
1033
1034 auto *CT = dyn_cast_or_null<DICompositeType>(Val: Scope);
1035 if (!CT || !CT->getRawIdentifier())
1036 return false;
1037
1038 // Compare to the RHS.
1039 // FIXME: We need to compare template parameters here to avoid incorrect
1040 // collisions in mapMetadata when RF_ReuseAndMutateDistinctMDs and a
1041 // ODR-DISubprogram has a non-ODR template parameter (i.e., a
1042 // DICompositeType that does not have an identifier). Eventually we should
1043 // decouple ODR logic from uniquing logic.
1044 return IsDefinition == RHS->isDefinition() && Scope == RHS->getRawScope() &&
1045 LinkageName == RHS->getRawLinkageName() &&
1046 TemplateParams == RHS->getRawTemplateParams();
1047 }
1048};
1049
1050template <> struct MDNodeKeyImpl<DILexicalBlock> {
1051 Metadata *Scope;
1052 Metadata *File;
1053 unsigned Line;
1054 unsigned Column;
1055
1056 MDNodeKeyImpl(Metadata *Scope, Metadata *File, unsigned Line, unsigned Column)
1057 : Scope(Scope), File(File), Line(Line), Column(Column) {}
1058 MDNodeKeyImpl(const DILexicalBlock *N)
1059 : Scope(N->getRawScope()), File(N->getRawFile()), Line(N->getLine()),
1060 Column(N->getColumn()) {}
1061
1062 bool isKeyOf(const DILexicalBlock *RHS) const {
1063 return Scope == RHS->getRawScope() && File == RHS->getRawFile() &&
1064 Line == RHS->getLine() && Column == RHS->getColumn();
1065 }
1066
1067 unsigned getHashValue() const {
1068 return hash_combine(args: Scope, args: File, args: Line, args: Column);
1069 }
1070};
1071
1072template <> struct MDNodeKeyImpl<DILexicalBlockFile> {
1073 Metadata *Scope;
1074 Metadata *File;
1075 unsigned Discriminator;
1076
1077 MDNodeKeyImpl(Metadata *Scope, Metadata *File, unsigned Discriminator)
1078 : Scope(Scope), File(File), Discriminator(Discriminator) {}
1079 MDNodeKeyImpl(const DILexicalBlockFile *N)
1080 : Scope(N->getRawScope()), File(N->getRawFile()),
1081 Discriminator(N->getDiscriminator()) {}
1082
1083 bool isKeyOf(const DILexicalBlockFile *RHS) const {
1084 return Scope == RHS->getRawScope() && File == RHS->getRawFile() &&
1085 Discriminator == RHS->getDiscriminator();
1086 }
1087
1088 unsigned getHashValue() const {
1089 return hash_combine(args: Scope, args: File, args: Discriminator);
1090 }
1091};
1092
1093template <> struct MDNodeKeyImpl<DINamespace> {
1094 Metadata *Scope;
1095 MDString *Name;
1096 bool ExportSymbols;
1097
1098 MDNodeKeyImpl(Metadata *Scope, MDString *Name, bool ExportSymbols)
1099 : Scope(Scope), Name(Name), ExportSymbols(ExportSymbols) {}
1100 MDNodeKeyImpl(const DINamespace *N)
1101 : Scope(N->getRawScope()), Name(N->getRawName()),
1102 ExportSymbols(N->getExportSymbols()) {}
1103
1104 bool isKeyOf(const DINamespace *RHS) const {
1105 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1106 ExportSymbols == RHS->getExportSymbols();
1107 }
1108
1109 unsigned getHashValue() const { return hash_combine(args: Scope, args: Name); }
1110};
1111
1112template <> struct MDNodeKeyImpl<DICommonBlock> {
1113 Metadata *Scope;
1114 Metadata *Decl;
1115 MDString *Name;
1116 Metadata *File;
1117 unsigned LineNo;
1118
1119 MDNodeKeyImpl(Metadata *Scope, Metadata *Decl, MDString *Name, Metadata *File,
1120 unsigned LineNo)
1121 : Scope(Scope), Decl(Decl), Name(Name), File(File), LineNo(LineNo) {}
1122 MDNodeKeyImpl(const DICommonBlock *N)
1123 : Scope(N->getRawScope()), Decl(N->getRawDecl()), Name(N->getRawName()),
1124 File(N->getRawFile()), LineNo(N->getLineNo()) {}
1125
1126 bool isKeyOf(const DICommonBlock *RHS) const {
1127 return Scope == RHS->getRawScope() && Decl == RHS->getRawDecl() &&
1128 Name == RHS->getRawName() && File == RHS->getRawFile() &&
1129 LineNo == RHS->getLineNo();
1130 }
1131
1132 unsigned getHashValue() const {
1133 return hash_combine(args: Scope, args: Decl, args: Name, args: File, args: LineNo);
1134 }
1135};
1136
1137template <> struct MDNodeKeyImpl<DIModule> {
1138 Metadata *File;
1139 Metadata *Scope;
1140 MDString *Name;
1141 MDString *ConfigurationMacros;
1142 MDString *IncludePath;
1143 MDString *APINotesFile;
1144 unsigned LineNo;
1145 bool IsDecl;
1146
1147 MDNodeKeyImpl(Metadata *File, Metadata *Scope, MDString *Name,
1148 MDString *ConfigurationMacros, MDString *IncludePath,
1149 MDString *APINotesFile, unsigned LineNo, bool IsDecl)
1150 : File(File), Scope(Scope), Name(Name),
1151 ConfigurationMacros(ConfigurationMacros), IncludePath(IncludePath),
1152 APINotesFile(APINotesFile), LineNo(LineNo), IsDecl(IsDecl) {}
1153 MDNodeKeyImpl(const DIModule *N)
1154 : File(N->getRawFile()), Scope(N->getRawScope()), Name(N->getRawName()),
1155 ConfigurationMacros(N->getRawConfigurationMacros()),
1156 IncludePath(N->getRawIncludePath()),
1157 APINotesFile(N->getRawAPINotesFile()), LineNo(N->getLineNo()),
1158 IsDecl(N->getIsDecl()) {}
1159
1160 bool isKeyOf(const DIModule *RHS) const {
1161 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1162 ConfigurationMacros == RHS->getRawConfigurationMacros() &&
1163 IncludePath == RHS->getRawIncludePath() &&
1164 APINotesFile == RHS->getRawAPINotesFile() &&
1165 File == RHS->getRawFile() && LineNo == RHS->getLineNo() &&
1166 IsDecl == RHS->getIsDecl();
1167 }
1168
1169 unsigned getHashValue() const {
1170 return hash_combine(args: Scope, args: Name, args: ConfigurationMacros, args: IncludePath);
1171 }
1172};
1173
1174template <> struct MDNodeKeyImpl<DITemplateTypeParameter> {
1175 MDString *Name;
1176 Metadata *Type;
1177 bool IsDefault;
1178
1179 MDNodeKeyImpl(MDString *Name, Metadata *Type, bool IsDefault)
1180 : Name(Name), Type(Type), IsDefault(IsDefault) {}
1181 MDNodeKeyImpl(const DITemplateTypeParameter *N)
1182 : Name(N->getRawName()), Type(N->getRawType()),
1183 IsDefault(N->isDefault()) {}
1184
1185 bool isKeyOf(const DITemplateTypeParameter *RHS) const {
1186 return Name == RHS->getRawName() && Type == RHS->getRawType() &&
1187 IsDefault == RHS->isDefault();
1188 }
1189
1190 unsigned getHashValue() const { return hash_combine(args: Name, args: Type, args: IsDefault); }
1191};
1192
1193template <> struct MDNodeKeyImpl<DITemplateValueParameter> {
1194 unsigned Tag;
1195 MDString *Name;
1196 Metadata *Type;
1197 bool IsDefault;
1198 Metadata *Value;
1199
1200 MDNodeKeyImpl(unsigned Tag, MDString *Name, Metadata *Type, bool IsDefault,
1201 Metadata *Value)
1202 : Tag(Tag), Name(Name), Type(Type), IsDefault(IsDefault), Value(Value) {}
1203 MDNodeKeyImpl(const DITemplateValueParameter *N)
1204 : Tag(N->getTag()), Name(N->getRawName()), Type(N->getRawType()),
1205 IsDefault(N->isDefault()), Value(N->getValue()) {}
1206
1207 bool isKeyOf(const DITemplateValueParameter *RHS) const {
1208 return Tag == RHS->getTag() && Name == RHS->getRawName() &&
1209 Type == RHS->getRawType() && IsDefault == RHS->isDefault() &&
1210 Value == RHS->getValue();
1211 }
1212
1213 unsigned getHashValue() const {
1214 return hash_combine(args: Tag, args: Name, args: Type, args: IsDefault, args: Value);
1215 }
1216};
1217
1218template <> struct MDNodeKeyImpl<DIGlobalVariable> {
1219 Metadata *Scope;
1220 MDString *Name;
1221 MDString *LinkageName;
1222 Metadata *File;
1223 unsigned Line;
1224 Metadata *Type;
1225 bool IsLocalToUnit;
1226 bool IsDefinition;
1227 Metadata *StaticDataMemberDeclaration;
1228 Metadata *TemplateParams;
1229 uint32_t AlignInBits;
1230 Metadata *Annotations;
1231
1232 MDNodeKeyImpl(Metadata *Scope, MDString *Name, MDString *LinkageName,
1233 Metadata *File, unsigned Line, Metadata *Type,
1234 bool IsLocalToUnit, bool IsDefinition,
1235 Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
1236 uint32_t AlignInBits, Metadata *Annotations)
1237 : Scope(Scope), Name(Name), LinkageName(LinkageName), File(File),
1238 Line(Line), Type(Type), IsLocalToUnit(IsLocalToUnit),
1239 IsDefinition(IsDefinition),
1240 StaticDataMemberDeclaration(StaticDataMemberDeclaration),
1241 TemplateParams(TemplateParams), AlignInBits(AlignInBits),
1242 Annotations(Annotations) {}
1243 MDNodeKeyImpl(const DIGlobalVariable *N)
1244 : Scope(N->getRawScope()), Name(N->getRawName()),
1245 LinkageName(N->getRawLinkageName()), File(N->getRawFile()),
1246 Line(N->getLine()), Type(N->getRawType()),
1247 IsLocalToUnit(N->isLocalToUnit()), IsDefinition(N->isDefinition()),
1248 StaticDataMemberDeclaration(N->getRawStaticDataMemberDeclaration()),
1249 TemplateParams(N->getRawTemplateParams()),
1250 AlignInBits(N->getAlignInBits()), Annotations(N->getRawAnnotations()) {}
1251
1252 bool isKeyOf(const DIGlobalVariable *RHS) const {
1253 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1254 LinkageName == RHS->getRawLinkageName() &&
1255 File == RHS->getRawFile() && Line == RHS->getLine() &&
1256 Type == RHS->getRawType() && IsLocalToUnit == RHS->isLocalToUnit() &&
1257 IsDefinition == RHS->isDefinition() &&
1258 StaticDataMemberDeclaration ==
1259 RHS->getRawStaticDataMemberDeclaration() &&
1260 TemplateParams == RHS->getRawTemplateParams() &&
1261 AlignInBits == RHS->getAlignInBits() &&
1262 Annotations == RHS->getRawAnnotations();
1263 }
1264
1265 unsigned getHashValue() const {
1266 // We do not use AlignInBits in hashing function here on purpose:
1267 // in most cases this param for local variable is zero (for function param
1268 // it is always zero). This leads to lots of hash collisions and errors on
1269 // cases with lots of similar variables.
1270 // clang/test/CodeGen/debug-info-257-args.c is an example of this problem,
1271 // generated IR is random for each run and test fails with Align included.
1272 // TODO: make hashing work fine with such situations
1273 return hash_combine(args: Scope, args: Name, args: LinkageName, args: File, args: Line, args: Type,
1274 args: IsLocalToUnit, args: IsDefinition, /* AlignInBits, */
1275 args: StaticDataMemberDeclaration, args: Annotations);
1276 }
1277};
1278
1279template <> struct MDNodeKeyImpl<DILocalVariable> {
1280 Metadata *Scope;
1281 MDString *Name;
1282 Metadata *File;
1283 unsigned Line;
1284 Metadata *Type;
1285 unsigned Arg;
1286 unsigned Flags;
1287 uint32_t AlignInBits;
1288 Metadata *Annotations;
1289
1290 MDNodeKeyImpl(Metadata *Scope, MDString *Name, Metadata *File, unsigned Line,
1291 Metadata *Type, unsigned Arg, unsigned Flags,
1292 uint32_t AlignInBits, Metadata *Annotations)
1293 : Scope(Scope), Name(Name), File(File), Line(Line), Type(Type), Arg(Arg),
1294 Flags(Flags), AlignInBits(AlignInBits), Annotations(Annotations) {}
1295 MDNodeKeyImpl(const DILocalVariable *N)
1296 : Scope(N->getRawScope()), Name(N->getRawName()), File(N->getRawFile()),
1297 Line(N->getLine()), Type(N->getRawType()), Arg(N->getArg()),
1298 Flags(N->getFlags()), AlignInBits(N->getAlignInBits()),
1299 Annotations(N->getRawAnnotations()) {}
1300
1301 bool isKeyOf(const DILocalVariable *RHS) const {
1302 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1303 File == RHS->getRawFile() && Line == RHS->getLine() &&
1304 Type == RHS->getRawType() && Arg == RHS->getArg() &&
1305 Flags == RHS->getFlags() && AlignInBits == RHS->getAlignInBits() &&
1306 Annotations == RHS->getRawAnnotations();
1307 }
1308
1309 unsigned getHashValue() const {
1310 // We do not use AlignInBits in hashing function here on purpose:
1311 // in most cases this param for local variable is zero (for function param
1312 // it is always zero). This leads to lots of hash collisions and errors on
1313 // cases with lots of similar variables.
1314 // clang/test/CodeGen/debug-info-257-args.c is an example of this problem,
1315 // generated IR is random for each run and test fails with Align included.
1316 // TODO: make hashing work fine with such situations
1317 return hash_combine(args: Scope, args: Name, args: File, args: Line, args: Type, args: Arg, args: Flags, args: Annotations);
1318 }
1319};
1320
1321template <> struct MDNodeKeyImpl<DILabel> {
1322 Metadata *Scope;
1323 MDString *Name;
1324 Metadata *File;
1325 unsigned Line;
1326 unsigned Column;
1327 bool IsArtificial;
1328 std::optional<unsigned> CoroSuspendIdx;
1329
1330 MDNodeKeyImpl(Metadata *Scope, MDString *Name, Metadata *File, unsigned Line,
1331 unsigned Column, bool IsArtificial,
1332 std::optional<unsigned> CoroSuspendIdx)
1333 : Scope(Scope), Name(Name), File(File), Line(Line), Column(Column),
1334 IsArtificial(IsArtificial), CoroSuspendIdx(CoroSuspendIdx) {}
1335 MDNodeKeyImpl(const DILabel *N)
1336 : Scope(N->getRawScope()), Name(N->getRawName()), File(N->getRawFile()),
1337 Line(N->getLine()), Column(N->getColumn()),
1338 IsArtificial(N->isArtificial()),
1339 CoroSuspendIdx(N->getCoroSuspendIdx()) {}
1340
1341 bool isKeyOf(const DILabel *RHS) const {
1342 return Scope == RHS->getRawScope() && Name == RHS->getRawName() &&
1343 File == RHS->getRawFile() && Line == RHS->getLine() &&
1344 Column == RHS->getColumn() && IsArtificial == RHS->isArtificial() &&
1345 CoroSuspendIdx == RHS->getCoroSuspendIdx();
1346 }
1347
1348 /// Using name and line to get hash value. It should already be mostly unique.
1349 unsigned getHashValue() const {
1350 return hash_combine(args: Scope, args: Name, args: Line, args: Column, args: IsArtificial,
1351 args: CoroSuspendIdx);
1352 }
1353};
1354
1355template <> struct MDNodeKeyImpl<DIExpression> {
1356 ArrayRef<uint64_t> Elements;
1357
1358 MDNodeKeyImpl(ArrayRef<uint64_t> Elements) : Elements(Elements) {}
1359 MDNodeKeyImpl(const DIExpression *N) : Elements(N->getElements()) {}
1360
1361 bool isKeyOf(const DIExpression *RHS) const {
1362 return Elements == RHS->getElements();
1363 }
1364
1365 unsigned getHashValue() const { return hash_combine_range(R: Elements); }
1366};
1367
1368template <> struct MDNodeKeyImpl<DIGlobalVariableExpression> {
1369 Metadata *Variable;
1370 Metadata *Expression;
1371
1372 MDNodeKeyImpl(Metadata *Variable, Metadata *Expression)
1373 : Variable(Variable), Expression(Expression) {}
1374 MDNodeKeyImpl(const DIGlobalVariableExpression *N)
1375 : Variable(N->getRawVariable()), Expression(N->getRawExpression()) {}
1376
1377 bool isKeyOf(const DIGlobalVariableExpression *RHS) const {
1378 return Variable == RHS->getRawVariable() &&
1379 Expression == RHS->getRawExpression();
1380 }
1381
1382 unsigned getHashValue() const { return hash_combine(args: Variable, args: Expression); }
1383};
1384
1385template <> struct MDNodeKeyImpl<DIObjCProperty> {
1386 MDString *Name;
1387 Metadata *File;
1388 unsigned Line;
1389 MDString *GetterName;
1390 MDString *SetterName;
1391 unsigned Attributes;
1392 Metadata *Type;
1393
1394 MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line,
1395 MDString *GetterName, MDString *SetterName, unsigned Attributes,
1396 Metadata *Type)
1397 : Name(Name), File(File), Line(Line), GetterName(GetterName),
1398 SetterName(SetterName), Attributes(Attributes), Type(Type) {}
1399 MDNodeKeyImpl(const DIObjCProperty *N)
1400 : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
1401 GetterName(N->getRawGetterName()), SetterName(N->getRawSetterName()),
1402 Attributes(N->getAttributes()), Type(N->getRawType()) {}
1403
1404 bool isKeyOf(const DIObjCProperty *RHS) const {
1405 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
1406 Line == RHS->getLine() && GetterName == RHS->getRawGetterName() &&
1407 SetterName == RHS->getRawSetterName() &&
1408 Attributes == RHS->getAttributes() && Type == RHS->getRawType();
1409 }
1410
1411 unsigned getHashValue() const {
1412 return hash_combine(args: Name, args: File, args: Line, args: GetterName, args: SetterName, args: Attributes,
1413 args: Type);
1414 }
1415};
1416
1417template <> struct MDNodeKeyImpl<DIProperty> {
1418 MDString *Name;
1419 Metadata *File;
1420 unsigned Line;
1421 Metadata *Type;
1422 Metadata *BackingStorage;
1423
1424 MDNodeKeyImpl(MDString *Name, Metadata *File, unsigned Line, Metadata *Type,
1425 Metadata *BackingStorage)
1426 : Name(Name), File(File), Line(Line), Type(Type),
1427 BackingStorage(BackingStorage) {}
1428 MDNodeKeyImpl(const DIProperty *N)
1429 : Name(N->getRawName()), File(N->getRawFile()), Line(N->getLine()),
1430 Type(N->getRawType()), BackingStorage(N->getRawBackingStorage()) {}
1431
1432 bool isKeyOf(const DIProperty *RHS) const {
1433 return Name == RHS->getRawName() && File == RHS->getRawFile() &&
1434 Line == RHS->getLine() && Type == RHS->getRawType() &&
1435 BackingStorage == RHS->getRawBackingStorage();
1436 }
1437
1438 unsigned getHashValue() const {
1439 return hash_combine(args: Name, args: File, args: Line, args: Type, args: BackingStorage);
1440 }
1441};
1442
1443template <> struct MDNodeKeyImpl<DIImportedEntity> {
1444 unsigned Tag;
1445 Metadata *Scope;
1446 Metadata *Entity;
1447 Metadata *File;
1448 unsigned Line;
1449 MDString *Name;
1450 Metadata *Elements;
1451
1452 MDNodeKeyImpl(unsigned Tag, Metadata *Scope, Metadata *Entity, Metadata *File,
1453 unsigned Line, MDString *Name, Metadata *Elements)
1454 : Tag(Tag), Scope(Scope), Entity(Entity), File(File), Line(Line),
1455 Name(Name), Elements(Elements) {}
1456 MDNodeKeyImpl(const DIImportedEntity *N)
1457 : Tag(N->getTag()), Scope(N->getRawScope()), Entity(N->getRawEntity()),
1458 File(N->getRawFile()), Line(N->getLine()), Name(N->getRawName()),
1459 Elements(N->getRawElements()) {}
1460
1461 bool isKeyOf(const DIImportedEntity *RHS) const {
1462 return Tag == RHS->getTag() && Scope == RHS->getRawScope() &&
1463 Entity == RHS->getRawEntity() && File == RHS->getFile() &&
1464 Line == RHS->getLine() && Name == RHS->getRawName() &&
1465 Elements == RHS->getRawElements();
1466 }
1467
1468 unsigned getHashValue() const {
1469 return hash_combine(args: Tag, args: Scope, args: Entity, args: File, args: Line, args: Name, args: Elements);
1470 }
1471};
1472
1473template <> struct MDNodeKeyImpl<DIMacro> {
1474 unsigned MIType;
1475 unsigned Line;
1476 MDString *Name;
1477 MDString *Value;
1478
1479 MDNodeKeyImpl(unsigned MIType, unsigned Line, MDString *Name, MDString *Value)
1480 : MIType(MIType), Line(Line), Name(Name), Value(Value) {}
1481 MDNodeKeyImpl(const DIMacro *N)
1482 : MIType(N->getMacinfoType()), Line(N->getLine()), Name(N->getRawName()),
1483 Value(N->getRawValue()) {}
1484
1485 bool isKeyOf(const DIMacro *RHS) const {
1486 return MIType == RHS->getMacinfoType() && Line == RHS->getLine() &&
1487 Name == RHS->getRawName() && Value == RHS->getRawValue();
1488 }
1489
1490 unsigned getHashValue() const {
1491 return hash_combine(args: MIType, args: Line, args: Name, args: Value);
1492 }
1493};
1494
1495template <> struct MDNodeKeyImpl<DIMacroFile> {
1496 unsigned MIType;
1497 unsigned Line;
1498 Metadata *File;
1499 Metadata *Elements;
1500
1501 MDNodeKeyImpl(unsigned MIType, unsigned Line, Metadata *File,
1502 Metadata *Elements)
1503 : MIType(MIType), Line(Line), File(File), Elements(Elements) {}
1504 MDNodeKeyImpl(const DIMacroFile *N)
1505 : MIType(N->getMacinfoType()), Line(N->getLine()), File(N->getRawFile()),
1506 Elements(N->getRawElements()) {}
1507
1508 bool isKeyOf(const DIMacroFile *RHS) const {
1509 return MIType == RHS->getMacinfoType() && Line == RHS->getLine() &&
1510 File == RHS->getRawFile() && Elements == RHS->getRawElements();
1511 }
1512
1513 unsigned getHashValue() const {
1514 return hash_combine(args: MIType, args: Line, args: File, args: Elements);
1515 }
1516};
1517
1518// DIArgLists are not MDNodes, but we still want to unique them in a DenseSet
1519// based on a hash of their arguments.
1520struct DIArgListKeyInfo {
1521 ArrayRef<ValueAsMetadata *> Args;
1522
1523 DIArgListKeyInfo(ArrayRef<ValueAsMetadata *> Args) : Args(Args) {}
1524 DIArgListKeyInfo(const DIArgList *N) : Args(N->getArgs()) {}
1525
1526 bool isKeyOf(const DIArgList *RHS) const { return Args == RHS->getArgs(); }
1527
1528 unsigned getHashValue() const { return hash_combine_range(R: Args); }
1529};
1530
1531/// DenseMapInfo for DIArgList.
1532struct DIArgListInfo {
1533 using KeyTy = DIArgListKeyInfo;
1534
1535 static unsigned getHashValue(const KeyTy &Key) { return Key.getHashValue(); }
1536
1537 static unsigned getHashValue(const DIArgList *N) {
1538 return KeyTy(N).getHashValue();
1539 }
1540
1541 static bool isEqual(const KeyTy &LHS, const DIArgList *RHS) {
1542 return LHS.isKeyOf(RHS);
1543 }
1544
1545 static bool isEqual(const DIArgList *LHS, const DIArgList *RHS) {
1546 return LHS == RHS;
1547 }
1548};
1549
1550/// DenseMapInfo for MDNode subclasses.
1551template <class NodeTy> struct MDNodeInfo {
1552 using KeyTy = MDNodeKeyImpl<NodeTy>;
1553 using SubsetEqualTy = MDNodeSubsetEqualImpl<NodeTy>;
1554
1555 static unsigned getHashValue(const KeyTy &Key) { return Key.getHashValue(); }
1556
1557 static unsigned getHashValue(const NodeTy *N) {
1558 return KeyTy(N).getHashValue();
1559 }
1560
1561 static bool isEqual(const KeyTy &LHS, const NodeTy *RHS) {
1562 return SubsetEqualTy::isSubsetEqual(LHS, RHS) || LHS.isKeyOf(RHS);
1563 }
1564
1565 static bool isEqual(const NodeTy *LHS, const NodeTy *RHS) {
1566 if (LHS == RHS)
1567 return true;
1568 return SubsetEqualTy::isSubsetEqual(LHS, RHS);
1569 }
1570};
1571
1572#define HANDLE_MDNODE_LEAF(CLASS) using CLASS##Info = MDNodeInfo<CLASS>;
1573#include "llvm/IR/Metadata.def"
1574
1575/// Single metadata attachment, forms linked list ended by index 0.
1576struct MDAttachment {
1577 unsigned Next = 0;
1578 unsigned MDKind;
1579 TrackingMDNodeRef Node;
1580};
1581
1582/// Head pointer for a Value's ValueHandleBase doubly-linked list, stored in
1583/// LLVMContextImpl::ValueHandles. The first node's PrevPtr points to Head, so
1584/// relocating the bucket refreshes PrevPtr to the new Head address.
1585class ValueHandleHead {
1586 // Tag Head with true via PointerIntPair so RemoveFromUseList can
1587 // distinguish ValueHandleHead::Head from an untagged ValueHandleBase::Next
1588 // when accessed through *PrevPtr.
1589 using TaggedPtr = PointerIntPair<ValueHandleBase *, 1, bool>;
1590
1591 ValueHandleBase *Head =
1592 static_cast<ValueHandleBase *>(TaggedPtr(nullptr, true).getOpaqueValue());
1593
1594public:
1595 ValueHandleBase *get() const {
1596 return TaggedPtr::getFromOpaqueValue(V: Head).getPointer();
1597 }
1598
1599 ValueHandleBase **getAddress() { return &Head; }
1600
1601 // Replace the pointer in *Slot with NewPtr while preserving its tag bit,
1602 // and return the old TaggedPtr.
1603 static TaggedPtr exchange(ValueHandleBase **Slot, ValueHandleBase *NewPtr) {
1604 TaggedPtr Old = TaggedPtr::getFromOpaqueValue(V: *Slot);
1605 TaggedPtr Updated = Old;
1606 Updated.setPointer(NewPtr);
1607 *Slot = static_cast<ValueHandleBase *>(Updated.getOpaqueValue());
1608 return Old;
1609 }
1610
1611 ValueHandleHead() = default;
1612 ValueHandleHead(ValueHandleHead &&Other) noexcept;
1613 ValueHandleHead &operator=(ValueHandleHead &&) = delete;
1614 ValueHandleHead(const ValueHandleHead &) = delete;
1615 ValueHandleHead &operator=(const ValueHandleHead &) = delete;
1616};
1617
1618class LLVMContextImpl {
1619public:
1620 /// OwnedModules - The set of modules instantiated in this context, and which
1621 /// will be automatically deleted if this context is deleted.
1622 SmallPtrSet<Module *, 4> OwnedModules;
1623
1624 /// MachineFunctionNums - Keep the next available unique number available for
1625 /// a MachineFunction in given module. Module must in OwnedModules.
1626 DenseMap<Module *, unsigned> MachineFunctionNums;
1627
1628 /// The main remark streamer used by all the other streamers (e.g. IR, MIR,
1629 /// frontends, etc.). This should only be used by the specific streamers, and
1630 /// never directly.
1631 std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer;
1632
1633 /// The virtual file system used for inputs.
1634 IntrusiveRefCntPtr<vfs::FileSystem> FS;
1635
1636 std::unique_ptr<DiagnosticHandler> DiagHandler;
1637 bool RespectDiagnosticFilters = false;
1638 bool DiagnosticsHotnessRequested = false;
1639 /// The minimum hotness value a diagnostic needs in order to be included in
1640 /// optimization diagnostics.
1641 ///
1642 /// The threshold is an Optional value, which maps to one of the 3 states:
1643 /// 1). 0 => threshold disabled. All emarks will be printed.
1644 /// 2). positive int => manual threshold by user. Remarks with hotness exceed
1645 /// threshold will be printed.
1646 /// 3). None => 'auto' threshold by user. The actual value is not
1647 /// available at command line, but will be synced with
1648 /// hotness threhold from profile summary during
1649 /// compilation.
1650 ///
1651 /// State 1 and 2 are considered as terminal states. State transition is
1652 /// only allowed from 3 to 2, when the threshold is first synced with profile
1653 /// summary. This ensures that the threshold is set only once and stays
1654 /// constant.
1655 ///
1656 /// If threshold option is not specified, it is disabled (0) by default.
1657 std::optional<uint64_t> DiagnosticsHotnessThreshold = 0;
1658
1659 /// The percentage of difference between profiling branch weights and
1660 /// llvm.expect branch weights to tolerate when emiting MisExpect diagnostics
1661 std::optional<uint32_t> DiagnosticsMisExpectTolerance = 0;
1662 bool MisExpectWarningRequested = false;
1663
1664 /// The specialized remark streamer used by LLVM's OptimizationRemarkEmitter.
1665 std::unique_ptr<LLVMRemarkStreamer> LLVMRS;
1666
1667 LLVMContext::YieldCallbackTy YieldCallback = nullptr;
1668 void *YieldOpaqueHandle = nullptr;
1669
1670 DenseMap<const Value *, ValueName *> ValueNames;
1671
1672 DenseMap<unsigned, std::unique_ptr<ConstantInt>> IntZeroConstants;
1673 DenseMap<unsigned, std::unique_ptr<ConstantInt>> IntOneConstants;
1674 DenseMap<APInt, std::unique_ptr<ConstantInt>> IntConstants;
1675 DenseMap<std::pair<ElementCount, APInt>, std::unique_ptr<ConstantInt>>
1676 IntSplatConstants;
1677
1678 DenseMap<unsigned, std::unique_ptr<ConstantByte>> ByteZeroConstants;
1679 DenseMap<unsigned, std::unique_ptr<ConstantByte>> ByteOneConstants;
1680 DenseMap<APInt, std::unique_ptr<ConstantByte>> ByteConstants;
1681 DenseMap<std::pair<ElementCount, APInt>, std::unique_ptr<ConstantByte>>
1682 ByteSplatConstants;
1683
1684 DenseMap<APFloat, std::unique_ptr<ConstantFP>> FPConstants;
1685 DenseMap<std::pair<ElementCount, APFloat>, std::unique_ptr<ConstantFP>>
1686 FPSplatConstants;
1687
1688 EnumAttributeImpl *EnumAttrs[Attribute::NumEnumAttrKinds] = {};
1689 UniquingSet<IntAttributeImpl> IntAttrs;
1690 UniquingSet<StringAttributeImpl> StringAttrs;
1691 UniquingSet<TypeAttributeImpl> TypeAttrs;
1692 FoldingSet<AttributeImpl> AttrsSet;
1693 UniquingSet<AttributeListImpl> AttrsLists;
1694 UniquingSet<AttributeSetNode> AttrsSetNodes;
1695
1696 StringMap<MDString, BumpPtrAllocator> MDStringCache;
1697 DenseMap<Value *, ValueAsMetadata *> ValuesAsMetadata;
1698 DenseMap<Metadata *, MetadataAsValue *> MetadataAsValues;
1699 DenseSet<DIArgList *, DIArgListInfo> DIArgLists;
1700
1701 uint32_t NextMetadataPrintID = 0;
1702
1703 uint32_t allocateMetadataPrintID() { return NextMetadataPrintID++; }
1704
1705 void getAllMetadataNodes(SmallVectorImpl<MDNode *> &Nodes) const;
1706
1707 uint32_t getMetadataPrintID(const MDNode *N) const {
1708 return N->getHeader().MetadataPrintID;
1709 }
1710
1711 void setMetadataPrintID(MDNode *N, uint32_t ID) {
1712 N->getHeader().MetadataPrintID = ID;
1713 }
1714
1715#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
1716 DenseSet<CLASS *, CLASS##Info> CLASS##s;
1717#include "llvm/IR/Metadata.def"
1718
1719 // Optional map for looking up composite types by identifier.
1720 std::optional<DenseMap<const MDString *, DICompositeType *>> DITypeMap;
1721
1722 // MDNodes may be uniqued or not uniqued. When they're not uniqued, they
1723 // aren't in the MDNodeSet, but they're still shared between objects, so no
1724 // one object can destroy them. Keep track of them here so we can delete
1725 // them on context teardown.
1726 std::vector<MDNode *> DistinctMDNodes;
1727
1728 // Temporary nodes are caller-owned, but track live ones for persistent
1729 // metadata print IDs.
1730 DenseSet<MDNode *> TemporaryMDNodes;
1731
1732 // ConstantRangeListAttributeImpl is a TrailingObjects/ArrayRef of
1733 // ConstantRange. Since this is a dynamically sized class, it's not
1734 // possible to use SpecificBumpPtrAllocator. Instead, we use normal Alloc
1735 // for allocation and record all allocated pointers in this vector. In the
1736 // LLVMContext destructor, call the destuctors of everything in the vector.
1737 std::vector<ConstantRangeListAttributeImpl *> ConstantRangeListAttributes;
1738
1739 DenseMap<Type *, std::unique_ptr<ConstantAggregateZero>> CAZConstants;
1740
1741 using ArrayConstantsTy = ConstantUniqueMap<ConstantArray>;
1742 ArrayConstantsTy ArrayConstants;
1743
1744 using StructConstantsTy = ConstantUniqueMap<ConstantStruct>;
1745 StructConstantsTy StructConstants;
1746
1747 using VectorConstantsTy = ConstantUniqueMap<ConstantVector>;
1748 VectorConstantsTy VectorConstants;
1749
1750 DenseMap<Type *, std::unique_ptr<ConstantPointerNull>> CPNConstants;
1751
1752 DenseMap<TargetExtType *, std::unique_ptr<ConstantTargetNone>> CTNConstants;
1753
1754 DenseMap<Type *, std::unique_ptr<UndefValue>> UVConstants;
1755
1756 DenseMap<Type *, std::unique_ptr<PoisonValue>> PVConstants;
1757
1758 StringMap<std::unique_ptr<ConstantDataSequential>> CDSConstants;
1759
1760 DenseMap<const BasicBlock *, BlockAddress *> BlockAddresses;
1761
1762 DenseMap<const GlobalValue *, DSOLocalEquivalent *> DSOLocalEquivalents;
1763
1764 DenseMap<const GlobalValue *, NoCFIValue *> NoCFIValues;
1765
1766 ConstantUniqueMap<ConstantPtrAuth> ConstantPtrAuths;
1767
1768 ConstantUniqueMap<ConstantExpr> ExprConstants;
1769
1770 ConstantUniqueMap<InlineAsm> InlineAsms;
1771
1772 ConstantInt *TheTrueVal = nullptr;
1773 ConstantInt *TheFalseVal = nullptr;
1774
1775 ConstantByte *TheTrueByteVal = nullptr;
1776 ConstantByte *TheFalseByteVal = nullptr;
1777
1778 // Basic type instances.
1779 Type VoidTy, LabelTy, HalfTy, BFloatTy, FloatTy, DoubleTy, MetadataTy,
1780 TokenTy;
1781 Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_AMXTy;
1782 IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty, Int128Ty;
1783 ByteType Byte1Ty, Byte8Ty, Byte16Ty, Byte32Ty, Byte64Ty, Byte128Ty;
1784
1785 std::unique_ptr<ConstantTokenNone> TheNoneToken;
1786
1787 BumpPtrAllocator Alloc;
1788 UniqueStringSaver Saver{Alloc};
1789 SpecificBumpPtrAllocator<ConstantRangeAttributeImpl>
1790 ConstantRangeAttributeAlloc;
1791
1792 DenseMap<unsigned, ByteType *> ByteTypes;
1793 DenseMap<unsigned, IntegerType *> IntegerTypes;
1794
1795 using FunctionTypeSet = DenseSet<FunctionType *, FunctionTypeKeyInfo>;
1796 FunctionTypeSet FunctionTypes;
1797 using StructTypeSet = DenseSet<StructType *, AnonStructTypeKeyInfo>;
1798 StructTypeSet AnonStructTypes;
1799 StringMap<StructType *> NamedStructTypes;
1800 unsigned NamedStructTypesUniqueID = 0;
1801
1802 using TargetExtTypeSet = DenseSet<TargetExtType *, TargetExtTypeKeyInfo>;
1803 TargetExtTypeSet TargetExtTypes;
1804
1805 DenseMap<std::pair<Type *, uint64_t>, ArrayType *> ArrayTypes;
1806 DenseMap<std::pair<Type *, ElementCount>, VectorType *> VectorTypes;
1807 PointerType *AS0PointerType = nullptr; // AddrSpace = 0
1808 DenseMap<unsigned, PointerType *> PointerTypes;
1809 DenseMap<std::pair<Type *, unsigned>, TypedPointerType *> ASTypedPointerTypes;
1810
1811 /// ValueHandles - This map keeps track of all of the value handles that are
1812 /// watching a Value*. The Value::HasValueHandle bit is used to know
1813 /// whether or not a value has an entry in this map.
1814 using ValueHandlesTy = DenseMap<Value *, ValueHandleHead>;
1815 ValueHandlesTy ValueHandles;
1816
1817 /// CustomMDKindNames - Map to hold the metadata string to ID mapping.
1818 StringMap<unsigned> CustomMDKindNames;
1819
1820 /// Collection of metadata attachments in this context.
1821 SmallVector<MDAttachment, 0> Metadatas;
1822 /// Index of first free Metadatas entry, linked list via MDAttachment::Next.
1823 unsigned MetadataRecycleHead = 0;
1824 /// Number of currently unused metadata entries. Only used/updated in debug
1825 /// builds to ensure that all metadata attachments are properly freed.
1826 unsigned MetadataRecycleSize = 0;
1827
1828 /// Collection of per-GlobalObject sections used in this context.
1829 DenseMap<const GlobalObject *, StringRef> GlobalObjectSections;
1830
1831 /// Collection of per-GlobalValue partitions used in this context.
1832 DenseMap<const GlobalValue *, StringRef> GlobalValuePartitions;
1833
1834 DenseMap<const GlobalValue *, GlobalValue::SanitizerMetadata>
1835 GlobalValueSanitizerMetadata;
1836
1837 /// A set of interned tags for operand bundles. The StringMap maps
1838 /// bundle tags to their IDs.
1839 ///
1840 /// \see LLVMContext::getOperandBundleTagID
1841 StringMap<uint32_t> BundleTagCache;
1842
1843 StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef Tag);
1844 void getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const;
1845 uint32_t getOperandBundleTagID(StringRef Tag) const;
1846
1847 /// A set of interned synchronization scopes. The StringMap maps
1848 /// synchronization scope names to their respective synchronization scope IDs.
1849 StringMap<SyncScope::ID> SSC;
1850
1851 /// getOrInsertSyncScopeID - Maps synchronization scope name to
1852 /// synchronization scope ID. Every synchronization scope registered with
1853 /// LLVMContext has unique ID except pre-defined ones.
1854 SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
1855
1856 /// getSyncScopeNames - Populates client supplied SmallVector with
1857 /// synchronization scope names registered with LLVMContext. Synchronization
1858 /// scope names are ordered by increasing synchronization scope IDs.
1859 void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
1860
1861 /// getSyncScopeName - Returns the name of a SyncScope::ID
1862 /// registered with LLVMContext, if any.
1863 std::optional<StringRef> getSyncScopeName(SyncScope::ID Id) const;
1864
1865 /// Maintain the GC name for each function.
1866 ///
1867 /// This saves allocating an additional word in Function for programs which
1868 /// do not use GC (i.e., most programs) at the cost of increased overhead for
1869 /// clients which do use GC.
1870 DenseMap<const Function *, std::string> GCNames;
1871
1872 /// Flag to indicate if Value (other than GlobalValue) retains their name or
1873 /// not.
1874 bool DiscardValueNames = false;
1875
1876 LLVMContextImpl(LLVMContext &C);
1877 ~LLVMContextImpl();
1878
1879 mutable OptPassGate *OPG = nullptr;
1880
1881 /// Access the object which can disable optional passes and individual
1882 /// optimizations at compile time.
1883 OptPassGate &getOptPassGate() const;
1884
1885 /// Set the object which can disable optional passes and individual
1886 /// optimizations at compile time.
1887 ///
1888 /// The lifetime of the object must be guaranteed to extend as long as the
1889 /// LLVMContext is used by compilation.
1890 void setOptPassGate(OptPassGate &);
1891
1892 /// Mapping of blocks to collections of "trailing" DbgVariableRecords. As part
1893 /// of the "RemoveDIs" project, debug-info variable location records are going
1894 /// to cease being instructions... which raises the problem of where should
1895 /// they be recorded when we remove the terminator of a blocks, such as:
1896 ///
1897 /// %foo = add i32 0, 0
1898 /// br label %bar
1899 ///
1900 /// If the branch is removed, a legitimate transient state while editing a
1901 /// block, any debug-records between those two instructions will not have a
1902 /// location. Each block thus records any DbgVariableRecord records that
1903 /// "trail" in such a way. These are stored in LLVMContext because typically
1904 /// LLVM only edits a small number of blocks at a time, so there's no need to
1905 /// bloat BasicBlock with such a data structure.
1906 SmallDenseMap<BasicBlock *, DbgMarker *> TrailingDbgRecords;
1907
1908 // Set, get and delete operations for TrailingDbgRecords.
1909 void setTrailingDbgRecords(BasicBlock *B, DbgMarker *M) {
1910 assert(!TrailingDbgRecords.count(B));
1911 TrailingDbgRecords[B] = M;
1912 }
1913
1914 DbgMarker *getTrailingDbgRecords(BasicBlock *B) {
1915 return TrailingDbgRecords.lookup(Val: B);
1916 }
1917
1918 void deleteTrailingDbgRecords(BasicBlock *B) { TrailingDbgRecords.erase(Val: B); }
1919
1920 std::string DefaultTargetCPU;
1921 std::string DefaultTargetFeatures;
1922
1923 cl::LibraryOptionsContext LibraryOptions;
1924
1925 /// The next available source atom group number. The front end is responsible
1926 /// for assigning source atom numbers, but certain optimisations need to
1927 /// assign new group numbers to a set of instructions. Most often code
1928 /// duplication optimisations like loop unroll. Tracking a global maximum
1929 /// value means we can know (cheaply) we're never using a group number that's
1930 /// already used within this function.
1931 ///
1932 /// Start a 1 because 0 means the source location isn't part of an atom group.
1933 uint64_t NextAtomGroup = 1;
1934};
1935
1936} // end namespace llvm
1937
1938#endif // LLVM_LIB_IR_LLVMCONTEXTIMPL_H
1939