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