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