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/StringMapEntry.h"
16#include "llvm/IR/DiagnosticHandler.h"
17#include "llvm/IR/LLVMRemarkStreamer.h"
18#include "llvm/IR/Module.h"
19#include "llvm/IR/OptBisect.h"
20#include "llvm/IR/Type.h"
21#include "llvm/IR/User.h"
22#include "llvm/Remarks/RemarkStreamer.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <cassert>
26
27using namespace llvm;
28
29LLVMContextImpl::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_AMXTy(C, Type::X86_AMXTyID),
37 Int1Ty(C, 1), Int8Ty(C, 8), Int16Ty(C, 16), Int32Ty(C, 32),
38 Int64Ty(C, 64), Int128Ty(C, 128), Byte1Ty(C, 1), Byte8Ty(C, 8),
39 Byte16Ty(C, 16), Byte32Ty(C, 32), Byte64Ty(C, 64), Byte128Ty(C, 128) {}
40
41void LLVMContextImpl::getAllMetadataNodes(
42 SmallVectorImpl<MDNode *> &Nodes) const {
43 Nodes.append(in_start: DistinctMDNodes.begin(), in_end: DistinctMDNodes.end());
44#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
45 Nodes.append(CLASS##s.begin(), CLASS##s.end());
46#include "llvm/IR/Metadata.def"
47 Nodes.append(in_start: TemporaryMDNodes.begin(), in_end: TemporaryMDNodes.end());
48}
49
50LLVMContextImpl::~LLVMContextImpl() {
51#ifndef NDEBUG
52 // Check that any variable location records that fell off the end of a block
53 // when it's terminator was removed were eventually replaced. This assertion
54 // firing indicates that DbgVariableRecords went missing during the lifetime
55 // of the LLVMContext.
56 assert(TrailingDbgRecords.empty() && "DbgRecords in blocks not cleaned");
57#endif
58
59 // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
60 // will call LLVMContextImpl::removeModule, thus invalidating iterators into
61 // the container. Avoid iterators during this operation:
62 while (!OwnedModules.empty())
63 delete *OwnedModules.begin();
64
65#ifndef NDEBUG
66 // Check for metadata references from leaked Values.
67 assert((Metadatas.empty() || MetadataRecycleSize + 1 == Metadatas.size()) &&
68 "Values with metadata have been leaked");
69#endif
70
71 // Drop references for MDNodes. Do this before Values get deleted to avoid
72 // unnecessary RAUW when nodes are still unresolved.
73 for (auto *I : DistinctMDNodes)
74 I->dropAllReferences();
75#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
76 for (auto *I : CLASS##s) \
77 I->dropAllReferences();
78#include "llvm/IR/Metadata.def"
79
80 // Also drop references that come from the Value bridges.
81 for (auto &Pair : ValuesAsMetadata)
82 Pair.second->dropUsers();
83 for (auto &Pair : MetadataAsValues)
84 Pair.second->dropUse();
85 // Do not untrack ValueAsMetadata references for DIArgLists, as they have
86 // already been more efficiently untracked above.
87 for (DIArgList *AL : DIArgLists) {
88 AL->dropAllReferences(/* Untrack */ false);
89 delete AL;
90 }
91 DIArgLists.clear();
92
93 // Destroy MDNodes.
94 for (MDNode *I : DistinctMDNodes)
95 I->deleteAsSubclass();
96
97 for (auto *ConstantRangeListAttribute : ConstantRangeListAttributes)
98 ConstantRangeListAttribute->~ConstantRangeListAttributeImpl();
99#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
100 for (CLASS * I : CLASS##s) \
101 delete I;
102#include "llvm/IR/Metadata.def"
103
104 // Free the constants.
105 for (auto *I : ExprConstants)
106 I->dropAllReferences();
107 for (auto *I : ArrayConstants)
108 I->dropAllReferences();
109 for (auto *I : StructConstants)
110 I->dropAllReferences();
111 for (auto *I : VectorConstants)
112 I->dropAllReferences();
113 ExprConstants.freeConstants();
114 ArrayConstants.freeConstants();
115 StructConstants.freeConstants();
116 VectorConstants.freeConstants();
117 ConstantPtrAuths.freeConstants();
118 InlineAsms.freeConstants();
119
120 CAZConstants.clear();
121 CPNConstants.clear();
122 CTNConstants.clear();
123 UVConstants.clear();
124 PVConstants.clear();
125 IntZeroConstants.clear();
126 IntOneConstants.clear();
127 IntConstants.clear();
128 IntSplatConstants.clear();
129 ByteZeroConstants.clear();
130 ByteOneConstants.clear();
131 ByteConstants.clear();
132 ByteSplatConstants.clear();
133 FPConstants.clear();
134 FPSplatConstants.clear();
135 CDSConstants.clear();
136
137 // Destroy attribute node lists.
138 for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
139 E = AttrsSetNodes.end(); I != E; ) {
140 FoldingSetIterator<AttributeSetNode> Elem = I++;
141 delete &*Elem;
142 }
143
144 // Destroy MetadataAsValues.
145 {
146 SmallVector<MetadataAsValue *, 8> MDVs;
147 MDVs.reserve(N: MetadataAsValues.size());
148 for (auto &Pair : MetadataAsValues)
149 MDVs.push_back(Elt: Pair.second);
150 MetadataAsValues.clear();
151 for (auto *V : MDVs)
152 delete V;
153 }
154
155 // Destroy ValuesAsMetadata.
156 for (auto &Pair : ValuesAsMetadata)
157 delete Pair.second;
158}
159
160namespace llvm {
161
162/// Make MDOperand transparent for hashing.
163///
164/// This overload of an implementation detail of the hashing library makes
165/// MDOperand hash to the same value as a \a Metadata pointer.
166///
167/// Note that overloading \a hash_value() as follows:
168///
169/// \code
170/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
171/// \endcode
172///
173/// does not cause MDOperand to be transparent. In particular, a bare pointer
174/// doesn't get hashed before it's combined, whereas \a MDOperand would.
175static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
176
177} // end namespace llvm
178
179unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
180 unsigned Hash = hash_combine_range(first: N->op_begin() + Offset, last: N->op_end());
181#ifndef NDEBUG
182 {
183 SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
184 unsigned RawHash = calculateHash(MDs);
185 assert(Hash == RawHash &&
186 "Expected hash of MDOperand to equal hash of Metadata*");
187 }
188#endif
189 return Hash;
190}
191
192unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
193 return hash_combine_range(R&: Ops);
194}
195
196StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
197 uint32_t NewIdx = BundleTagCache.size();
198 return &*(BundleTagCache.insert(KV: std::make_pair(x&: Tag, y&: NewIdx)).first);
199}
200
201void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
202 Tags.resize(N: BundleTagCache.size());
203 for (const auto &T : BundleTagCache)
204 Tags[T.second] = T.first();
205}
206
207uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
208 auto I = BundleTagCache.find(Key: Tag);
209 assert(I != BundleTagCache.end() && "Unknown tag!");
210 return I->second;
211}
212
213SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
214 auto NewSSID = SSC.size();
215 assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
216 "Hit the maximum number of synchronization scopes allowed!");
217 return SSC.insert(KV: std::make_pair(x&: SSN, y: SyncScope::ID(NewSSID))).first->second;
218}
219
220void LLVMContextImpl::getSyncScopeNames(
221 SmallVectorImpl<StringRef> &SSNs) const {
222 SSNs.resize(N: SSC.size());
223 for (const auto &SSE : SSC)
224 SSNs[SSE.second] = SSE.first();
225}
226
227std::optional<StringRef>
228LLVMContextImpl::getSyncScopeName(SyncScope::ID Id) const {
229 for (const auto &SSE : SSC) {
230 if (SSE.second != Id)
231 continue;
232 return SSE.first();
233 }
234 return std::nullopt;
235}
236
237/// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
238/// singleton OptBisect if not explicitly set.
239OptPassGate &LLVMContextImpl::getOptPassGate() const {
240 if (!OPG)
241 OPG = &getGlobalPassGate();
242 return *OPG;
243}
244
245void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
246 this->OPG = &OPG;
247}
248