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