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