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 for (auto *I : ConstantPtrAuths)
114 I->dropAllReferences();
115 ExprConstants.freeConstants();
116 ArrayConstants.freeConstants();
117 StructConstants.freeConstants();
118 VectorConstants.freeConstants();
119 ConstantPtrAuths.freeConstants();
120 InlineAsms.freeConstants();
121
122 CAZConstants.clear();
123 CPNConstants.clear();
124 CTNConstants.clear();
125 UVConstants.clear();
126 PVConstants.clear();
127 IntZeroConstants.clear();
128 IntOneConstants.clear();
129 IntConstants.clear();
130 IntSplatConstants.clear();
131 ByteZeroConstants.clear();
132 ByteOneConstants.clear();
133 ByteConstants.clear();
134 ByteSplatConstants.clear();
135 FPConstants.clear();
136 FPSplatConstants.clear();
137 CDSConstants.clear();
138 TheNoneToken.reset();
139
140 // Destroy attribute node lists.
141 for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
142 E = AttrsSetNodes.end(); I != E; ) {
143 FoldingSetIterator<AttributeSetNode> Elem = I++;
144 delete &*Elem;
145 }
146
147 // Destroy MetadataAsValues.
148 {
149 SmallVector<MetadataAsValue *, 8> MDVs;
150 MDVs.reserve(N: MetadataAsValues.size());
151 for (auto &Pair : MetadataAsValues)
152 MDVs.push_back(Elt: Pair.second);
153 MetadataAsValues.clear();
154 for (auto *V : MDVs)
155 delete V;
156 }
157
158 // Destroy ValuesAsMetadata.
159 for (auto &Pair : ValuesAsMetadata)
160 delete Pair.second;
161}
162
163namespace llvm {
164
165/// Make MDOperand transparent for hashing.
166///
167/// This overload of an implementation detail of the hashing library makes
168/// MDOperand hash to the same value as a \a Metadata pointer.
169///
170/// Note that overloading \a hash_value() as follows:
171///
172/// \code
173/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
174/// \endcode
175///
176/// does not cause MDOperand to be transparent. In particular, a bare pointer
177/// doesn't get hashed before it's combined, whereas \a MDOperand would.
178static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
179
180} // end namespace llvm
181
182unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
183 unsigned Hash = hash_combine_range(first: N->op_begin() + Offset, last: N->op_end());
184#ifndef NDEBUG
185 {
186 SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
187 unsigned RawHash = calculateHash(MDs);
188 assert(Hash == RawHash &&
189 "Expected hash of MDOperand to equal hash of Metadata*");
190 }
191#endif
192 return Hash;
193}
194
195unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
196 return hash_combine_range(R&: Ops);
197}
198
199StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
200 uint32_t NewIdx = BundleTagCache.size();
201 return &*(BundleTagCache.insert(KV: std::make_pair(x&: Tag, y&: NewIdx)).first);
202}
203
204void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
205 Tags.resize(N: BundleTagCache.size());
206 for (const auto &T : BundleTagCache)
207 Tags[T.second] = T.first();
208}
209
210uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
211 auto I = BundleTagCache.find(Key: Tag);
212 assert(I != BundleTagCache.end() && "Unknown tag!");
213 return I->second;
214}
215
216SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
217 auto NewSSID = SSC.size();
218 assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
219 "Hit the maximum number of synchronization scopes allowed!");
220 return SSC.insert(KV: std::make_pair(x&: SSN, y: SyncScope::ID(NewSSID))).first->second;
221}
222
223void LLVMContextImpl::getSyncScopeNames(
224 SmallVectorImpl<StringRef> &SSNs) const {
225 SSNs.resize(N: SSC.size());
226 for (const auto &SSE : SSC)
227 SSNs[SSE.second] = SSE.first();
228}
229
230std::optional<StringRef>
231LLVMContextImpl::getSyncScopeName(SyncScope::ID Id) const {
232 for (const auto &SSE : SSC) {
233 if (SSE.second != Id)
234 continue;
235 return SSE.first();
236 }
237 return std::nullopt;
238}
239
240/// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
241/// singleton OptBisect if not explicitly set.
242OptPassGate &LLVMContextImpl::getOptPassGate() const {
243 if (!OPG)
244 OPG = &getGlobalPassGate();
245 return *OPG;
246}
247
248void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
249 this->OPG = &OPG;
250}
251