xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/DirectX/DXILWriter/DXILValueEnumerator.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
181ad6265SDimitry Andric //===- ValueEnumerator.cpp - Number values and types for bitcode writer ---===//
281ad6265SDimitry Andric //
381ad6265SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
481ad6265SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
581ad6265SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
681ad6265SDimitry Andric //
781ad6265SDimitry Andric //===----------------------------------------------------------------------===//
881ad6265SDimitry Andric //
981ad6265SDimitry Andric // This file implements the ValueEnumerator class.
1081ad6265SDimitry Andric // Forked from lib/Bitcode/Writer
1181ad6265SDimitry Andric //
1281ad6265SDimitry Andric //===----------------------------------------------------------------------===//
1381ad6265SDimitry Andric 
1481ad6265SDimitry Andric #include "DXILValueEnumerator.h"
1581ad6265SDimitry Andric #include "llvm/ADT/SmallVector.h"
1681ad6265SDimitry Andric #include "llvm/Config/llvm-config.h"
1781ad6265SDimitry Andric #include "llvm/IR/Argument.h"
1881ad6265SDimitry Andric #include "llvm/IR/BasicBlock.h"
1981ad6265SDimitry Andric #include "llvm/IR/Constant.h"
2081ad6265SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
2181ad6265SDimitry Andric #include "llvm/IR/DerivedTypes.h"
2281ad6265SDimitry Andric #include "llvm/IR/Function.h"
2381ad6265SDimitry Andric #include "llvm/IR/GlobalAlias.h"
2481ad6265SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
2581ad6265SDimitry Andric #include "llvm/IR/GlobalObject.h"
2681ad6265SDimitry Andric #include "llvm/IR/GlobalValue.h"
2781ad6265SDimitry Andric #include "llvm/IR/GlobalVariable.h"
2881ad6265SDimitry Andric #include "llvm/IR/Instruction.h"
2981ad6265SDimitry Andric #include "llvm/IR/Instructions.h"
3081ad6265SDimitry Andric #include "llvm/IR/Metadata.h"
3181ad6265SDimitry Andric #include "llvm/IR/Module.h"
3281ad6265SDimitry Andric #include "llvm/IR/Operator.h"
3381ad6265SDimitry Andric #include "llvm/IR/Type.h"
34bdd1243dSDimitry Andric #include "llvm/IR/TypedPointerType.h"
3581ad6265SDimitry Andric #include "llvm/IR/Use.h"
3681ad6265SDimitry Andric #include "llvm/IR/User.h"
3781ad6265SDimitry Andric #include "llvm/IR/Value.h"
3881ad6265SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
3981ad6265SDimitry Andric #include "llvm/Support/Casting.h"
4081ad6265SDimitry Andric #include "llvm/Support/Compiler.h"
4181ad6265SDimitry Andric #include "llvm/Support/Debug.h"
4281ad6265SDimitry Andric #include "llvm/Support/MathExtras.h"
4381ad6265SDimitry Andric #include "llvm/Support/raw_ostream.h"
4481ad6265SDimitry Andric #include <algorithm>
4581ad6265SDimitry Andric #include <cstddef>
4681ad6265SDimitry Andric #include <iterator>
4781ad6265SDimitry Andric #include <tuple>
4881ad6265SDimitry Andric 
4981ad6265SDimitry Andric using namespace llvm;
5081ad6265SDimitry Andric using namespace llvm::dxil;
5181ad6265SDimitry Andric 
5281ad6265SDimitry Andric namespace {
5381ad6265SDimitry Andric 
5481ad6265SDimitry Andric struct OrderMap {
5581ad6265SDimitry Andric   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
5681ad6265SDimitry Andric   unsigned LastGlobalConstantID = 0;
5781ad6265SDimitry Andric   unsigned LastGlobalValueID = 0;
5881ad6265SDimitry Andric 
5981ad6265SDimitry Andric   OrderMap() = default;
6081ad6265SDimitry Andric 
6181ad6265SDimitry Andric   bool isGlobalConstant(unsigned ID) const {
6281ad6265SDimitry Andric     return ID <= LastGlobalConstantID;
6381ad6265SDimitry Andric   }
6481ad6265SDimitry Andric 
6581ad6265SDimitry Andric   bool isGlobalValue(unsigned ID) const {
6681ad6265SDimitry Andric     return ID <= LastGlobalValueID && !isGlobalConstant(ID);
6781ad6265SDimitry Andric   }
6881ad6265SDimitry Andric 
6981ad6265SDimitry Andric   unsigned size() const { return IDs.size(); }
7081ad6265SDimitry Andric   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
7181ad6265SDimitry Andric 
7281ad6265SDimitry Andric   std::pair<unsigned, bool> lookup(const Value *V) const {
7381ad6265SDimitry Andric     return IDs.lookup(V);
7481ad6265SDimitry Andric   }
7581ad6265SDimitry Andric 
7681ad6265SDimitry Andric   void index(const Value *V) {
7781ad6265SDimitry Andric     // Explicitly sequence get-size and insert-value operations to avoid UB.
7881ad6265SDimitry Andric     unsigned ID = IDs.size() + 1;
7981ad6265SDimitry Andric     IDs[V].first = ID;
8081ad6265SDimitry Andric   }
8181ad6265SDimitry Andric };
8281ad6265SDimitry Andric 
8381ad6265SDimitry Andric } // end anonymous namespace
8481ad6265SDimitry Andric 
8581ad6265SDimitry Andric static void orderValue(const Value *V, OrderMap &OM) {
8681ad6265SDimitry Andric   if (OM.lookup(V).first)
8781ad6265SDimitry Andric     return;
8881ad6265SDimitry Andric 
8981ad6265SDimitry Andric   if (const Constant *C = dyn_cast<Constant>(V)) {
9081ad6265SDimitry Andric     if (C->getNumOperands() && !isa<GlobalValue>(C)) {
9181ad6265SDimitry Andric       for (const Value *Op : C->operands())
9281ad6265SDimitry Andric         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
9381ad6265SDimitry Andric           orderValue(Op, OM);
9481ad6265SDimitry Andric       if (auto *CE = dyn_cast<ConstantExpr>(C))
9581ad6265SDimitry Andric         if (CE->getOpcode() == Instruction::ShuffleVector)
9681ad6265SDimitry Andric           orderValue(CE->getShuffleMaskForBitcode(), OM);
9781ad6265SDimitry Andric     }
9881ad6265SDimitry Andric   }
9981ad6265SDimitry Andric 
10081ad6265SDimitry Andric   // Note: we cannot cache this lookup above, since inserting into the map
10181ad6265SDimitry Andric   // changes the map's size, and thus affects the other IDs.
10281ad6265SDimitry Andric   OM.index(V);
10381ad6265SDimitry Andric }
10481ad6265SDimitry Andric 
10581ad6265SDimitry Andric static OrderMap orderModule(const Module &M) {
10681ad6265SDimitry Andric   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
10781ad6265SDimitry Andric   // and ValueEnumerator::incorporateFunction().
10881ad6265SDimitry Andric   OrderMap OM;
10981ad6265SDimitry Andric 
11081ad6265SDimitry Andric   // In the reader, initializers of GlobalValues are set *after* all the
11181ad6265SDimitry Andric   // globals have been read.  Rather than awkwardly modeling this behaviour
11281ad6265SDimitry Andric   // directly in predictValueUseListOrderImpl(), just assign IDs to
11381ad6265SDimitry Andric   // initializers of GlobalValues before GlobalValues themselves to model this
11481ad6265SDimitry Andric   // implicitly.
11581ad6265SDimitry Andric   for (const GlobalVariable &G : M.globals())
11681ad6265SDimitry Andric     if (G.hasInitializer())
11781ad6265SDimitry Andric       if (!isa<GlobalValue>(G.getInitializer()))
11881ad6265SDimitry Andric         orderValue(G.getInitializer(), OM);
11981ad6265SDimitry Andric   for (const GlobalAlias &A : M.aliases())
12081ad6265SDimitry Andric     if (!isa<GlobalValue>(A.getAliasee()))
12181ad6265SDimitry Andric       orderValue(A.getAliasee(), OM);
12281ad6265SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs())
12381ad6265SDimitry Andric     if (!isa<GlobalValue>(I.getResolver()))
12481ad6265SDimitry Andric       orderValue(I.getResolver(), OM);
12581ad6265SDimitry Andric   for (const Function &F : M) {
12681ad6265SDimitry Andric     for (const Use &U : F.operands())
12781ad6265SDimitry Andric       if (!isa<GlobalValue>(U.get()))
12881ad6265SDimitry Andric         orderValue(U.get(), OM);
12981ad6265SDimitry Andric   }
13081ad6265SDimitry Andric 
13181ad6265SDimitry Andric   // As constants used in metadata operands are emitted as module-level
13281ad6265SDimitry Andric   // constants, we must order them before other operands. Also, we must order
13381ad6265SDimitry Andric   // these before global values, as these will be read before setting the
13481ad6265SDimitry Andric   // global values' initializers. The latter matters for constants which have
13581ad6265SDimitry Andric   // uses towards other constants that are used as initializers.
13681ad6265SDimitry Andric   auto orderConstantValue = [&OM](const Value *V) {
13781ad6265SDimitry Andric     if ((isa<Constant>(V) && !isa<GlobalValue>(V)) || isa<InlineAsm>(V))
13881ad6265SDimitry Andric       orderValue(V, OM);
13981ad6265SDimitry Andric   };
14081ad6265SDimitry Andric   for (const Function &F : M) {
14181ad6265SDimitry Andric     if (F.isDeclaration())
14281ad6265SDimitry Andric       continue;
14381ad6265SDimitry Andric     for (const BasicBlock &BB : F)
14481ad6265SDimitry Andric       for (const Instruction &I : BB)
14581ad6265SDimitry Andric         for (const Value *V : I.operands()) {
14681ad6265SDimitry Andric           if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
14781ad6265SDimitry Andric             if (const auto *VAM =
14881ad6265SDimitry Andric                     dyn_cast<ValueAsMetadata>(MAV->getMetadata())) {
14981ad6265SDimitry Andric               orderConstantValue(VAM->getValue());
15081ad6265SDimitry Andric             } else if (const auto *AL =
15181ad6265SDimitry Andric                            dyn_cast<DIArgList>(MAV->getMetadata())) {
15281ad6265SDimitry Andric               for (const auto *VAM : AL->getArgs())
15381ad6265SDimitry Andric                 orderConstantValue(VAM->getValue());
15481ad6265SDimitry Andric             }
15581ad6265SDimitry Andric           }
15681ad6265SDimitry Andric         }
15781ad6265SDimitry Andric   }
15881ad6265SDimitry Andric   OM.LastGlobalConstantID = OM.size();
15981ad6265SDimitry Andric 
16081ad6265SDimitry Andric   // Initializers of GlobalValues are processed in
16181ad6265SDimitry Andric   // BitcodeReader::ResolveGlobalAndAliasInits().  Match the order there rather
16281ad6265SDimitry Andric   // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
16381ad6265SDimitry Andric   // by giving IDs in reverse order.
16481ad6265SDimitry Andric   //
16581ad6265SDimitry Andric   // Since GlobalValues never reference each other directly (just through
16681ad6265SDimitry Andric   // initializers), their relative IDs only matter for determining order of
16781ad6265SDimitry Andric   // uses in their initializers.
16881ad6265SDimitry Andric   for (const Function &F : M)
16981ad6265SDimitry Andric     orderValue(&F, OM);
17081ad6265SDimitry Andric   for (const GlobalAlias &A : M.aliases())
17181ad6265SDimitry Andric     orderValue(&A, OM);
17281ad6265SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs())
17381ad6265SDimitry Andric     orderValue(&I, OM);
17481ad6265SDimitry Andric   for (const GlobalVariable &G : M.globals())
17581ad6265SDimitry Andric     orderValue(&G, OM);
17681ad6265SDimitry Andric   OM.LastGlobalValueID = OM.size();
17781ad6265SDimitry Andric 
17881ad6265SDimitry Andric   for (const Function &F : M) {
17981ad6265SDimitry Andric     if (F.isDeclaration())
18081ad6265SDimitry Andric       continue;
18181ad6265SDimitry Andric     // Here we need to match the union of ValueEnumerator::incorporateFunction()
18281ad6265SDimitry Andric     // and WriteFunction().  Basic blocks are implicitly declared before
18381ad6265SDimitry Andric     // anything else (by declaring their size).
18481ad6265SDimitry Andric     for (const BasicBlock &BB : F)
18581ad6265SDimitry Andric       orderValue(&BB, OM);
18681ad6265SDimitry Andric     for (const Argument &A : F.args())
18781ad6265SDimitry Andric       orderValue(&A, OM);
18881ad6265SDimitry Andric     for (const BasicBlock &BB : F)
18981ad6265SDimitry Andric       for (const Instruction &I : BB) {
19081ad6265SDimitry Andric         for (const Value *Op : I.operands())
19181ad6265SDimitry Andric           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
19281ad6265SDimitry Andric               isa<InlineAsm>(*Op))
19381ad6265SDimitry Andric             orderValue(Op, OM);
19481ad6265SDimitry Andric         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
19581ad6265SDimitry Andric           orderValue(SVI->getShuffleMaskForBitcode(), OM);
19681ad6265SDimitry Andric       }
19781ad6265SDimitry Andric     for (const BasicBlock &BB : F)
19881ad6265SDimitry Andric       for (const Instruction &I : BB)
19981ad6265SDimitry Andric         orderValue(&I, OM);
20081ad6265SDimitry Andric   }
20181ad6265SDimitry Andric   return OM;
20281ad6265SDimitry Andric }
20381ad6265SDimitry Andric 
20481ad6265SDimitry Andric static void predictValueUseListOrderImpl(const Value *V, const Function *F,
20581ad6265SDimitry Andric                                          unsigned ID, const OrderMap &OM,
20681ad6265SDimitry Andric                                          UseListOrderStack &Stack) {
20781ad6265SDimitry Andric   // Predict use-list order for this one.
20881ad6265SDimitry Andric   using Entry = std::pair<const Use *, unsigned>;
20981ad6265SDimitry Andric   SmallVector<Entry, 64> List;
21081ad6265SDimitry Andric   for (const Use &U : V->uses())
21181ad6265SDimitry Andric     // Check if this user will be serialized.
21281ad6265SDimitry Andric     if (OM.lookup(U.getUser()).first)
21381ad6265SDimitry Andric       List.push_back(std::make_pair(&U, List.size()));
21481ad6265SDimitry Andric 
21581ad6265SDimitry Andric   if (List.size() < 2)
21681ad6265SDimitry Andric     // We may have lost some users.
21781ad6265SDimitry Andric     return;
21881ad6265SDimitry Andric 
21981ad6265SDimitry Andric   bool IsGlobalValue = OM.isGlobalValue(ID);
22081ad6265SDimitry Andric   llvm::sort(List, [&](const Entry &L, const Entry &R) {
22181ad6265SDimitry Andric     const Use *LU = L.first;
22281ad6265SDimitry Andric     const Use *RU = R.first;
22381ad6265SDimitry Andric     if (LU == RU)
22481ad6265SDimitry Andric       return false;
22581ad6265SDimitry Andric 
22681ad6265SDimitry Andric     auto LID = OM.lookup(LU->getUser()).first;
22781ad6265SDimitry Andric     auto RID = OM.lookup(RU->getUser()).first;
22881ad6265SDimitry Andric 
22981ad6265SDimitry Andric     // Global values are processed in reverse order.
23081ad6265SDimitry Andric     //
23181ad6265SDimitry Andric     // Moreover, initializers of GlobalValues are set *after* all the globals
23281ad6265SDimitry Andric     // have been read (despite having earlier IDs).  Rather than awkwardly
23381ad6265SDimitry Andric     // modeling this behaviour here, orderModule() has assigned IDs to
23481ad6265SDimitry Andric     // initializers of GlobalValues before GlobalValues themselves.
23581ad6265SDimitry Andric     if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID)) {
23681ad6265SDimitry Andric       if (LID == RID)
23781ad6265SDimitry Andric         return LU->getOperandNo() > RU->getOperandNo();
23881ad6265SDimitry Andric       return LID < RID;
23981ad6265SDimitry Andric     }
24081ad6265SDimitry Andric 
24181ad6265SDimitry Andric     // If ID is 4, then expect: 7 6 5 1 2 3.
24281ad6265SDimitry Andric     if (LID < RID) {
24381ad6265SDimitry Andric       if (RID <= ID)
24481ad6265SDimitry Andric         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
24581ad6265SDimitry Andric           return true;
24681ad6265SDimitry Andric       return false;
24781ad6265SDimitry Andric     }
24881ad6265SDimitry Andric     if (RID < LID) {
24981ad6265SDimitry Andric       if (LID <= ID)
25081ad6265SDimitry Andric         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
25181ad6265SDimitry Andric           return false;
25281ad6265SDimitry Andric       return true;
25381ad6265SDimitry Andric     }
25481ad6265SDimitry Andric 
25581ad6265SDimitry Andric     // LID and RID are equal, so we have different operands of the same user.
25681ad6265SDimitry Andric     // Assume operands are added in order for all instructions.
25781ad6265SDimitry Andric     if (LID <= ID)
25881ad6265SDimitry Andric       if (!IsGlobalValue) // GlobalValue uses don't get reversed.
25981ad6265SDimitry Andric         return LU->getOperandNo() < RU->getOperandNo();
26081ad6265SDimitry Andric     return LU->getOperandNo() > RU->getOperandNo();
26181ad6265SDimitry Andric   });
26281ad6265SDimitry Andric 
263972a253aSDimitry Andric   if (llvm::is_sorted(List, llvm::less_second()))
26481ad6265SDimitry Andric     // Order is already correct.
26581ad6265SDimitry Andric     return;
26681ad6265SDimitry Andric 
26781ad6265SDimitry Andric   // Store the shuffle.
26881ad6265SDimitry Andric   Stack.emplace_back(V, F, List.size());
26981ad6265SDimitry Andric   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
27081ad6265SDimitry Andric   for (size_t I = 0, E = List.size(); I != E; ++I)
27181ad6265SDimitry Andric     Stack.back().Shuffle[I] = List[I].second;
27281ad6265SDimitry Andric }
27381ad6265SDimitry Andric 
27481ad6265SDimitry Andric static void predictValueUseListOrder(const Value *V, const Function *F,
27581ad6265SDimitry Andric                                      OrderMap &OM, UseListOrderStack &Stack) {
27681ad6265SDimitry Andric   auto &IDPair = OM[V];
27781ad6265SDimitry Andric   assert(IDPair.first && "Unmapped value");
27881ad6265SDimitry Andric   if (IDPair.second)
27981ad6265SDimitry Andric     // Already predicted.
28081ad6265SDimitry Andric     return;
28181ad6265SDimitry Andric 
28281ad6265SDimitry Andric   // Do the actual prediction.
28381ad6265SDimitry Andric   IDPair.second = true;
28481ad6265SDimitry Andric   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
28581ad6265SDimitry Andric     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
28681ad6265SDimitry Andric 
28781ad6265SDimitry Andric   // Recursive descent into constants.
28881ad6265SDimitry Andric   if (const Constant *C = dyn_cast<Constant>(V)) {
28981ad6265SDimitry Andric     if (C->getNumOperands()) { // Visit GlobalValues.
29081ad6265SDimitry Andric       for (const Value *Op : C->operands())
29181ad6265SDimitry Andric         if (isa<Constant>(Op)) // Visit GlobalValues.
29281ad6265SDimitry Andric           predictValueUseListOrder(Op, F, OM, Stack);
29381ad6265SDimitry Andric       if (auto *CE = dyn_cast<ConstantExpr>(C))
29481ad6265SDimitry Andric         if (CE->getOpcode() == Instruction::ShuffleVector)
29581ad6265SDimitry Andric           predictValueUseListOrder(CE->getShuffleMaskForBitcode(), F, OM,
29681ad6265SDimitry Andric                                    Stack);
29781ad6265SDimitry Andric     }
29881ad6265SDimitry Andric   }
29981ad6265SDimitry Andric }
30081ad6265SDimitry Andric 
30181ad6265SDimitry Andric static UseListOrderStack predictUseListOrder(const Module &M) {
30281ad6265SDimitry Andric   OrderMap OM = orderModule(M);
30381ad6265SDimitry Andric 
30481ad6265SDimitry Andric   // Use-list orders need to be serialized after all the users have been added
30581ad6265SDimitry Andric   // to a value, or else the shuffles will be incomplete.  Store them per
30681ad6265SDimitry Andric   // function in a stack.
30781ad6265SDimitry Andric   //
30881ad6265SDimitry Andric   // Aside from function order, the order of values doesn't matter much here.
30981ad6265SDimitry Andric   UseListOrderStack Stack;
31081ad6265SDimitry Andric 
31181ad6265SDimitry Andric   // We want to visit the functions backward now so we can list function-local
31281ad6265SDimitry Andric   // constants in the last Function they're used in.  Module-level constants
31381ad6265SDimitry Andric   // have already been visited above.
31481ad6265SDimitry Andric   for (const Function &F : llvm::reverse(M)) {
31581ad6265SDimitry Andric     if (F.isDeclaration())
31681ad6265SDimitry Andric       continue;
31781ad6265SDimitry Andric     for (const BasicBlock &BB : F)
31881ad6265SDimitry Andric       predictValueUseListOrder(&BB, &F, OM, Stack);
31981ad6265SDimitry Andric     for (const Argument &A : F.args())
32081ad6265SDimitry Andric       predictValueUseListOrder(&A, &F, OM, Stack);
32181ad6265SDimitry Andric     for (const BasicBlock &BB : F)
32281ad6265SDimitry Andric       for (const Instruction &I : BB) {
32381ad6265SDimitry Andric         for (const Value *Op : I.operands())
32481ad6265SDimitry Andric           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
32581ad6265SDimitry Andric             predictValueUseListOrder(Op, &F, OM, Stack);
32681ad6265SDimitry Andric         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
32781ad6265SDimitry Andric           predictValueUseListOrder(SVI->getShuffleMaskForBitcode(), &F, OM,
32881ad6265SDimitry Andric                                    Stack);
32981ad6265SDimitry Andric       }
33081ad6265SDimitry Andric     for (const BasicBlock &BB : F)
33181ad6265SDimitry Andric       for (const Instruction &I : BB)
33281ad6265SDimitry Andric         predictValueUseListOrder(&I, &F, OM, Stack);
33381ad6265SDimitry Andric   }
33481ad6265SDimitry Andric 
33581ad6265SDimitry Andric   // Visit globals last, since the module-level use-list block will be seen
33681ad6265SDimitry Andric   // before the function bodies are processed.
33781ad6265SDimitry Andric   for (const GlobalVariable &G : M.globals())
33881ad6265SDimitry Andric     predictValueUseListOrder(&G, nullptr, OM, Stack);
33981ad6265SDimitry Andric   for (const Function &F : M)
34081ad6265SDimitry Andric     predictValueUseListOrder(&F, nullptr, OM, Stack);
34181ad6265SDimitry Andric   for (const GlobalAlias &A : M.aliases())
34281ad6265SDimitry Andric     predictValueUseListOrder(&A, nullptr, OM, Stack);
34381ad6265SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs())
34481ad6265SDimitry Andric     predictValueUseListOrder(&I, nullptr, OM, Stack);
34581ad6265SDimitry Andric   for (const GlobalVariable &G : M.globals())
34681ad6265SDimitry Andric     if (G.hasInitializer())
34781ad6265SDimitry Andric       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
34881ad6265SDimitry Andric   for (const GlobalAlias &A : M.aliases())
34981ad6265SDimitry Andric     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
35081ad6265SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs())
35181ad6265SDimitry Andric     predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
35281ad6265SDimitry Andric   for (const Function &F : M) {
35381ad6265SDimitry Andric     for (const Use &U : F.operands())
35481ad6265SDimitry Andric       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
35581ad6265SDimitry Andric   }
35681ad6265SDimitry Andric 
35781ad6265SDimitry Andric   return Stack;
35881ad6265SDimitry Andric }
35981ad6265SDimitry Andric 
36081ad6265SDimitry Andric ValueEnumerator::ValueEnumerator(const Module &M, Type *PrefixType) {
36181ad6265SDimitry Andric   EnumerateType(PrefixType);
36281ad6265SDimitry Andric 
36381ad6265SDimitry Andric   UseListOrders = predictUseListOrder(M);
36481ad6265SDimitry Andric 
36581ad6265SDimitry Andric   // Enumerate the global variables.
36681ad6265SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
36781ad6265SDimitry Andric     EnumerateValue(&GV);
36881ad6265SDimitry Andric     EnumerateType(GV.getValueType());
36981ad6265SDimitry Andric   }
37081ad6265SDimitry Andric 
37181ad6265SDimitry Andric   // Enumerate the functions.
37281ad6265SDimitry Andric   for (const Function &F : M) {
37381ad6265SDimitry Andric     EnumerateValue(&F);
37481ad6265SDimitry Andric     EnumerateType(F.getValueType());
37581ad6265SDimitry Andric     EnumerateType(
376bdd1243dSDimitry Andric         TypedPointerType::get(F.getFunctionType(), F.getAddressSpace()));
37781ad6265SDimitry Andric     EnumerateAttributes(F.getAttributes());
37881ad6265SDimitry Andric   }
37981ad6265SDimitry Andric 
38081ad6265SDimitry Andric   // Enumerate the aliases.
38181ad6265SDimitry Andric   for (const GlobalAlias &GA : M.aliases()) {
38281ad6265SDimitry Andric     EnumerateValue(&GA);
38381ad6265SDimitry Andric     EnumerateType(GA.getValueType());
38481ad6265SDimitry Andric   }
38581ad6265SDimitry Andric 
38681ad6265SDimitry Andric   // Enumerate the ifuncs.
38781ad6265SDimitry Andric   for (const GlobalIFunc &GIF : M.ifuncs()) {
38881ad6265SDimitry Andric     EnumerateValue(&GIF);
38981ad6265SDimitry Andric     EnumerateType(GIF.getValueType());
39081ad6265SDimitry Andric   }
39181ad6265SDimitry Andric 
39281ad6265SDimitry Andric   // Enumerate the global variable initializers and attributes.
39381ad6265SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
39481ad6265SDimitry Andric     if (GV.hasInitializer())
39581ad6265SDimitry Andric       EnumerateValue(GV.getInitializer());
39681ad6265SDimitry Andric     EnumerateType(
397bdd1243dSDimitry Andric         TypedPointerType::get(GV.getValueType(), GV.getAddressSpace()));
39881ad6265SDimitry Andric     if (GV.hasAttributes())
39981ad6265SDimitry Andric       EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
40081ad6265SDimitry Andric   }
40181ad6265SDimitry Andric 
40281ad6265SDimitry Andric   // Enumerate the aliasees.
40381ad6265SDimitry Andric   for (const GlobalAlias &GA : M.aliases())
40481ad6265SDimitry Andric     EnumerateValue(GA.getAliasee());
40581ad6265SDimitry Andric 
40681ad6265SDimitry Andric   // Enumerate the ifunc resolvers.
40781ad6265SDimitry Andric   for (const GlobalIFunc &GIF : M.ifuncs())
40881ad6265SDimitry Andric     EnumerateValue(GIF.getResolver());
40981ad6265SDimitry Andric 
41081ad6265SDimitry Andric   // Enumerate any optional Function data.
41181ad6265SDimitry Andric   for (const Function &F : M)
41281ad6265SDimitry Andric     for (const Use &U : F.operands())
41381ad6265SDimitry Andric       EnumerateValue(U.get());
41481ad6265SDimitry Andric 
41581ad6265SDimitry Andric   // Enumerate the metadata type.
41681ad6265SDimitry Andric   //
41781ad6265SDimitry Andric   // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
41881ad6265SDimitry Andric   // only encodes the metadata type when it's used as a value.
41981ad6265SDimitry Andric   EnumerateType(Type::getMetadataTy(M.getContext()));
42081ad6265SDimitry Andric 
42181ad6265SDimitry Andric   // Insert constants and metadata that are named at module level into the slot
42281ad6265SDimitry Andric   // pool so that the module symbol table can refer to them...
42381ad6265SDimitry Andric   EnumerateValueSymbolTable(M.getValueSymbolTable());
42481ad6265SDimitry Andric   EnumerateNamedMetadata(M);
42581ad6265SDimitry Andric 
42681ad6265SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
42781ad6265SDimitry Andric   for (const GlobalVariable &GV : M.globals()) {
42881ad6265SDimitry Andric     MDs.clear();
42981ad6265SDimitry Andric     GV.getAllMetadata(MDs);
43081ad6265SDimitry Andric     for (const auto &I : MDs)
43181ad6265SDimitry Andric       // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer
43281ad6265SDimitry Andric       // to write metadata to the global variable's own metadata block
43381ad6265SDimitry Andric       // (PR28134).
43481ad6265SDimitry Andric       EnumerateMetadata(nullptr, I.second);
43581ad6265SDimitry Andric   }
43681ad6265SDimitry Andric 
43781ad6265SDimitry Andric   // Enumerate types used by function bodies and argument lists.
43881ad6265SDimitry Andric   for (const Function &F : M) {
43981ad6265SDimitry Andric     for (const Argument &A : F.args())
44081ad6265SDimitry Andric       EnumerateType(A.getType());
44181ad6265SDimitry Andric 
44281ad6265SDimitry Andric     // Enumerate metadata attached to this function.
44381ad6265SDimitry Andric     MDs.clear();
44481ad6265SDimitry Andric     F.getAllMetadata(MDs);
44581ad6265SDimitry Andric     for (const auto &I : MDs)
44681ad6265SDimitry Andric       EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second);
44781ad6265SDimitry Andric 
44881ad6265SDimitry Andric     for (const BasicBlock &BB : F)
44981ad6265SDimitry Andric       for (const Instruction &I : BB) {
45081ad6265SDimitry Andric         for (const Use &Op : I.operands()) {
45181ad6265SDimitry Andric           auto *MD = dyn_cast<MetadataAsValue>(&Op);
45281ad6265SDimitry Andric           if (!MD) {
45381ad6265SDimitry Andric             EnumerateOperandType(Op);
45481ad6265SDimitry Andric             continue;
45581ad6265SDimitry Andric           }
45681ad6265SDimitry Andric 
45781ad6265SDimitry Andric           // Local metadata is enumerated during function-incorporation, but
45881ad6265SDimitry Andric           // any ConstantAsMetadata arguments in a DIArgList should be examined
45981ad6265SDimitry Andric           // now.
46081ad6265SDimitry Andric           if (isa<LocalAsMetadata>(MD->getMetadata()))
46181ad6265SDimitry Andric             continue;
46281ad6265SDimitry Andric           if (auto *AL = dyn_cast<DIArgList>(MD->getMetadata())) {
46381ad6265SDimitry Andric             for (auto *VAM : AL->getArgs())
46481ad6265SDimitry Andric               if (isa<ConstantAsMetadata>(VAM))
46581ad6265SDimitry Andric                 EnumerateMetadata(&F, VAM);
46681ad6265SDimitry Andric             continue;
46781ad6265SDimitry Andric           }
46881ad6265SDimitry Andric 
46981ad6265SDimitry Andric           EnumerateMetadata(&F, MD->getMetadata());
47081ad6265SDimitry Andric         }
47181ad6265SDimitry Andric         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
47281ad6265SDimitry Andric           EnumerateType(SVI->getShuffleMaskForBitcode()->getType());
47381ad6265SDimitry Andric         if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
47481ad6265SDimitry Andric           EnumerateType(GEP->getSourceElementType());
47581ad6265SDimitry Andric         if (auto *AI = dyn_cast<AllocaInst>(&I))
47681ad6265SDimitry Andric           EnumerateType(AI->getAllocatedType());
47781ad6265SDimitry Andric         EnumerateType(I.getType());
47881ad6265SDimitry Andric         if (const auto *Call = dyn_cast<CallBase>(&I)) {
47981ad6265SDimitry Andric           EnumerateAttributes(Call->getAttributes());
48081ad6265SDimitry Andric           EnumerateType(Call->getFunctionType());
48181ad6265SDimitry Andric         }
48281ad6265SDimitry Andric 
48381ad6265SDimitry Andric         // Enumerate metadata attached with this instruction.
48481ad6265SDimitry Andric         MDs.clear();
48581ad6265SDimitry Andric         I.getAllMetadataOtherThanDebugLoc(MDs);
48681ad6265SDimitry Andric         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
48781ad6265SDimitry Andric           EnumerateMetadata(&F, MDs[i].second);
48881ad6265SDimitry Andric 
48981ad6265SDimitry Andric         // Don't enumerate the location directly -- it has a special record
49081ad6265SDimitry Andric         // type -- but enumerate its operands.
49181ad6265SDimitry Andric         if (DILocation *L = I.getDebugLoc())
49281ad6265SDimitry Andric           for (const Metadata *Op : L->operands())
49381ad6265SDimitry Andric             EnumerateMetadata(&F, Op);
49481ad6265SDimitry Andric       }
49581ad6265SDimitry Andric   }
49681ad6265SDimitry Andric 
49781ad6265SDimitry Andric   // Organize metadata ordering.
49881ad6265SDimitry Andric   organizeMetadata();
49981ad6265SDimitry Andric }
50081ad6265SDimitry Andric 
50181ad6265SDimitry Andric unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
50281ad6265SDimitry Andric   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
50381ad6265SDimitry Andric   assert(I != InstructionMap.end() && "Instruction is not mapped!");
50481ad6265SDimitry Andric   return I->second;
50581ad6265SDimitry Andric }
50681ad6265SDimitry Andric 
50781ad6265SDimitry Andric unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
50881ad6265SDimitry Andric   unsigned ComdatID = Comdats.idFor(C);
50981ad6265SDimitry Andric   assert(ComdatID && "Comdat not found!");
51081ad6265SDimitry Andric   return ComdatID;
51181ad6265SDimitry Andric }
51281ad6265SDimitry Andric 
51381ad6265SDimitry Andric void ValueEnumerator::setInstructionID(const Instruction *I) {
51481ad6265SDimitry Andric   InstructionMap[I] = InstructionCount++;
51581ad6265SDimitry Andric }
51681ad6265SDimitry Andric 
51781ad6265SDimitry Andric unsigned ValueEnumerator::getValueID(const Value *V) const {
51881ad6265SDimitry Andric   if (auto *MD = dyn_cast<MetadataAsValue>(V))
51981ad6265SDimitry Andric     return getMetadataID(MD->getMetadata());
52081ad6265SDimitry Andric 
52181ad6265SDimitry Andric   ValueMapType::const_iterator I = ValueMap.find(V);
52281ad6265SDimitry Andric   assert(I != ValueMap.end() && "Value not in slotcalculator!");
52381ad6265SDimitry Andric   return I->second - 1;
52481ad6265SDimitry Andric }
52581ad6265SDimitry Andric 
52681ad6265SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
52781ad6265SDimitry Andric LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
52881ad6265SDimitry Andric   print(dbgs(), ValueMap, "Default");
52981ad6265SDimitry Andric   dbgs() << '\n';
53081ad6265SDimitry Andric   print(dbgs(), MetadataMap, "MetaData");
53181ad6265SDimitry Andric   dbgs() << '\n';
53281ad6265SDimitry Andric }
53381ad6265SDimitry Andric #endif
53481ad6265SDimitry Andric 
53581ad6265SDimitry Andric void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
53681ad6265SDimitry Andric                             const char *Name) const {
53781ad6265SDimitry Andric   OS << "Map Name: " << Name << "\n";
53881ad6265SDimitry Andric   OS << "Size: " << Map.size() << "\n";
53981ad6265SDimitry Andric   for (const auto &I : Map) {
54081ad6265SDimitry Andric     const Value *V = I.first;
54181ad6265SDimitry Andric     if (V->hasName())
54281ad6265SDimitry Andric       OS << "Value: " << V->getName();
54381ad6265SDimitry Andric     else
54481ad6265SDimitry Andric       OS << "Value: [null]\n";
54581ad6265SDimitry Andric     V->print(errs());
54681ad6265SDimitry Andric     errs() << '\n';
54781ad6265SDimitry Andric 
54881ad6265SDimitry Andric     OS << " Uses(" << V->getNumUses() << "):";
54981ad6265SDimitry Andric     for (const Use &U : V->uses()) {
55081ad6265SDimitry Andric       if (&U != &*V->use_begin())
55181ad6265SDimitry Andric         OS << ",";
55281ad6265SDimitry Andric       if (U->hasName())
55381ad6265SDimitry Andric         OS << " " << U->getName();
55481ad6265SDimitry Andric       else
55581ad6265SDimitry Andric         OS << " [null]";
55681ad6265SDimitry Andric     }
55781ad6265SDimitry Andric     OS << "\n\n";
55881ad6265SDimitry Andric   }
55981ad6265SDimitry Andric }
56081ad6265SDimitry Andric 
56181ad6265SDimitry Andric void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
56281ad6265SDimitry Andric                             const char *Name) const {
56381ad6265SDimitry Andric   OS << "Map Name: " << Name << "\n";
56481ad6265SDimitry Andric   OS << "Size: " << Map.size() << "\n";
56581ad6265SDimitry Andric   for (const auto &I : Map) {
56681ad6265SDimitry Andric     const Metadata *MD = I.first;
56781ad6265SDimitry Andric     OS << "Metadata: slot = " << I.second.ID << "\n";
56881ad6265SDimitry Andric     OS << "Metadata: function = " << I.second.F << "\n";
56981ad6265SDimitry Andric     MD->print(OS);
57081ad6265SDimitry Andric     OS << "\n";
57181ad6265SDimitry Andric   }
57281ad6265SDimitry Andric }
57381ad6265SDimitry Andric 
57481ad6265SDimitry Andric /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
57581ad6265SDimitry Andric /// table into the values table.
57681ad6265SDimitry Andric void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
57781ad6265SDimitry Andric   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
57881ad6265SDimitry Andric        VI != VE; ++VI)
57981ad6265SDimitry Andric     EnumerateValue(VI->getValue());
58081ad6265SDimitry Andric }
58181ad6265SDimitry Andric 
58281ad6265SDimitry Andric /// Insert all of the values referenced by named metadata in the specified
58381ad6265SDimitry Andric /// module.
58481ad6265SDimitry Andric void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
58581ad6265SDimitry Andric   for (const auto &I : M.named_metadata())
58681ad6265SDimitry Andric     EnumerateNamedMDNode(&I);
58781ad6265SDimitry Andric }
58881ad6265SDimitry Andric 
58981ad6265SDimitry Andric void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
59081ad6265SDimitry Andric   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
59181ad6265SDimitry Andric     EnumerateMetadata(nullptr, MD->getOperand(i));
59281ad6265SDimitry Andric }
59381ad6265SDimitry Andric 
59481ad6265SDimitry Andric unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const {
59581ad6265SDimitry Andric   return F ? getValueID(F) + 1 : 0;
59681ad6265SDimitry Andric }
59781ad6265SDimitry Andric 
59881ad6265SDimitry Andric void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) {
59981ad6265SDimitry Andric   EnumerateMetadata(getMetadataFunctionID(F), MD);
60081ad6265SDimitry Andric }
60181ad6265SDimitry Andric 
60281ad6265SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalMetadata(
60381ad6265SDimitry Andric     const Function &F, const LocalAsMetadata *Local) {
60481ad6265SDimitry Andric   EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
60581ad6265SDimitry Andric }
60681ad6265SDimitry Andric 
60781ad6265SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalListMetadata(
60881ad6265SDimitry Andric     const Function &F, const DIArgList *ArgList) {
60981ad6265SDimitry Andric   EnumerateFunctionLocalListMetadata(getMetadataFunctionID(&F), ArgList);
61081ad6265SDimitry Andric }
61181ad6265SDimitry Andric 
61281ad6265SDimitry Andric void ValueEnumerator::dropFunctionFromMetadata(
61381ad6265SDimitry Andric     MetadataMapType::value_type &FirstMD) {
61481ad6265SDimitry Andric   SmallVector<const MDNode *, 64> Worklist;
61581ad6265SDimitry Andric   auto push = [&Worklist](MetadataMapType::value_type &MD) {
61681ad6265SDimitry Andric     auto &Entry = MD.second;
61781ad6265SDimitry Andric 
61881ad6265SDimitry Andric     // Nothing to do if this metadata isn't tagged.
61981ad6265SDimitry Andric     if (!Entry.F)
62081ad6265SDimitry Andric       return;
62181ad6265SDimitry Andric 
62281ad6265SDimitry Andric     // Drop the function tag.
62381ad6265SDimitry Andric     Entry.F = 0;
62481ad6265SDimitry Andric 
62581ad6265SDimitry Andric     // If this is has an ID and is an MDNode, then its operands have entries as
62681ad6265SDimitry Andric     // well.  We need to drop the function from them too.
62781ad6265SDimitry Andric     if (Entry.ID)
62881ad6265SDimitry Andric       if (auto *N = dyn_cast<MDNode>(MD.first))
62981ad6265SDimitry Andric         Worklist.push_back(N);
63081ad6265SDimitry Andric   };
63181ad6265SDimitry Andric   push(FirstMD);
63281ad6265SDimitry Andric   while (!Worklist.empty())
63381ad6265SDimitry Andric     for (const Metadata *Op : Worklist.pop_back_val()->operands()) {
63481ad6265SDimitry Andric       if (!Op)
63581ad6265SDimitry Andric         continue;
63681ad6265SDimitry Andric       auto MD = MetadataMap.find(Op);
63781ad6265SDimitry Andric       if (MD != MetadataMap.end())
63881ad6265SDimitry Andric         push(*MD);
63981ad6265SDimitry Andric     }
64081ad6265SDimitry Andric }
64181ad6265SDimitry Andric 
64281ad6265SDimitry Andric void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) {
64381ad6265SDimitry Andric   // It's vital for reader efficiency that uniqued subgraphs are done in
64481ad6265SDimitry Andric   // post-order; it's expensive when their operands have forward references.
64581ad6265SDimitry Andric   // If a distinct node is referenced from a uniqued node, it'll be delayed
64681ad6265SDimitry Andric   // until the uniqued subgraph has been completely traversed.
64781ad6265SDimitry Andric   SmallVector<const MDNode *, 32> DelayedDistinctNodes;
64881ad6265SDimitry Andric 
64981ad6265SDimitry Andric   // Start by enumerating MD, and then work through its transitive operands in
65081ad6265SDimitry Andric   // post-order.  This requires a depth-first search.
65181ad6265SDimitry Andric   SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist;
65281ad6265SDimitry Andric   if (const MDNode *N = enumerateMetadataImpl(F, MD))
65381ad6265SDimitry Andric     Worklist.push_back(std::make_pair(N, N->op_begin()));
65481ad6265SDimitry Andric 
65581ad6265SDimitry Andric   while (!Worklist.empty()) {
65681ad6265SDimitry Andric     const MDNode *N = Worklist.back().first;
65781ad6265SDimitry Andric 
65881ad6265SDimitry Andric     // Enumerate operands until we hit a new node.  We need to traverse these
65981ad6265SDimitry Andric     // nodes' operands before visiting the rest of N's operands.
66081ad6265SDimitry Andric     MDNode::op_iterator I = std::find_if(
66181ad6265SDimitry Andric         Worklist.back().second, N->op_end(),
66281ad6265SDimitry Andric         [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
66381ad6265SDimitry Andric     if (I != N->op_end()) {
66481ad6265SDimitry Andric       auto *Op = cast<MDNode>(*I);
66581ad6265SDimitry Andric       Worklist.back().second = ++I;
66681ad6265SDimitry Andric 
66781ad6265SDimitry Andric       // Delay traversing Op if it's a distinct node and N is uniqued.
66881ad6265SDimitry Andric       if (Op->isDistinct() && !N->isDistinct())
66981ad6265SDimitry Andric         DelayedDistinctNodes.push_back(Op);
67081ad6265SDimitry Andric       else
67181ad6265SDimitry Andric         Worklist.push_back(std::make_pair(Op, Op->op_begin()));
67281ad6265SDimitry Andric       continue;
67381ad6265SDimitry Andric     }
67481ad6265SDimitry Andric 
67581ad6265SDimitry Andric     // All the operands have been visited.  Now assign an ID.
67681ad6265SDimitry Andric     Worklist.pop_back();
67781ad6265SDimitry Andric     MDs.push_back(N);
67881ad6265SDimitry Andric     MetadataMap[N].ID = MDs.size();
67981ad6265SDimitry Andric 
68081ad6265SDimitry Andric     // Flush out any delayed distinct nodes; these are all the distinct nodes
68181ad6265SDimitry Andric     // that are leaves in last uniqued subgraph.
68281ad6265SDimitry Andric     if (Worklist.empty() || Worklist.back().first->isDistinct()) {
68381ad6265SDimitry Andric       for (const MDNode *N : DelayedDistinctNodes)
68481ad6265SDimitry Andric         Worklist.push_back(std::make_pair(N, N->op_begin()));
68581ad6265SDimitry Andric       DelayedDistinctNodes.clear();
68681ad6265SDimitry Andric     }
68781ad6265SDimitry Andric   }
68881ad6265SDimitry Andric }
68981ad6265SDimitry Andric 
69081ad6265SDimitry Andric const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F,
69181ad6265SDimitry Andric                                                      const Metadata *MD) {
69281ad6265SDimitry Andric   if (!MD)
69381ad6265SDimitry Andric     return nullptr;
69481ad6265SDimitry Andric 
69581ad6265SDimitry Andric   assert(
69681ad6265SDimitry Andric       (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
69781ad6265SDimitry Andric       "Invalid metadata kind");
69881ad6265SDimitry Andric 
69981ad6265SDimitry Andric   auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F)));
70081ad6265SDimitry Andric   MDIndex &Entry = Insertion.first->second;
70181ad6265SDimitry Andric   if (!Insertion.second) {
70281ad6265SDimitry Andric     // Already mapped.  If F doesn't match the function tag, drop it.
70381ad6265SDimitry Andric     if (Entry.hasDifferentFunction(F))
70481ad6265SDimitry Andric       dropFunctionFromMetadata(*Insertion.first);
70581ad6265SDimitry Andric     return nullptr;
70681ad6265SDimitry Andric   }
70781ad6265SDimitry Andric 
70881ad6265SDimitry Andric   // Don't assign IDs to metadata nodes.
70981ad6265SDimitry Andric   if (auto *N = dyn_cast<MDNode>(MD))
71081ad6265SDimitry Andric     return N;
71181ad6265SDimitry Andric 
71281ad6265SDimitry Andric   // Save the metadata.
71381ad6265SDimitry Andric   MDs.push_back(MD);
71481ad6265SDimitry Andric   Entry.ID = MDs.size();
71581ad6265SDimitry Andric 
71681ad6265SDimitry Andric   // Enumerate the constant, if any.
71781ad6265SDimitry Andric   if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
71881ad6265SDimitry Andric     EnumerateValue(C->getValue());
71981ad6265SDimitry Andric 
72081ad6265SDimitry Andric   return nullptr;
72181ad6265SDimitry Andric }
72281ad6265SDimitry Andric 
72381ad6265SDimitry Andric /// EnumerateFunctionLocalMetadata - Incorporate function-local metadata
72481ad6265SDimitry Andric /// information reachable from the metadata.
72581ad6265SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalMetadata(
72681ad6265SDimitry Andric     unsigned F, const LocalAsMetadata *Local) {
72781ad6265SDimitry Andric   assert(F && "Expected a function");
72881ad6265SDimitry Andric 
72981ad6265SDimitry Andric   // Check to see if it's already in!
73081ad6265SDimitry Andric   MDIndex &Index = MetadataMap[Local];
73181ad6265SDimitry Andric   if (Index.ID) {
73281ad6265SDimitry Andric     assert(Index.F == F && "Expected the same function");
73381ad6265SDimitry Andric     return;
73481ad6265SDimitry Andric   }
73581ad6265SDimitry Andric 
73681ad6265SDimitry Andric   MDs.push_back(Local);
73781ad6265SDimitry Andric   Index.F = F;
73881ad6265SDimitry Andric   Index.ID = MDs.size();
73981ad6265SDimitry Andric 
74081ad6265SDimitry Andric   EnumerateValue(Local->getValue());
74181ad6265SDimitry Andric }
74281ad6265SDimitry Andric 
74381ad6265SDimitry Andric /// EnumerateFunctionLocalListMetadata - Incorporate function-local metadata
74481ad6265SDimitry Andric /// information reachable from the metadata.
74581ad6265SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalListMetadata(
74681ad6265SDimitry Andric     unsigned F, const DIArgList *ArgList) {
74781ad6265SDimitry Andric   assert(F && "Expected a function");
74881ad6265SDimitry Andric 
74981ad6265SDimitry Andric   // Check to see if it's already in!
75081ad6265SDimitry Andric   MDIndex &Index = MetadataMap[ArgList];
75181ad6265SDimitry Andric   if (Index.ID) {
75281ad6265SDimitry Andric     assert(Index.F == F && "Expected the same function");
75381ad6265SDimitry Andric     return;
75481ad6265SDimitry Andric   }
75581ad6265SDimitry Andric 
75681ad6265SDimitry Andric   for (ValueAsMetadata *VAM : ArgList->getArgs()) {
75781ad6265SDimitry Andric     if (isa<LocalAsMetadata>(VAM)) {
75881ad6265SDimitry Andric       assert(MetadataMap.count(VAM) &&
75981ad6265SDimitry Andric              "LocalAsMetadata should be enumerated before DIArgList");
76081ad6265SDimitry Andric       assert(MetadataMap[VAM].F == F &&
76181ad6265SDimitry Andric              "Expected LocalAsMetadata in the same function");
76281ad6265SDimitry Andric     } else {
76381ad6265SDimitry Andric       assert(isa<ConstantAsMetadata>(VAM) &&
76481ad6265SDimitry Andric              "Expected LocalAsMetadata or ConstantAsMetadata");
76581ad6265SDimitry Andric       assert(ValueMap.count(VAM->getValue()) &&
76681ad6265SDimitry Andric              "Constant should be enumerated beforeDIArgList");
76781ad6265SDimitry Andric       EnumerateMetadata(F, VAM);
76881ad6265SDimitry Andric     }
76981ad6265SDimitry Andric   }
77081ad6265SDimitry Andric 
77181ad6265SDimitry Andric   MDs.push_back(ArgList);
77281ad6265SDimitry Andric   Index.F = F;
77381ad6265SDimitry Andric   Index.ID = MDs.size();
77481ad6265SDimitry Andric }
77581ad6265SDimitry Andric 
77681ad6265SDimitry Andric static unsigned getMetadataTypeOrder(const Metadata *MD) {
77781ad6265SDimitry Andric   // Strings are emitted in bulk and must come first.
77881ad6265SDimitry Andric   if (isa<MDString>(MD))
77981ad6265SDimitry Andric     return 0;
78081ad6265SDimitry Andric 
78181ad6265SDimitry Andric   // ConstantAsMetadata doesn't reference anything.  We may as well shuffle it
78281ad6265SDimitry Andric   // to the front since we can detect it.
78381ad6265SDimitry Andric   auto *N = dyn_cast<MDNode>(MD);
78481ad6265SDimitry Andric   if (!N)
78581ad6265SDimitry Andric     return 1;
78681ad6265SDimitry Andric 
78781ad6265SDimitry Andric   // The reader is fast forward references for distinct node operands, but slow
78881ad6265SDimitry Andric   // when uniqued operands are unresolved.
78981ad6265SDimitry Andric   return N->isDistinct() ? 2 : 3;
79081ad6265SDimitry Andric }
79181ad6265SDimitry Andric 
79281ad6265SDimitry Andric void ValueEnumerator::organizeMetadata() {
79381ad6265SDimitry Andric   assert(MetadataMap.size() == MDs.size() &&
79481ad6265SDimitry Andric          "Metadata map and vector out of sync");
79581ad6265SDimitry Andric 
79681ad6265SDimitry Andric   if (MDs.empty())
79781ad6265SDimitry Andric     return;
79881ad6265SDimitry Andric 
79981ad6265SDimitry Andric   // Copy out the index information from MetadataMap in order to choose a new
80081ad6265SDimitry Andric   // order.
80181ad6265SDimitry Andric   SmallVector<MDIndex, 64> Order;
80281ad6265SDimitry Andric   Order.reserve(MetadataMap.size());
80381ad6265SDimitry Andric   for (const Metadata *MD : MDs)
80481ad6265SDimitry Andric     Order.push_back(MetadataMap.lookup(MD));
80581ad6265SDimitry Andric 
80681ad6265SDimitry Andric   // Partition:
80781ad6265SDimitry Andric   //   - by function, then
80881ad6265SDimitry Andric   //   - by isa<MDString>
80981ad6265SDimitry Andric   // and then sort by the original/current ID.  Since the IDs are guaranteed to
810fcaf7f86SDimitry Andric   // be unique, the result of llvm::sort will be deterministic.  There's no need
81181ad6265SDimitry Andric   // for std::stable_sort.
81281ad6265SDimitry Andric   llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
81381ad6265SDimitry Andric     return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <
81481ad6265SDimitry Andric            std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID);
81581ad6265SDimitry Andric   });
81681ad6265SDimitry Andric 
81781ad6265SDimitry Andric   // Rebuild MDs, index the metadata ranges for each function in FunctionMDs,
81881ad6265SDimitry Andric   // and fix up MetadataMap.
81981ad6265SDimitry Andric   std::vector<const Metadata *> OldMDs;
82081ad6265SDimitry Andric   MDs.swap(OldMDs);
82181ad6265SDimitry Andric   MDs.reserve(OldMDs.size());
82281ad6265SDimitry Andric   for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) {
82381ad6265SDimitry Andric     auto *MD = Order[I].get(OldMDs);
82481ad6265SDimitry Andric     MDs.push_back(MD);
82581ad6265SDimitry Andric     MetadataMap[MD].ID = I + 1;
82681ad6265SDimitry Andric     if (isa<MDString>(MD))
82781ad6265SDimitry Andric       ++NumMDStrings;
82881ad6265SDimitry Andric   }
82981ad6265SDimitry Andric 
83081ad6265SDimitry Andric   // Return early if there's nothing for the functions.
83181ad6265SDimitry Andric   if (MDs.size() == Order.size())
83281ad6265SDimitry Andric     return;
83381ad6265SDimitry Andric 
83481ad6265SDimitry Andric   // Build the function metadata ranges.
83581ad6265SDimitry Andric   MDRange R;
83681ad6265SDimitry Andric   FunctionMDs.reserve(OldMDs.size());
83781ad6265SDimitry Andric   unsigned PrevF = 0;
83881ad6265SDimitry Andric   for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E;
83981ad6265SDimitry Andric        ++I) {
84081ad6265SDimitry Andric     unsigned F = Order[I].F;
84181ad6265SDimitry Andric     if (!PrevF) {
84281ad6265SDimitry Andric       PrevF = F;
84381ad6265SDimitry Andric     } else if (PrevF != F) {
84481ad6265SDimitry Andric       R.Last = FunctionMDs.size();
84581ad6265SDimitry Andric       std::swap(R, FunctionMDInfo[PrevF]);
84681ad6265SDimitry Andric       R.First = FunctionMDs.size();
84781ad6265SDimitry Andric 
84881ad6265SDimitry Andric       ID = MDs.size();
84981ad6265SDimitry Andric       PrevF = F;
85081ad6265SDimitry Andric     }
85181ad6265SDimitry Andric 
85281ad6265SDimitry Andric     auto *MD = Order[I].get(OldMDs);
85381ad6265SDimitry Andric     FunctionMDs.push_back(MD);
85481ad6265SDimitry Andric     MetadataMap[MD].ID = ++ID;
85581ad6265SDimitry Andric     if (isa<MDString>(MD))
85681ad6265SDimitry Andric       ++R.NumStrings;
85781ad6265SDimitry Andric   }
85881ad6265SDimitry Andric   R.Last = FunctionMDs.size();
85981ad6265SDimitry Andric   FunctionMDInfo[PrevF] = R;
86081ad6265SDimitry Andric }
86181ad6265SDimitry Andric 
86281ad6265SDimitry Andric void ValueEnumerator::incorporateFunctionMetadata(const Function &F) {
86381ad6265SDimitry Andric   NumModuleMDs = MDs.size();
86481ad6265SDimitry Andric 
86581ad6265SDimitry Andric   auto R = FunctionMDInfo.lookup(getValueID(&F) + 1);
86681ad6265SDimitry Andric   NumMDStrings = R.NumStrings;
86781ad6265SDimitry Andric   MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
86881ad6265SDimitry Andric              FunctionMDs.begin() + R.Last);
86981ad6265SDimitry Andric }
87081ad6265SDimitry Andric 
87181ad6265SDimitry Andric void ValueEnumerator::EnumerateValue(const Value *V) {
87281ad6265SDimitry Andric   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
87381ad6265SDimitry Andric   assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
87481ad6265SDimitry Andric 
87581ad6265SDimitry Andric   // Check to see if it's already in!
87681ad6265SDimitry Andric   unsigned &ValueID = ValueMap[V];
87781ad6265SDimitry Andric   if (ValueID) {
87881ad6265SDimitry Andric     // Increment use count.
87981ad6265SDimitry Andric     Values[ValueID - 1].second++;
88081ad6265SDimitry Andric     return;
88181ad6265SDimitry Andric   }
88281ad6265SDimitry Andric 
88381ad6265SDimitry Andric   if (auto *GO = dyn_cast<GlobalObject>(V))
88481ad6265SDimitry Andric     if (const Comdat *C = GO->getComdat())
88581ad6265SDimitry Andric       Comdats.insert(C);
88681ad6265SDimitry Andric 
88781ad6265SDimitry Andric   // Enumerate the type of this value.
88881ad6265SDimitry Andric   EnumerateType(V->getType());
88981ad6265SDimitry Andric 
89081ad6265SDimitry Andric   if (const Constant *C = dyn_cast<Constant>(V)) {
89181ad6265SDimitry Andric     if (isa<GlobalValue>(C)) {
89281ad6265SDimitry Andric       // Initializers for globals are handled explicitly elsewhere.
89381ad6265SDimitry Andric     } else if (C->getNumOperands()) {
89481ad6265SDimitry Andric       // If a constant has operands, enumerate them.  This makes sure that if a
89581ad6265SDimitry Andric       // constant has uses (for example an array of const ints), that they are
89681ad6265SDimitry Andric       // inserted also.
89781ad6265SDimitry Andric 
89881ad6265SDimitry Andric       // We prefer to enumerate them with values before we enumerate the user
89981ad6265SDimitry Andric       // itself.  This makes it more likely that we can avoid forward references
90081ad6265SDimitry Andric       // in the reader.  We know that there can be no cycles in the constants
90181ad6265SDimitry Andric       // graph that don't go through a global variable.
90281ad6265SDimitry Andric       for (User::const_op_iterator I = C->op_begin(), E = C->op_end(); I != E;
90381ad6265SDimitry Andric            ++I)
90481ad6265SDimitry Andric         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
90581ad6265SDimitry Andric           EnumerateValue(*I);
90681ad6265SDimitry Andric       if (auto *CE = dyn_cast<ConstantExpr>(C)) {
90781ad6265SDimitry Andric         if (CE->getOpcode() == Instruction::ShuffleVector)
90881ad6265SDimitry Andric           EnumerateValue(CE->getShuffleMaskForBitcode());
90981ad6265SDimitry Andric         if (auto *GEP = dyn_cast<GEPOperator>(CE))
91081ad6265SDimitry Andric           EnumerateType(GEP->getSourceElementType());
91181ad6265SDimitry Andric       }
91281ad6265SDimitry Andric 
91381ad6265SDimitry Andric       // Finally, add the value.  Doing this could make the ValueID reference be
91481ad6265SDimitry Andric       // dangling, don't reuse it.
91581ad6265SDimitry Andric       Values.push_back(std::make_pair(V, 1U));
91681ad6265SDimitry Andric       ValueMap[V] = Values.size();
91781ad6265SDimitry Andric       return;
91881ad6265SDimitry Andric     }
91981ad6265SDimitry Andric   }
92081ad6265SDimitry Andric 
92181ad6265SDimitry Andric   // Add the value.
92281ad6265SDimitry Andric   Values.push_back(std::make_pair(V, 1U));
92381ad6265SDimitry Andric   ValueID = Values.size();
92481ad6265SDimitry Andric }
92581ad6265SDimitry Andric 
92681ad6265SDimitry Andric void ValueEnumerator::EnumerateType(Type *Ty) {
92781ad6265SDimitry Andric   unsigned *TypeID = &TypeMap[Ty];
92881ad6265SDimitry Andric 
92981ad6265SDimitry Andric   // We've already seen this type.
93081ad6265SDimitry Andric   if (*TypeID)
93181ad6265SDimitry Andric     return;
93281ad6265SDimitry Andric 
93381ad6265SDimitry Andric   // If it is a non-anonymous struct, mark the type as being visited so that we
93481ad6265SDimitry Andric   // don't recursively visit it.  This is safe because we allow forward
93581ad6265SDimitry Andric   // references of these in the bitcode reader.
93681ad6265SDimitry Andric   if (StructType *STy = dyn_cast<StructType>(Ty))
93781ad6265SDimitry Andric     if (!STy->isLiteral())
93881ad6265SDimitry Andric       *TypeID = ~0U;
93981ad6265SDimitry Andric 
94081ad6265SDimitry Andric   // Enumerate all of the subtypes before we enumerate this type.  This ensures
94181ad6265SDimitry Andric   // that the type will be enumerated in an order that can be directly built.
94281ad6265SDimitry Andric   for (Type *SubTy : Ty->subtypes())
94381ad6265SDimitry Andric     EnumerateType(SubTy);
94481ad6265SDimitry Andric 
94581ad6265SDimitry Andric   // Refresh the TypeID pointer in case the table rehashed.
94681ad6265SDimitry Andric   TypeID = &TypeMap[Ty];
94781ad6265SDimitry Andric 
94881ad6265SDimitry Andric   // Check to see if we got the pointer another way.  This can happen when
94981ad6265SDimitry Andric   // enumerating recursive types that hit the base case deeper than they start.
95081ad6265SDimitry Andric   //
95181ad6265SDimitry Andric   // If this is actually a struct that we are treating as forward ref'able,
95281ad6265SDimitry Andric   // then emit the definition now that all of its contents are available.
95381ad6265SDimitry Andric   if (*TypeID && *TypeID != ~0U)
95481ad6265SDimitry Andric     return;
95581ad6265SDimitry Andric 
95681ad6265SDimitry Andric   // Add this type now that its contents are all happily enumerated.
95781ad6265SDimitry Andric   Types.push_back(Ty);
95881ad6265SDimitry Andric 
95981ad6265SDimitry Andric   *TypeID = Types.size();
96081ad6265SDimitry Andric }
96181ad6265SDimitry Andric 
96281ad6265SDimitry Andric // Enumerate the types for the specified value.  If the value is a constant,
96381ad6265SDimitry Andric // walk through it, enumerating the types of the constant.
96481ad6265SDimitry Andric void ValueEnumerator::EnumerateOperandType(const Value *V) {
96581ad6265SDimitry Andric   EnumerateType(V->getType());
96681ad6265SDimitry Andric 
96781ad6265SDimitry Andric   assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
96881ad6265SDimitry Andric 
96981ad6265SDimitry Andric   const Constant *C = dyn_cast<Constant>(V);
97081ad6265SDimitry Andric   if (!C)
97181ad6265SDimitry Andric     return;
97281ad6265SDimitry Andric 
97381ad6265SDimitry Andric   // If this constant is already enumerated, ignore it, we know its type must
97481ad6265SDimitry Andric   // be enumerated.
97581ad6265SDimitry Andric   if (ValueMap.count(C))
97681ad6265SDimitry Andric     return;
97781ad6265SDimitry Andric 
97881ad6265SDimitry Andric   // This constant may have operands, make sure to enumerate the types in
97981ad6265SDimitry Andric   // them.
98081ad6265SDimitry Andric   for (const Value *Op : C->operands()) {
98181ad6265SDimitry Andric     // Don't enumerate basic blocks here, this happens as operands to
98281ad6265SDimitry Andric     // blockaddress.
98381ad6265SDimitry Andric     if (isa<BasicBlock>(Op))
98481ad6265SDimitry Andric       continue;
98581ad6265SDimitry Andric 
98681ad6265SDimitry Andric     EnumerateOperandType(Op);
98781ad6265SDimitry Andric   }
98881ad6265SDimitry Andric   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
98981ad6265SDimitry Andric     if (CE->getOpcode() == Instruction::ShuffleVector)
99081ad6265SDimitry Andric       EnumerateOperandType(CE->getShuffleMaskForBitcode());
99181ad6265SDimitry Andric     if (CE->getOpcode() == Instruction::GetElementPtr)
99281ad6265SDimitry Andric       EnumerateType(cast<GEPOperator>(CE)->getSourceElementType());
99381ad6265SDimitry Andric   }
99481ad6265SDimitry Andric }
99581ad6265SDimitry Andric 
99681ad6265SDimitry Andric void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
99781ad6265SDimitry Andric   if (PAL.isEmpty())
99881ad6265SDimitry Andric     return; // null is always 0.
99981ad6265SDimitry Andric 
100081ad6265SDimitry Andric   // Do a lookup.
100181ad6265SDimitry Andric   unsigned &Entry = AttributeListMap[PAL];
100281ad6265SDimitry Andric   if (Entry == 0) {
100381ad6265SDimitry Andric     // Never saw this before, add it.
100481ad6265SDimitry Andric     AttributeLists.push_back(PAL);
100581ad6265SDimitry Andric     Entry = AttributeLists.size();
100681ad6265SDimitry Andric   }
100781ad6265SDimitry Andric 
100881ad6265SDimitry Andric   // Do lookups for all attribute groups.
100981ad6265SDimitry Andric   for (unsigned i : PAL.indexes()) {
101081ad6265SDimitry Andric     AttributeSet AS = PAL.getAttributes(i);
101181ad6265SDimitry Andric     if (!AS.hasAttributes())
101281ad6265SDimitry Andric       continue;
101381ad6265SDimitry Andric     IndexAndAttrSet Pair = {i, AS};
101481ad6265SDimitry Andric     unsigned &Entry = AttributeGroupMap[Pair];
101581ad6265SDimitry Andric     if (Entry == 0) {
101681ad6265SDimitry Andric       AttributeGroups.push_back(Pair);
101781ad6265SDimitry Andric       Entry = AttributeGroups.size();
101881ad6265SDimitry Andric 
101981ad6265SDimitry Andric       for (Attribute Attr : AS) {
102081ad6265SDimitry Andric         if (Attr.isTypeAttribute())
102181ad6265SDimitry Andric           EnumerateType(Attr.getValueAsType());
102281ad6265SDimitry Andric       }
102381ad6265SDimitry Andric     }
102481ad6265SDimitry Andric   }
102581ad6265SDimitry Andric }
102681ad6265SDimitry Andric 
102781ad6265SDimitry Andric void ValueEnumerator::incorporateFunction(const Function &F) {
102881ad6265SDimitry Andric   InstructionCount = 0;
102981ad6265SDimitry Andric   NumModuleValues = Values.size();
103081ad6265SDimitry Andric 
103181ad6265SDimitry Andric   // Add global metadata to the function block.  This doesn't include
103281ad6265SDimitry Andric   // LocalAsMetadata.
103381ad6265SDimitry Andric   incorporateFunctionMetadata(F);
103481ad6265SDimitry Andric 
103581ad6265SDimitry Andric   // Adding function arguments to the value table.
103681ad6265SDimitry Andric   for (const auto &I : F.args()) {
103781ad6265SDimitry Andric     EnumerateValue(&I);
103881ad6265SDimitry Andric     if (I.hasAttribute(Attribute::ByVal))
103981ad6265SDimitry Andric       EnumerateType(I.getParamByValType());
104081ad6265SDimitry Andric     else if (I.hasAttribute(Attribute::StructRet))
104181ad6265SDimitry Andric       EnumerateType(I.getParamStructRetType());
104281ad6265SDimitry Andric     else if (I.hasAttribute(Attribute::ByRef))
104381ad6265SDimitry Andric       EnumerateType(I.getParamByRefType());
104481ad6265SDimitry Andric   }
104581ad6265SDimitry Andric   FirstFuncConstantID = Values.size();
104681ad6265SDimitry Andric 
104781ad6265SDimitry Andric   // Add all function-level constants to the value table.
104881ad6265SDimitry Andric   for (const BasicBlock &BB : F) {
104981ad6265SDimitry Andric     for (const Instruction &I : BB) {
105081ad6265SDimitry Andric       for (const Use &OI : I.operands()) {
105181ad6265SDimitry Andric         if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
105281ad6265SDimitry Andric           EnumerateValue(OI);
105381ad6265SDimitry Andric       }
105481ad6265SDimitry Andric       if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
105581ad6265SDimitry Andric         EnumerateValue(SVI->getShuffleMaskForBitcode());
105681ad6265SDimitry Andric     }
105781ad6265SDimitry Andric     BasicBlocks.push_back(&BB);
105881ad6265SDimitry Andric     ValueMap[&BB] = BasicBlocks.size();
105981ad6265SDimitry Andric   }
106081ad6265SDimitry Andric 
106181ad6265SDimitry Andric   // Add the function's parameter attributes so they are available for use in
106281ad6265SDimitry Andric   // the function's instruction.
106381ad6265SDimitry Andric   EnumerateAttributes(F.getAttributes());
106481ad6265SDimitry Andric 
106581ad6265SDimitry Andric   FirstInstID = Values.size();
106681ad6265SDimitry Andric 
106781ad6265SDimitry Andric   SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
106881ad6265SDimitry Andric   SmallVector<DIArgList *, 8> ArgListMDVector;
106981ad6265SDimitry Andric   // Add all of the instructions.
107081ad6265SDimitry Andric   for (const BasicBlock &BB : F) {
107181ad6265SDimitry Andric     for (const Instruction &I : BB) {
107281ad6265SDimitry Andric       for (const Use &OI : I.operands()) {
107381ad6265SDimitry Andric         if (auto *MD = dyn_cast<MetadataAsValue>(&OI)) {
107481ad6265SDimitry Andric           if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata())) {
107581ad6265SDimitry Andric             // Enumerate metadata after the instructions they might refer to.
107681ad6265SDimitry Andric             FnLocalMDVector.push_back(Local);
107781ad6265SDimitry Andric           } else if (auto *ArgList = dyn_cast<DIArgList>(MD->getMetadata())) {
107881ad6265SDimitry Andric             ArgListMDVector.push_back(ArgList);
107981ad6265SDimitry Andric             for (ValueAsMetadata *VMD : ArgList->getArgs()) {
108081ad6265SDimitry Andric               if (auto *Local = dyn_cast<LocalAsMetadata>(VMD)) {
108181ad6265SDimitry Andric                 // Enumerate metadata after the instructions they might refer
108281ad6265SDimitry Andric                 // to.
108381ad6265SDimitry Andric                 FnLocalMDVector.push_back(Local);
108481ad6265SDimitry Andric               }
108581ad6265SDimitry Andric             }
108681ad6265SDimitry Andric           }
108781ad6265SDimitry Andric         }
108881ad6265SDimitry Andric       }
108981ad6265SDimitry Andric 
109081ad6265SDimitry Andric       if (!I.getType()->isVoidTy())
109181ad6265SDimitry Andric         EnumerateValue(&I);
109281ad6265SDimitry Andric     }
109381ad6265SDimitry Andric   }
109481ad6265SDimitry Andric 
109581ad6265SDimitry Andric   // Add all of the function-local metadata.
109681ad6265SDimitry Andric   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) {
109781ad6265SDimitry Andric     // At this point, every local values have been incorporated, we shouldn't
109881ad6265SDimitry Andric     // have a metadata operand that references a value that hasn't been seen.
109981ad6265SDimitry Andric     assert(ValueMap.count(FnLocalMDVector[i]->getValue()) &&
110081ad6265SDimitry Andric            "Missing value for metadata operand");
110181ad6265SDimitry Andric     EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
110281ad6265SDimitry Andric   }
110381ad6265SDimitry Andric   // DIArgList entries must come after function-local metadata, as it is not
110481ad6265SDimitry Andric   // possible to forward-reference them.
110581ad6265SDimitry Andric   for (const DIArgList *ArgList : ArgListMDVector)
110681ad6265SDimitry Andric     EnumerateFunctionLocalListMetadata(F, ArgList);
110781ad6265SDimitry Andric }
110881ad6265SDimitry Andric 
110981ad6265SDimitry Andric void ValueEnumerator::purgeFunction() {
111081ad6265SDimitry Andric   /// Remove purged values from the ValueMap.
111181ad6265SDimitry Andric   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
111281ad6265SDimitry Andric     ValueMap.erase(Values[i].first);
111381ad6265SDimitry Andric   for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
111481ad6265SDimitry Andric     MetadataMap.erase(MDs[i]);
111581ad6265SDimitry Andric   for (const BasicBlock *BB : BasicBlocks)
111681ad6265SDimitry Andric     ValueMap.erase(BB);
111781ad6265SDimitry Andric 
111881ad6265SDimitry Andric   Values.resize(NumModuleValues);
111981ad6265SDimitry Andric   MDs.resize(NumModuleMDs);
112081ad6265SDimitry Andric   BasicBlocks.clear();
112181ad6265SDimitry Andric   NumMDStrings = 0;
112281ad6265SDimitry Andric }
112381ad6265SDimitry Andric 
112481ad6265SDimitry Andric static void IncorporateFunctionInfoGlobalBBIDs(
112581ad6265SDimitry Andric     const Function *F, DenseMap<const BasicBlock *, unsigned> &IDMap) {
112681ad6265SDimitry Andric   unsigned Counter = 0;
112781ad6265SDimitry Andric   for (const BasicBlock &BB : *F)
112881ad6265SDimitry Andric     IDMap[&BB] = ++Counter;
112981ad6265SDimitry Andric }
113081ad6265SDimitry Andric 
113181ad6265SDimitry Andric /// getGlobalBasicBlockID - This returns the function-specific ID for the
113281ad6265SDimitry Andric /// specified basic block.  This is relatively expensive information, so it
113381ad6265SDimitry Andric /// should only be used by rare constructs such as address-of-label.
113481ad6265SDimitry Andric unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
113581ad6265SDimitry Andric   unsigned &Idx = GlobalBasicBlockIDs[BB];
113681ad6265SDimitry Andric   if (Idx != 0)
113781ad6265SDimitry Andric     return Idx - 1;
113881ad6265SDimitry Andric 
113981ad6265SDimitry Andric   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
114081ad6265SDimitry Andric   return getGlobalBasicBlockID(BB);
114181ad6265SDimitry Andric }
114281ad6265SDimitry Andric 
1143*0fca6ea1SDimitry Andric uint64_t ValueEnumerator::computeBitsRequiredForTypeIndices() const {
114481ad6265SDimitry Andric   return Log2_32_Ceil(getTypes().size() + 1);
114581ad6265SDimitry Andric }
1146