1//===- LLVMContextImpl.cpp - Implement LLVMContextImpl --------------------===//
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 implements the opaque LLVMContextImpl.
10//
11//===----------------------------------------------------------------------===//
12
13#include "LLVMContextImpl.h"
14#include "AttributeImpl.h"
15#include "llvm/ADT/StringMapEntry.h"
16#include "llvm/ADT/iterator.h"
17#include "llvm/IR/DiagnosticHandler.h"
18#include "llvm/IR/LLVMRemarkStreamer.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/OptBisect.h"
21#include "llvm/IR/Type.h"
22#include "llvm/IR/Use.h"
23#include "llvm/IR/User.h"
24#include "llvm/Remarks/RemarkStreamer.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/ErrorHandling.h"
27#include <cassert>
28
29using namespace llvm;
30
31LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
32 : DiagHandler(std::make_unique<DiagnosticHandler>()),
33 VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID),
34 HalfTy(C, Type::HalfTyID), BFloatTy(C, Type::BFloatTyID),
35 FloatTy(C, Type::FloatTyID), DoubleTy(C, Type::DoubleTyID),
36 MetadataTy(C, Type::MetadataTyID), TokenTy(C, Type::TokenTyID),
37 X86_FP80Ty(C, Type::X86_FP80TyID), FP128Ty(C, Type::FP128TyID),
38 PPC_FP128Ty(C, Type::PPC_FP128TyID), X86_AMXTy(C, Type::X86_AMXTyID),
39 Int1Ty(C, 1), Int8Ty(C, 8), Int16Ty(C, 16), Int32Ty(C, 32),
40 Int64Ty(C, 64), Int128Ty(C, 128), Byte1Ty(C, 1), Byte8Ty(C, 8),
41 Byte16Ty(C, 16), Byte32Ty(C, 32), Byte64Ty(C, 64), Byte128Ty(C, 128) {}
42
43LLVMContextImpl::~LLVMContextImpl() {
44#ifndef NDEBUG
45 // Check that any variable location records that fell off the end of a block
46 // when it's terminator was removed were eventually replaced. This assertion
47 // firing indicates that DbgVariableRecords went missing during the lifetime
48 // of the LLVMContext.
49 assert(TrailingDbgRecords.empty() && "DbgRecords in blocks not cleaned");
50#endif
51
52 // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
53 // will call LLVMContextImpl::removeModule, thus invalidating iterators into
54 // the container. Avoid iterators during this operation:
55 while (!OwnedModules.empty())
56 delete *OwnedModules.begin();
57
58#ifndef NDEBUG
59 // Check for metadata references from leaked Values.
60 for (auto &Pair : ValueMetadata)
61 Pair.first->dump();
62 assert(ValueMetadata.empty() && "Values with metadata have been leaked");
63#endif
64
65 // Drop references for MDNodes. Do this before Values get deleted to avoid
66 // unnecessary RAUW when nodes are still unresolved.
67 for (auto *I : DistinctMDNodes)
68 I->dropAllReferences();
69#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
70 for (auto *I : CLASS##s) \
71 I->dropAllReferences();
72#include "llvm/IR/Metadata.def"
73
74 // Also drop references that come from the Value bridges.
75 for (auto &Pair : ValuesAsMetadata)
76 Pair.second->dropUsers();
77 for (auto &Pair : MetadataAsValues)
78 Pair.second->dropUse();
79 // Do not untrack ValueAsMetadata references for DIArgLists, as they have
80 // already been more efficiently untracked above.
81 for (DIArgList *AL : DIArgLists) {
82 AL->dropAllReferences(/* Untrack */ false);
83 delete AL;
84 }
85 DIArgLists.clear();
86
87 // Destroy MDNodes.
88 for (MDNode *I : DistinctMDNodes)
89 I->deleteAsSubclass();
90
91 for (auto *ConstantRangeListAttribute : ConstantRangeListAttributes)
92 ConstantRangeListAttribute->~ConstantRangeListAttributeImpl();
93#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
94 for (CLASS * I : CLASS##s) \
95 delete I;
96#include "llvm/IR/Metadata.def"
97
98 // Free the constants.
99 for (auto *I : ExprConstants)
100 I->dropAllReferences();
101 for (auto *I : ArrayConstants)
102 I->dropAllReferences();
103 for (auto *I : StructConstants)
104 I->dropAllReferences();
105 for (auto *I : VectorConstants)
106 I->dropAllReferences();
107 ExprConstants.freeConstants();
108 ArrayConstants.freeConstants();
109 StructConstants.freeConstants();
110 VectorConstants.freeConstants();
111 ConstantPtrAuths.freeConstants();
112 InlineAsms.freeConstants();
113
114 CAZConstants.clear();
115 CPNConstants.clear();
116 CTNConstants.clear();
117 UVConstants.clear();
118 PVConstants.clear();
119 IntZeroConstants.clear();
120 IntOneConstants.clear();
121 IntConstants.clear();
122 IntSplatConstants.clear();
123 ByteZeroConstants.clear();
124 ByteOneConstants.clear();
125 ByteConstants.clear();
126 ByteSplatConstants.clear();
127 FPConstants.clear();
128 FPSplatConstants.clear();
129 CDSConstants.clear();
130
131 // Destroy attribute node lists.
132 for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
133 E = AttrsSetNodes.end(); I != E; ) {
134 FoldingSetIterator<AttributeSetNode> Elem = I++;
135 delete &*Elem;
136 }
137
138 // Destroy MetadataAsValues.
139 {
140 SmallVector<MetadataAsValue *, 8> MDVs;
141 MDVs.reserve(N: MetadataAsValues.size());
142 for (auto &Pair : MetadataAsValues)
143 MDVs.push_back(Elt: Pair.second);
144 MetadataAsValues.clear();
145 for (auto *V : MDVs)
146 delete V;
147 }
148
149 // Destroy ValuesAsMetadata.
150 for (auto &Pair : ValuesAsMetadata)
151 delete Pair.second;
152}
153
154namespace llvm {
155
156/// Make MDOperand transparent for hashing.
157///
158/// This overload of an implementation detail of the hashing library makes
159/// MDOperand hash to the same value as a \a Metadata pointer.
160///
161/// Note that overloading \a hash_value() as follows:
162///
163/// \code
164/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
165/// \endcode
166///
167/// does not cause MDOperand to be transparent. In particular, a bare pointer
168/// doesn't get hashed before it's combined, whereas \a MDOperand would.
169static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
170
171} // end namespace llvm
172
173unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
174 unsigned Hash = hash_combine_range(first: N->op_begin() + Offset, last: N->op_end());
175#ifndef NDEBUG
176 {
177 SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
178 unsigned RawHash = calculateHash(MDs);
179 assert(Hash == RawHash &&
180 "Expected hash of MDOperand to equal hash of Metadata*");
181 }
182#endif
183 return Hash;
184}
185
186unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
187 return hash_combine_range(R&: Ops);
188}
189
190StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
191 uint32_t NewIdx = BundleTagCache.size();
192 return &*(BundleTagCache.insert(KV: std::make_pair(x&: Tag, y&: NewIdx)).first);
193}
194
195void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
196 Tags.resize(N: BundleTagCache.size());
197 for (const auto &T : BundleTagCache)
198 Tags[T.second] = T.first();
199}
200
201uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
202 auto I = BundleTagCache.find(Key: Tag);
203 assert(I != BundleTagCache.end() && "Unknown tag!");
204 return I->second;
205}
206
207SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
208 auto NewSSID = SSC.size();
209 assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
210 "Hit the maximum number of synchronization scopes allowed!");
211 return SSC.insert(KV: std::make_pair(x&: SSN, y: SyncScope::ID(NewSSID))).first->second;
212}
213
214void LLVMContextImpl::getSyncScopeNames(
215 SmallVectorImpl<StringRef> &SSNs) const {
216 SSNs.resize(N: SSC.size());
217 for (const auto &SSE : SSC)
218 SSNs[SSE.second] = SSE.first();
219}
220
221std::optional<StringRef>
222LLVMContextImpl::getSyncScopeName(SyncScope::ID Id) const {
223 for (const auto &SSE : SSC) {
224 if (SSE.second != Id)
225 continue;
226 return SSE.first();
227 }
228 return std::nullopt;
229}
230
231/// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
232/// singleton OptBisect if not explicitly set.
233OptPassGate &LLVMContextImpl::getOptPassGate() const {
234 if (!OPG)
235 OPG = &getGlobalPassGate();
236 return *OPG;
237}
238
239void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
240 this->OPG = &OPG;
241}
242