xref: /freebsd/contrib/llvm-project/llvm/lib/IR/LLVMContextImpl.cpp (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
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   CTNConstants.clear();
117   UVConstants.clear();
118   PVConstants.clear();
119   IntConstants.clear();
120   FPConstants.clear();
121   CDSConstants.clear();
122 
123   // Destroy attribute node lists.
124   for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
125          E = AttrsSetNodes.end(); I != E; ) {
126     FoldingSetIterator<AttributeSetNode> Elem = I++;
127     delete &*Elem;
128   }
129 
130   // Destroy MetadataAsValues.
131   {
132     SmallVector<MetadataAsValue *, 8> MDVs;
133     MDVs.reserve(MetadataAsValues.size());
134     for (auto &Pair : MetadataAsValues)
135       MDVs.push_back(Pair.second);
136     MetadataAsValues.clear();
137     for (auto *V : MDVs)
138       delete V;
139   }
140 
141   // Destroy ValuesAsMetadata.
142   for (auto &Pair : ValuesAsMetadata)
143     delete Pair.second;
144 }
145 
146 void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
147   SmallSetVector<ConstantArray *, 4> WorkList;
148 
149   // When ArrayConstants are of substantial size and only a few in them are
150   // dead, starting WorkList with all elements of ArrayConstants can be
151   // wasteful. Instead, starting WorkList with only elements that have empty
152   // uses.
153   for (ConstantArray *C : ArrayConstants)
154     if (C->use_empty())
155       WorkList.insert(C);
156 
157   while (!WorkList.empty()) {
158     ConstantArray *C = WorkList.pop_back_val();
159     if (C->use_empty()) {
160       for (const Use &Op : C->operands()) {
161         if (auto *COp = dyn_cast<ConstantArray>(Op))
162           WorkList.insert(COp);
163       }
164       C->destroyConstant();
165     }
166   }
167 }
168 
169 void Module::dropTriviallyDeadConstantArrays() {
170   Context.pImpl->dropTriviallyDeadConstantArrays();
171 }
172 
173 namespace llvm {
174 
175 /// Make MDOperand transparent for hashing.
176 ///
177 /// This overload of an implementation detail of the hashing library makes
178 /// MDOperand hash to the same value as a \a Metadata pointer.
179 ///
180 /// Note that overloading \a hash_value() as follows:
181 ///
182 /// \code
183 ///     size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
184 /// \endcode
185 ///
186 /// does not cause MDOperand to be transparent.  In particular, a bare pointer
187 /// doesn't get hashed before it's combined, whereas \a MDOperand would.
188 static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
189 
190 } // end namespace llvm
191 
192 unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
193   unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
194 #ifndef NDEBUG
195   {
196     SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
197     unsigned RawHash = calculateHash(MDs);
198     assert(Hash == RawHash &&
199            "Expected hash of MDOperand to equal hash of Metadata*");
200   }
201 #endif
202   return Hash;
203 }
204 
205 unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
206   return hash_combine_range(Ops.begin(), Ops.end());
207 }
208 
209 StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
210   uint32_t NewIdx = BundleTagCache.size();
211   return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
212 }
213 
214 void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
215   Tags.resize(BundleTagCache.size());
216   for (const auto &T : BundleTagCache)
217     Tags[T.second] = T.first();
218 }
219 
220 uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
221   auto I = BundleTagCache.find(Tag);
222   assert(I != BundleTagCache.end() && "Unknown tag!");
223   return I->second;
224 }
225 
226 SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
227   auto NewSSID = SSC.size();
228   assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
229          "Hit the maximum number of synchronization scopes allowed!");
230   return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
231 }
232 
233 void LLVMContextImpl::getSyncScopeNames(
234     SmallVectorImpl<StringRef> &SSNs) const {
235   SSNs.resize(SSC.size());
236   for (const auto &SSE : SSC)
237     SSNs[SSE.second] = SSE.first();
238 }
239 
240 /// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
241 /// singleton OptBisect if not explicitly set.
242 OptPassGate &LLVMContextImpl::getOptPassGate() const {
243   if (!OPG)
244     OPG = &getGlobalPassGate();
245   return *OPG;
246 }
247 
248 void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
249   this->OPG = &OPG;
250 }
251 
252 bool LLVMContextImpl::getOpaquePointers() {
253   if (LLVM_UNLIKELY(!OpaquePointers))
254     OpaquePointers = OpaquePointersCL;
255   return *OpaquePointers;
256 }
257 
258 void LLVMContextImpl::setOpaquePointers(bool OP) {
259   assert((!OpaquePointers || *OpaquePointers == OP) &&
260          "Cannot change opaque pointers mode once set");
261   OpaquePointers = OP;
262 }
263