10b57cec5SDimitry Andric //===- LLVMContextImpl.cpp - Implement LLVMContextImpl --------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file implements the opaque LLVMContextImpl.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "LLVMContextImpl.h"
141fd87a68SDimitry Andric #include "AttributeImpl.h"
155ffd83dbSDimitry Andric #include "llvm/ADT/SetVector.h"
161fd87a68SDimitry Andric #include "llvm/ADT/StringMapEntry.h"
171fd87a68SDimitry Andric #include "llvm/ADT/iterator.h"
181fd87a68SDimitry Andric #include "llvm/ADT/iterator_range.h"
191fd87a68SDimitry Andric #include "llvm/IR/DiagnosticHandler.h"
201fd87a68SDimitry Andric #include "llvm/IR/LLVMRemarkStreamer.h"
210b57cec5SDimitry Andric #include "llvm/IR/Module.h"
220b57cec5SDimitry Andric #include "llvm/IR/OptBisect.h"
230b57cec5SDimitry Andric #include "llvm/IR/Type.h"
241fd87a68SDimitry Andric #include "llvm/IR/Use.h"
251fd87a68SDimitry Andric #include "llvm/IR/User.h"
261fd87a68SDimitry Andric #include "llvm/Remarks/RemarkStreamer.h"
27fe6060f1SDimitry Andric #include "llvm/Support/CommandLine.h"
281fd87a68SDimitry Andric #include "llvm/Support/Compiler.h"
291fd87a68SDimitry Andric #include "llvm/Support/ErrorHandling.h"
301fd87a68SDimitry Andric #include "llvm/Support/TypeSize.h"
310b57cec5SDimitry Andric #include <cassert>
320b57cec5SDimitry Andric #include <utility>
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric using namespace llvm;
350b57cec5SDimitry Andric 
LLVMContextImpl(LLVMContext & C)360b57cec5SDimitry Andric LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
378bcb0991SDimitry Andric     : DiagHandler(std::make_unique<DiagnosticHandler>()),
38fe6060f1SDimitry Andric       VoidTy(C, Type::VoidTyID), LabelTy(C, Type::LabelTyID),
39fe6060f1SDimitry Andric       HalfTy(C, Type::HalfTyID), BFloatTy(C, Type::BFloatTyID),
40fe6060f1SDimitry Andric       FloatTy(C, Type::FloatTyID), DoubleTy(C, Type::DoubleTyID),
41fe6060f1SDimitry Andric       MetadataTy(C, Type::MetadataTyID), TokenTy(C, Type::TokenTyID),
42fe6060f1SDimitry Andric       X86_FP80Ty(C, Type::X86_FP80TyID), FP128Ty(C, Type::FP128TyID),
43fe6060f1SDimitry Andric       PPC_FP128Ty(C, Type::PPC_FP128TyID), X86_MMXTy(C, Type::X86_MMXTyID),
44fe6060f1SDimitry Andric       X86_AMXTy(C, Type::X86_AMXTyID), Int1Ty(C, 1), Int8Ty(C, 8),
4506c3fb27SDimitry Andric       Int16Ty(C, 16), Int32Ty(C, 32), Int64Ty(C, 64), Int128Ty(C, 128) {}
460b57cec5SDimitry Andric 
~LLVMContextImpl()470b57cec5SDimitry Andric LLVMContextImpl::~LLVMContextImpl() {
485f757f3fSDimitry Andric #ifndef NDEBUG
495f757f3fSDimitry Andric   // Check that any variable location records that fell off the end of a block
505f757f3fSDimitry Andric   // when it's terminator was removed were eventually replaced. This assertion
515f757f3fSDimitry Andric   // firing indicates that DPValues went missing during the lifetime of the
525f757f3fSDimitry Andric   // LLVMContext.
535f757f3fSDimitry Andric   assert(TrailingDPValues.empty() && "DPValue records in blocks not cleaned");
545f757f3fSDimitry Andric #endif
555f757f3fSDimitry Andric 
560b57cec5SDimitry Andric   // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
570b57cec5SDimitry Andric   // will call LLVMContextImpl::removeModule, thus invalidating iterators into
580b57cec5SDimitry Andric   // the container. Avoid iterators during this operation:
590b57cec5SDimitry Andric   while (!OwnedModules.empty())
600b57cec5SDimitry Andric     delete *OwnedModules.begin();
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric #ifndef NDEBUG
63e8d8bef9SDimitry Andric   // Check for metadata references from leaked Values.
64e8d8bef9SDimitry Andric   for (auto &Pair : ValueMetadata)
650b57cec5SDimitry Andric     Pair.first->dump();
66e8d8bef9SDimitry Andric   assert(ValueMetadata.empty() && "Values with metadata have been leaked");
670b57cec5SDimitry Andric #endif
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric   // Drop references for MDNodes.  Do this before Values get deleted to avoid
700b57cec5SDimitry Andric   // unnecessary RAUW when nodes are still unresolved.
715f757f3fSDimitry Andric   for (auto *I : DistinctMDNodes)
720b57cec5SDimitry Andric     I->dropAllReferences();
730b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
740b57cec5SDimitry Andric   for (auto *I : CLASS##s)                                                     \
750b57cec5SDimitry Andric     I->dropAllReferences();
760b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   // Also drop references that come from the Value bridges.
790b57cec5SDimitry Andric   for (auto &Pair : ValuesAsMetadata)
800b57cec5SDimitry Andric     Pair.second->dropUsers();
810b57cec5SDimitry Andric   for (auto &Pair : MetadataAsValues)
820b57cec5SDimitry Andric     Pair.second->dropUse();
835f757f3fSDimitry Andric   // Do not untrack ValueAsMetadata references for DIArgLists, as they have
845f757f3fSDimitry Andric   // already been more efficiently untracked above.
855f757f3fSDimitry Andric   for (DIArgList *AL : DIArgLists) {
865f757f3fSDimitry Andric     AL->dropAllReferences(/* Untrack */ false);
875f757f3fSDimitry Andric     delete AL;
885f757f3fSDimitry Andric   }
895f757f3fSDimitry Andric   DIArgLists.clear();
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   // Destroy MDNodes.
920b57cec5SDimitry Andric   for (MDNode *I : DistinctMDNodes)
930b57cec5SDimitry Andric     I->deleteAsSubclass();
940b57cec5SDimitry Andric #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
950b57cec5SDimitry Andric   for (CLASS * I : CLASS##s)                                                   \
960b57cec5SDimitry Andric     delete I;
970b57cec5SDimitry Andric #include "llvm/IR/Metadata.def"
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric   // Free the constants.
1000b57cec5SDimitry Andric   for (auto *I : ExprConstants)
1010b57cec5SDimitry Andric     I->dropAllReferences();
1020b57cec5SDimitry Andric   for (auto *I : ArrayConstants)
1030b57cec5SDimitry Andric     I->dropAllReferences();
1040b57cec5SDimitry Andric   for (auto *I : StructConstants)
1050b57cec5SDimitry Andric     I->dropAllReferences();
1060b57cec5SDimitry Andric   for (auto *I : VectorConstants)
1070b57cec5SDimitry Andric     I->dropAllReferences();
1080b57cec5SDimitry Andric   ExprConstants.freeConstants();
1090b57cec5SDimitry Andric   ArrayConstants.freeConstants();
1100b57cec5SDimitry Andric   StructConstants.freeConstants();
1110b57cec5SDimitry Andric   VectorConstants.freeConstants();
1120b57cec5SDimitry Andric   InlineAsms.freeConstants();
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   CAZConstants.clear();
1150b57cec5SDimitry Andric   CPNConstants.clear();
116bdd1243dSDimitry Andric   CTNConstants.clear();
1170b57cec5SDimitry Andric   UVConstants.clear();
118e8d8bef9SDimitry Andric   PVConstants.clear();
11906c3fb27SDimitry Andric   IntZeroConstants.clear();
12006c3fb27SDimitry Andric   IntOneConstants.clear();
1210b57cec5SDimitry Andric   IntConstants.clear();
1220b57cec5SDimitry Andric   FPConstants.clear();
1230b57cec5SDimitry Andric   CDSConstants.clear();
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   // Destroy attribute node lists.
1260b57cec5SDimitry Andric   for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
1270b57cec5SDimitry Andric          E = AttrsSetNodes.end(); I != E; ) {
1280b57cec5SDimitry Andric     FoldingSetIterator<AttributeSetNode> Elem = I++;
1290b57cec5SDimitry Andric     delete &*Elem;
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric   // Destroy MetadataAsValues.
1330b57cec5SDimitry Andric   {
1340b57cec5SDimitry Andric     SmallVector<MetadataAsValue *, 8> MDVs;
1350b57cec5SDimitry Andric     MDVs.reserve(MetadataAsValues.size());
1360b57cec5SDimitry Andric     for (auto &Pair : MetadataAsValues)
1370b57cec5SDimitry Andric       MDVs.push_back(Pair.second);
1380b57cec5SDimitry Andric     MetadataAsValues.clear();
1390b57cec5SDimitry Andric     for (auto *V : MDVs)
1400b57cec5SDimitry Andric       delete V;
1410b57cec5SDimitry Andric   }
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   // Destroy ValuesAsMetadata.
1440b57cec5SDimitry Andric   for (auto &Pair : ValuesAsMetadata)
1450b57cec5SDimitry Andric     delete Pair.second;
1460b57cec5SDimitry Andric }
1470b57cec5SDimitry Andric 
dropTriviallyDeadConstantArrays()1480b57cec5SDimitry Andric void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
149e8d8bef9SDimitry Andric   SmallSetVector<ConstantArray *, 4> WorkList;
150e8d8bef9SDimitry Andric 
151e8d8bef9SDimitry Andric   // When ArrayConstants are of substantial size and only a few in them are
152e8d8bef9SDimitry Andric   // dead, starting WorkList with all elements of ArrayConstants can be
153e8d8bef9SDimitry Andric   // wasteful. Instead, starting WorkList with only elements that have empty
154e8d8bef9SDimitry Andric   // uses.
155e8d8bef9SDimitry Andric   for (ConstantArray *C : ArrayConstants)
156e8d8bef9SDimitry Andric     if (C->use_empty())
157e8d8bef9SDimitry Andric       WorkList.insert(C);
1580b57cec5SDimitry Andric 
1595ffd83dbSDimitry Andric   while (!WorkList.empty()) {
1605ffd83dbSDimitry Andric     ConstantArray *C = WorkList.pop_back_val();
1610b57cec5SDimitry Andric     if (C->use_empty()) {
1625ffd83dbSDimitry Andric       for (const Use &Op : C->operands()) {
1635ffd83dbSDimitry Andric         if (auto *COp = dyn_cast<ConstantArray>(Op))
1645ffd83dbSDimitry Andric           WorkList.insert(COp);
1655ffd83dbSDimitry Andric       }
1660b57cec5SDimitry Andric       C->destroyConstant();
1670b57cec5SDimitry Andric     }
1680b57cec5SDimitry Andric   }
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
dropTriviallyDeadConstantArrays()1710b57cec5SDimitry Andric void Module::dropTriviallyDeadConstantArrays() {
1720b57cec5SDimitry Andric   Context.pImpl->dropTriviallyDeadConstantArrays();
1730b57cec5SDimitry Andric }
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric namespace llvm {
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric /// Make MDOperand transparent for hashing.
1780b57cec5SDimitry Andric ///
1790b57cec5SDimitry Andric /// This overload of an implementation detail of the hashing library makes
1800b57cec5SDimitry Andric /// MDOperand hash to the same value as a \a Metadata pointer.
1810b57cec5SDimitry Andric ///
1820b57cec5SDimitry Andric /// Note that overloading \a hash_value() as follows:
1830b57cec5SDimitry Andric ///
1840b57cec5SDimitry Andric /// \code
1850b57cec5SDimitry Andric ///     size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
1860b57cec5SDimitry Andric /// \endcode
1870b57cec5SDimitry Andric ///
1880b57cec5SDimitry Andric /// does not cause MDOperand to be transparent.  In particular, a bare pointer
1890b57cec5SDimitry Andric /// doesn't get hashed before it's combined, whereas \a MDOperand would.
get_hashable_data(const MDOperand & X)1900b57cec5SDimitry Andric static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric } // end namespace llvm
1930b57cec5SDimitry Andric 
calculateHash(MDNode * N,unsigned Offset)1940b57cec5SDimitry Andric unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
1950b57cec5SDimitry Andric   unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
1960b57cec5SDimitry Andric #ifndef NDEBUG
1970b57cec5SDimitry Andric   {
198e8d8bef9SDimitry Andric     SmallVector<Metadata *, 8> MDs(drop_begin(N->operands(), Offset));
1990b57cec5SDimitry Andric     unsigned RawHash = calculateHash(MDs);
2000b57cec5SDimitry Andric     assert(Hash == RawHash &&
2010b57cec5SDimitry Andric            "Expected hash of MDOperand to equal hash of Metadata*");
2020b57cec5SDimitry Andric   }
2030b57cec5SDimitry Andric #endif
2040b57cec5SDimitry Andric   return Hash;
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
calculateHash(ArrayRef<Metadata * > Ops)2070b57cec5SDimitry Andric unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
2080b57cec5SDimitry Andric   return hash_combine_range(Ops.begin(), Ops.end());
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
getOrInsertBundleTag(StringRef Tag)2110b57cec5SDimitry Andric StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
2120b57cec5SDimitry Andric   uint32_t NewIdx = BundleTagCache.size();
2130b57cec5SDimitry Andric   return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
getOperandBundleTags(SmallVectorImpl<StringRef> & Tags) const2160b57cec5SDimitry Andric void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
2170b57cec5SDimitry Andric   Tags.resize(BundleTagCache.size());
2180b57cec5SDimitry Andric   for (const auto &T : BundleTagCache)
2190b57cec5SDimitry Andric     Tags[T.second] = T.first();
2200b57cec5SDimitry Andric }
2210b57cec5SDimitry Andric 
getOperandBundleTagID(StringRef Tag) const2220b57cec5SDimitry Andric uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
2230b57cec5SDimitry Andric   auto I = BundleTagCache.find(Tag);
2240b57cec5SDimitry Andric   assert(I != BundleTagCache.end() && "Unknown tag!");
2250b57cec5SDimitry Andric   return I->second;
2260b57cec5SDimitry Andric }
2270b57cec5SDimitry Andric 
getOrInsertSyncScopeID(StringRef SSN)2280b57cec5SDimitry Andric SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
2290b57cec5SDimitry Andric   auto NewSSID = SSC.size();
2300b57cec5SDimitry Andric   assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
2310b57cec5SDimitry Andric          "Hit the maximum number of synchronization scopes allowed!");
2320b57cec5SDimitry Andric   return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
getSyncScopeNames(SmallVectorImpl<StringRef> & SSNs) const2350b57cec5SDimitry Andric void LLVMContextImpl::getSyncScopeNames(
2360b57cec5SDimitry Andric     SmallVectorImpl<StringRef> &SSNs) const {
2370b57cec5SDimitry Andric   SSNs.resize(SSC.size());
2380b57cec5SDimitry Andric   for (const auto &SSE : SSC)
2390b57cec5SDimitry Andric     SSNs[SSE.second] = SSE.first();
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
242e8d8bef9SDimitry Andric /// Gets the OptPassGate for this LLVMContextImpl, which defaults to the
243e8d8bef9SDimitry Andric /// singleton OptBisect if not explicitly set.
getOptPassGate() const2440b57cec5SDimitry Andric OptPassGate &LLVMContextImpl::getOptPassGate() const {
2450b57cec5SDimitry Andric   if (!OPG)
246bdd1243dSDimitry Andric     OPG = &getGlobalPassGate();
2470b57cec5SDimitry Andric   return *OPG;
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
setOptPassGate(OptPassGate & OPG)2500b57cec5SDimitry Andric void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
2510b57cec5SDimitry Andric   this->OPG = &OPG;
2520b57cec5SDimitry Andric }
253