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