1044eb2f6SDimitry Andric //===- ValueEnumerator.cpp - Number values and types for bitcode writer ---===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the ValueEnumerator class.
10009b1c42SEd Schouten //
11009b1c42SEd Schouten //===----------------------------------------------------------------------===//
12009b1c42SEd Schouten
13009b1c42SEd Schouten #include "ValueEnumerator.h"
14044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
15eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
16044eb2f6SDimitry Andric #include "llvm/IR/Argument.h"
17044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
18044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
195a5ac124SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
204a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
21044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
22044eb2f6SDimitry Andric #include "llvm/IR/GlobalAlias.h"
23044eb2f6SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
24044eb2f6SDimitry Andric #include "llvm/IR/GlobalObject.h"
25044eb2f6SDimitry Andric #include "llvm/IR/GlobalValue.h"
26044eb2f6SDimitry Andric #include "llvm/IR/GlobalVariable.h"
27044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
284a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
29044eb2f6SDimitry Andric #include "llvm/IR/Metadata.h"
304a16efa3SDimitry Andric #include "llvm/IR/Module.h"
31344a3780SDimitry Andric #include "llvm/IR/Operator.h"
32044eb2f6SDimitry Andric #include "llvm/IR/Type.h"
33044eb2f6SDimitry Andric #include "llvm/IR/Use.h"
34044eb2f6SDimitry Andric #include "llvm/IR/User.h"
35044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
364a16efa3SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
37044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
38044eb2f6SDimitry Andric #include "llvm/Support/Compiler.h"
3963faed5bSDimitry Andric #include "llvm/Support/Debug.h"
40044eb2f6SDimitry Andric #include "llvm/Support/MathExtras.h"
4163faed5bSDimitry Andric #include "llvm/Support/raw_ostream.h"
42009b1c42SEd Schouten #include <algorithm>
43044eb2f6SDimitry Andric #include <cstddef>
44044eb2f6SDimitry Andric #include <iterator>
45044eb2f6SDimitry Andric #include <tuple>
46044eb2f6SDimitry Andric
47009b1c42SEd Schouten using namespace llvm;
48009b1c42SEd Schouten
4967c32a98SDimitry Andric namespace {
50044eb2f6SDimitry Andric
5167c32a98SDimitry Andric struct OrderMap {
5267c32a98SDimitry Andric DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
53044eb2f6SDimitry Andric unsigned LastGlobalValueID = 0;
5467c32a98SDimitry Andric
55044eb2f6SDimitry Andric OrderMap() = default;
5667c32a98SDimitry Andric
isGlobalValue__anon6d2696990111::OrderMap5767c32a98SDimitry Andric bool isGlobalValue(unsigned ID) const {
58145449b1SDimitry Andric return ID <= LastGlobalValueID;
5967c32a98SDimitry Andric }
6067c32a98SDimitry Andric
size__anon6d2696990111::OrderMap6167c32a98SDimitry Andric unsigned size() const { return IDs.size(); }
operator []__anon6d2696990111::OrderMap6267c32a98SDimitry Andric std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
63044eb2f6SDimitry Andric
lookup__anon6d2696990111::OrderMap6467c32a98SDimitry Andric std::pair<unsigned, bool> lookup(const Value *V) const {
6567c32a98SDimitry Andric return IDs.lookup(V);
6667c32a98SDimitry Andric }
67044eb2f6SDimitry Andric
index__anon6d2696990111::OrderMap6867c32a98SDimitry Andric void index(const Value *V) {
6967c32a98SDimitry Andric // Explicitly sequence get-size and insert-value operations to avoid UB.
7067c32a98SDimitry Andric unsigned ID = IDs.size() + 1;
7167c32a98SDimitry Andric IDs[V].first = ID;
7267c32a98SDimitry Andric }
7367c32a98SDimitry Andric };
74044eb2f6SDimitry Andric
75044eb2f6SDimitry Andric } // end anonymous namespace
7667c32a98SDimitry Andric
orderValue(const Value * V,OrderMap & OM)7767c32a98SDimitry Andric static void orderValue(const Value *V, OrderMap &OM) {
7867c32a98SDimitry Andric if (OM.lookup(V).first)
7967c32a98SDimitry Andric return;
8067c32a98SDimitry Andric
81cfca06d7SDimitry Andric if (const Constant *C = dyn_cast<Constant>(V)) {
82145449b1SDimitry Andric if (C->getNumOperands()) {
8367c32a98SDimitry Andric for (const Value *Op : C->operands())
8467c32a98SDimitry Andric if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
8567c32a98SDimitry Andric orderValue(Op, OM);
86cfca06d7SDimitry Andric if (auto *CE = dyn_cast<ConstantExpr>(C))
87cfca06d7SDimitry Andric if (CE->getOpcode() == Instruction::ShuffleVector)
88cfca06d7SDimitry Andric orderValue(CE->getShuffleMaskForBitcode(), OM);
89cfca06d7SDimitry Andric }
90cfca06d7SDimitry Andric }
9167c32a98SDimitry Andric
9267c32a98SDimitry Andric // Note: we cannot cache this lookup above, since inserting into the map
9367c32a98SDimitry Andric // changes the map's size, and thus affects the other IDs.
9467c32a98SDimitry Andric OM.index(V);
9567c32a98SDimitry Andric }
9667c32a98SDimitry Andric
orderModule(const Module & M)9767c32a98SDimitry Andric static OrderMap orderModule(const Module &M) {
9867c32a98SDimitry Andric // This needs to match the order used by ValueEnumerator::ValueEnumerator()
9967c32a98SDimitry Andric // and ValueEnumerator::incorporateFunction().
10067c32a98SDimitry Andric OrderMap OM;
10167c32a98SDimitry Andric
102145449b1SDimitry Andric // Initializers of GlobalValues are processed in
103145449b1SDimitry Andric // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
104145449b1SDimitry Andric // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
105145449b1SDimitry Andric // by giving IDs in reverse order.
106145449b1SDimitry Andric //
107145449b1SDimitry Andric // Since GlobalValues never reference each other directly (just through
108145449b1SDimitry Andric // initializers), their relative IDs only matter for determining order of
109145449b1SDimitry Andric // uses in their initializers.
110145449b1SDimitry Andric for (const GlobalVariable &G : reverse(M.globals()))
111145449b1SDimitry Andric orderValue(&G, OM);
112145449b1SDimitry Andric for (const GlobalAlias &A : reverse(M.aliases()))
113145449b1SDimitry Andric orderValue(&A, OM);
114145449b1SDimitry Andric for (const GlobalIFunc &I : reverse(M.ifuncs()))
115145449b1SDimitry Andric orderValue(&I, OM);
116145449b1SDimitry Andric for (const Function &F : reverse(M))
117145449b1SDimitry Andric orderValue(&F, OM);
118145449b1SDimitry Andric OM.LastGlobalValueID = OM.size();
119b60736ecSDimitry Andric
120344a3780SDimitry Andric auto orderConstantValue = [&OM](const Value *V) {
121145449b1SDimitry Andric if (isa<Constant>(V) || isa<InlineAsm>(V))
122344a3780SDimitry Andric orderValue(V, OM);
123344a3780SDimitry Andric };
124145449b1SDimitry Andric
125b60736ecSDimitry Andric for (const Function &F : M) {
126b60736ecSDimitry Andric if (F.isDeclaration())
127b60736ecSDimitry Andric continue;
128145449b1SDimitry Andric // Here we need to match the union of ValueEnumerator::incorporateFunction()
129145449b1SDimitry Andric // and WriteFunction(). Basic blocks are implicitly declared before
130145449b1SDimitry Andric // anything else (by declaring their size).
131145449b1SDimitry Andric for (const BasicBlock &BB : F)
132145449b1SDimitry Andric orderValue(&BB, OM);
133145449b1SDimitry Andric
134145449b1SDimitry Andric // Metadata used by instructions is decoded before the actual instructions,
135145449b1SDimitry Andric // so visit any constants used by it beforehand.
136b60736ecSDimitry Andric for (const BasicBlock &BB : F)
137ac9a064cSDimitry Andric for (const Instruction &I : BB) {
138ac9a064cSDimitry Andric auto OrderConstantFromMetadata = [&](Metadata *MD) {
139ac9a064cSDimitry Andric if (const auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
140344a3780SDimitry Andric orderConstantValue(VAM->getValue());
141ac9a064cSDimitry Andric } else if (const auto *AL = dyn_cast<DIArgList>(MD)) {
142344a3780SDimitry Andric for (const auto *VAM : AL->getArgs())
143344a3780SDimitry Andric orderConstantValue(VAM->getValue());
144344a3780SDimitry Andric }
145ac9a064cSDimitry Andric };
146ac9a064cSDimitry Andric
147ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
148ac9a064cSDimitry Andric OrderConstantFromMetadata(DVR.getRawLocation());
149ac9a064cSDimitry Andric if (DVR.isDbgAssign())
150ac9a064cSDimitry Andric OrderConstantFromMetadata(DVR.getRawAddress());
151ac9a064cSDimitry Andric }
152ac9a064cSDimitry Andric
153ac9a064cSDimitry Andric for (const Value *V : I.operands()) {
154ac9a064cSDimitry Andric if (const auto *MAV = dyn_cast<MetadataAsValue>(V))
155ac9a064cSDimitry Andric OrderConstantFromMetadata(MAV->getMetadata());
156b60736ecSDimitry Andric }
157b60736ecSDimitry Andric }
15867c32a98SDimitry Andric
15967c32a98SDimitry Andric for (const Argument &A : F.args())
16067c32a98SDimitry Andric orderValue(&A, OM);
16167c32a98SDimitry Andric for (const BasicBlock &BB : F)
162cfca06d7SDimitry Andric for (const Instruction &I : BB) {
16367c32a98SDimitry Andric for (const Value *Op : I.operands())
164145449b1SDimitry Andric orderConstantValue(Op);
165cfca06d7SDimitry Andric if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
166cfca06d7SDimitry Andric orderValue(SVI->getShuffleMaskForBitcode(), OM);
16767c32a98SDimitry Andric orderValue(&I, OM);
16867c32a98SDimitry Andric }
169145449b1SDimitry Andric }
17067c32a98SDimitry Andric return OM;
17167c32a98SDimitry Andric }
17267c32a98SDimitry Andric
predictValueUseListOrderImpl(const Value * V,const Function * F,unsigned ID,const OrderMap & OM,UseListOrderStack & Stack)17367c32a98SDimitry Andric static void predictValueUseListOrderImpl(const Value *V, const Function *F,
17467c32a98SDimitry Andric unsigned ID, const OrderMap &OM,
17567c32a98SDimitry Andric UseListOrderStack &Stack) {
17667c32a98SDimitry Andric // Predict use-list order for this one.
177044eb2f6SDimitry Andric using Entry = std::pair<const Use *, unsigned>;
17867c32a98SDimitry Andric SmallVector<Entry, 64> List;
17967c32a98SDimitry Andric for (const Use &U : V->uses())
18067c32a98SDimitry Andric // Check if this user will be serialized.
18167c32a98SDimitry Andric if (OM.lookup(U.getUser()).first)
18267c32a98SDimitry Andric List.push_back(std::make_pair(&U, List.size()));
18367c32a98SDimitry Andric
18467c32a98SDimitry Andric if (List.size() < 2)
18567c32a98SDimitry Andric // We may have lost some users.
18667c32a98SDimitry Andric return;
18767c32a98SDimitry Andric
18867c32a98SDimitry Andric bool IsGlobalValue = OM.isGlobalValue(ID);
189d8e91e46SDimitry Andric llvm::sort(List, [&](const Entry &L, const Entry &R) {
19067c32a98SDimitry Andric const Use *LU = L.first;
19167c32a98SDimitry Andric const Use *RU = R.first;
19267c32a98SDimitry Andric if (LU == RU)
19367c32a98SDimitry Andric return false;
19467c32a98SDimitry Andric
19567c32a98SDimitry Andric auto LID = OM.lookup(LU->getUser()).first;
19667c32a98SDimitry Andric auto RID = OM.lookup(RU->getUser()).first;
19767c32a98SDimitry Andric
19867c32a98SDimitry Andric // If ID is 4, then expect: 7 6 5 1 2 3.
19967c32a98SDimitry Andric if (LID < RID) {
20067c32a98SDimitry Andric if (RID <= ID)
20167c32a98SDimitry Andric if (!IsGlobalValue) // GlobalValue uses don't get reversed.
20267c32a98SDimitry Andric return true;
20367c32a98SDimitry Andric return false;
20467c32a98SDimitry Andric }
20567c32a98SDimitry Andric if (RID < LID) {
20667c32a98SDimitry Andric if (LID <= ID)
20767c32a98SDimitry Andric if (!IsGlobalValue) // GlobalValue uses don't get reversed.
20867c32a98SDimitry Andric return false;
20967c32a98SDimitry Andric return true;
21067c32a98SDimitry Andric }
21167c32a98SDimitry Andric
21267c32a98SDimitry Andric // LID and RID are equal, so we have different operands of the same user.
21367c32a98SDimitry Andric // Assume operands are added in order for all instructions.
21467c32a98SDimitry Andric if (LID <= ID)
21567c32a98SDimitry Andric if (!IsGlobalValue) // GlobalValue uses don't get reversed.
21667c32a98SDimitry Andric return LU->getOperandNo() < RU->getOperandNo();
21767c32a98SDimitry Andric return LU->getOperandNo() > RU->getOperandNo();
21867c32a98SDimitry Andric });
21967c32a98SDimitry Andric
220145449b1SDimitry Andric if (llvm::is_sorted(List, llvm::less_second()))
22167c32a98SDimitry Andric // Order is already correct.
22267c32a98SDimitry Andric return;
22367c32a98SDimitry Andric
22467c32a98SDimitry Andric // Store the shuffle.
22567c32a98SDimitry Andric Stack.emplace_back(V, F, List.size());
22667c32a98SDimitry Andric assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
22767c32a98SDimitry Andric for (size_t I = 0, E = List.size(); I != E; ++I)
22867c32a98SDimitry Andric Stack.back().Shuffle[I] = List[I].second;
22967c32a98SDimitry Andric }
23067c32a98SDimitry Andric
predictValueUseListOrder(const Value * V,const Function * F,OrderMap & OM,UseListOrderStack & Stack)23167c32a98SDimitry Andric static void predictValueUseListOrder(const Value *V, const Function *F,
23267c32a98SDimitry Andric OrderMap &OM, UseListOrderStack &Stack) {
23367c32a98SDimitry Andric auto &IDPair = OM[V];
23467c32a98SDimitry Andric assert(IDPair.first && "Unmapped value");
23567c32a98SDimitry Andric if (IDPair.second)
23667c32a98SDimitry Andric // Already predicted.
23767c32a98SDimitry Andric return;
23867c32a98SDimitry Andric
23967c32a98SDimitry Andric // Do the actual prediction.
24067c32a98SDimitry Andric IDPair.second = true;
24167c32a98SDimitry Andric if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
24267c32a98SDimitry Andric predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
24367c32a98SDimitry Andric
24467c32a98SDimitry Andric // Recursive descent into constants.
245cfca06d7SDimitry Andric if (const Constant *C = dyn_cast<Constant>(V)) {
246cfca06d7SDimitry Andric if (C->getNumOperands()) { // Visit GlobalValues.
24767c32a98SDimitry Andric for (const Value *Op : C->operands())
24867c32a98SDimitry Andric if (isa<Constant>(Op)) // Visit GlobalValues.
24967c32a98SDimitry Andric predictValueUseListOrder(Op, F, OM, Stack);
250cfca06d7SDimitry Andric if (auto *CE = dyn_cast<ConstantExpr>(C))
251cfca06d7SDimitry Andric if (CE->getOpcode() == Instruction::ShuffleVector)
252cfca06d7SDimitry Andric predictValueUseListOrder(CE->getShuffleMaskForBitcode(), F, OM,
253cfca06d7SDimitry Andric Stack);
254cfca06d7SDimitry Andric }
255cfca06d7SDimitry Andric }
25667c32a98SDimitry Andric }
25767c32a98SDimitry Andric
predictUseListOrder(const Module & M)25867c32a98SDimitry Andric static UseListOrderStack predictUseListOrder(const Module &M) {
25967c32a98SDimitry Andric OrderMap OM = orderModule(M);
26067c32a98SDimitry Andric
26167c32a98SDimitry Andric // Use-list orders need to be serialized after all the users have been added
26267c32a98SDimitry Andric // to a value, or else the shuffles will be incomplete. Store them per
26367c32a98SDimitry Andric // function in a stack.
26467c32a98SDimitry Andric //
26567c32a98SDimitry Andric // Aside from function order, the order of values doesn't matter much here.
26667c32a98SDimitry Andric UseListOrderStack Stack;
26767c32a98SDimitry Andric
26867c32a98SDimitry Andric // We want to visit the functions backward now so we can list function-local
26967c32a98SDimitry Andric // constants in the last Function they're used in. Module-level constants
27067c32a98SDimitry Andric // have already been visited above.
27177fc4c14SDimitry Andric for (const Function &F : llvm::reverse(M)) {
272ac9a064cSDimitry Andric auto PredictValueOrderFromMetadata = [&](Metadata *MD) {
273ac9a064cSDimitry Andric if (const auto *VAM = dyn_cast<ValueAsMetadata>(MD)) {
274ac9a064cSDimitry Andric predictValueUseListOrder(VAM->getValue(), &F, OM, Stack);
275ac9a064cSDimitry Andric } else if (const auto *AL = dyn_cast<DIArgList>(MD)) {
276ac9a064cSDimitry Andric for (const auto *VAM : AL->getArgs())
277ac9a064cSDimitry Andric predictValueUseListOrder(VAM->getValue(), &F, OM, Stack);
278ac9a064cSDimitry Andric }
279ac9a064cSDimitry Andric };
28067c32a98SDimitry Andric if (F.isDeclaration())
28167c32a98SDimitry Andric continue;
28267c32a98SDimitry Andric for (const BasicBlock &BB : F)
28367c32a98SDimitry Andric predictValueUseListOrder(&BB, &F, OM, Stack);
28467c32a98SDimitry Andric for (const Argument &A : F.args())
28567c32a98SDimitry Andric predictValueUseListOrder(&A, &F, OM, Stack);
286ac9a064cSDimitry Andric for (const BasicBlock &BB : F) {
287cfca06d7SDimitry Andric for (const Instruction &I : BB) {
288ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
289ac9a064cSDimitry Andric PredictValueOrderFromMetadata(DVR.getRawLocation());
290ac9a064cSDimitry Andric if (DVR.isDbgAssign())
291ac9a064cSDimitry Andric PredictValueOrderFromMetadata(DVR.getRawAddress());
292ac9a064cSDimitry Andric }
293145449b1SDimitry Andric for (const Value *Op : I.operands()) {
29467c32a98SDimitry Andric if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
29567c32a98SDimitry Andric predictValueUseListOrder(Op, &F, OM, Stack);
296ac9a064cSDimitry Andric if (const auto *MAV = dyn_cast<MetadataAsValue>(Op))
297ac9a064cSDimitry Andric PredictValueOrderFromMetadata(MAV->getMetadata());
298145449b1SDimitry Andric }
299cfca06d7SDimitry Andric if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
300cfca06d7SDimitry Andric predictValueUseListOrder(SVI->getShuffleMaskForBitcode(), &F, OM,
301cfca06d7SDimitry Andric Stack);
30267c32a98SDimitry Andric predictValueUseListOrder(&I, &F, OM, Stack);
30367c32a98SDimitry Andric }
304145449b1SDimitry Andric }
305ac9a064cSDimitry Andric }
30667c32a98SDimitry Andric
30767c32a98SDimitry Andric // Visit globals last, since the module-level use-list block will be seen
30867c32a98SDimitry Andric // before the function bodies are processed.
30967c32a98SDimitry Andric for (const GlobalVariable &G : M.globals())
31067c32a98SDimitry Andric predictValueUseListOrder(&G, nullptr, OM, Stack);
31167c32a98SDimitry Andric for (const Function &F : M)
31267c32a98SDimitry Andric predictValueUseListOrder(&F, nullptr, OM, Stack);
31367c32a98SDimitry Andric for (const GlobalAlias &A : M.aliases())
31467c32a98SDimitry Andric predictValueUseListOrder(&A, nullptr, OM, Stack);
31501095a5dSDimitry Andric for (const GlobalIFunc &I : M.ifuncs())
31601095a5dSDimitry Andric predictValueUseListOrder(&I, nullptr, OM, Stack);
31767c32a98SDimitry Andric for (const GlobalVariable &G : M.globals())
31867c32a98SDimitry Andric if (G.hasInitializer())
31967c32a98SDimitry Andric predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
32067c32a98SDimitry Andric for (const GlobalAlias &A : M.aliases())
32167c32a98SDimitry Andric predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
32201095a5dSDimitry Andric for (const GlobalIFunc &I : M.ifuncs())
32301095a5dSDimitry Andric predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
32467c32a98SDimitry Andric for (const Function &F : M) {
325dd58ef01SDimitry Andric for (const Use &U : F.operands())
326dd58ef01SDimitry Andric predictValueUseListOrder(U.get(), nullptr, OM, Stack);
32767c32a98SDimitry Andric }
32867c32a98SDimitry Andric
32967c32a98SDimitry Andric return Stack;
33067c32a98SDimitry Andric }
33167c32a98SDimitry Andric
isIntOrIntVectorValue(const std::pair<const Value *,unsigned> & V)3324a16efa3SDimitry Andric static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
3334a16efa3SDimitry Andric return V.first->getType()->isIntOrIntVectorTy();
334009b1c42SEd Schouten }
335009b1c42SEd Schouten
ValueEnumerator(const Module & M,bool ShouldPreserveUseListOrder)3365a5ac124SDimitry Andric ValueEnumerator::ValueEnumerator(const Module &M,
3375a5ac124SDimitry Andric bool ShouldPreserveUseListOrder)
33801095a5dSDimitry Andric : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
3395a5ac124SDimitry Andric if (ShouldPreserveUseListOrder)
34067c32a98SDimitry Andric UseListOrders = predictUseListOrder(M);
34167c32a98SDimitry Andric
342009b1c42SEd Schouten // Enumerate the global variables.
343344a3780SDimitry Andric for (const GlobalVariable &GV : M.globals()) {
3443a0822f0SDimitry Andric EnumerateValue(&GV);
345344a3780SDimitry Andric EnumerateType(GV.getValueType());
346344a3780SDimitry Andric }
347009b1c42SEd Schouten
348009b1c42SEd Schouten // Enumerate the functions.
3493a0822f0SDimitry Andric for (const Function & F : M) {
3503a0822f0SDimitry Andric EnumerateValue(&F);
351344a3780SDimitry Andric EnumerateType(F.getValueType());
3523a0822f0SDimitry Andric EnumerateAttributes(F.getAttributes());
353009b1c42SEd Schouten }
354009b1c42SEd Schouten
355009b1c42SEd Schouten // Enumerate the aliases.
356344a3780SDimitry Andric for (const GlobalAlias &GA : M.aliases()) {
3573a0822f0SDimitry Andric EnumerateValue(&GA);
358344a3780SDimitry Andric EnumerateType(GA.getValueType());
359344a3780SDimitry Andric }
360009b1c42SEd Schouten
36101095a5dSDimitry Andric // Enumerate the ifuncs.
3626f8fc217SDimitry Andric for (const GlobalIFunc &GIF : M.ifuncs()) {
36301095a5dSDimitry Andric EnumerateValue(&GIF);
3646f8fc217SDimitry Andric EnumerateType(GIF.getValueType());
3656f8fc217SDimitry Andric }
36601095a5dSDimitry Andric
367009b1c42SEd Schouten // Remember what is the cutoff between globalvalue's and other constants.
368009b1c42SEd Schouten unsigned FirstConstant = Values.size();
369009b1c42SEd Schouten
3706b3f41edSDimitry Andric // Enumerate the global variable initializers and attributes.
3716b3f41edSDimitry Andric for (const GlobalVariable &GV : M.globals()) {
3723a0822f0SDimitry Andric if (GV.hasInitializer())
3733a0822f0SDimitry Andric EnumerateValue(GV.getInitializer());
3746b3f41edSDimitry Andric if (GV.hasAttributes())
3756b3f41edSDimitry Andric EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
3766b3f41edSDimitry Andric }
377009b1c42SEd Schouten
378009b1c42SEd Schouten // Enumerate the aliasees.
3793a0822f0SDimitry Andric for (const GlobalAlias &GA : M.aliases())
3803a0822f0SDimitry Andric EnumerateValue(GA.getAliasee());
381009b1c42SEd Schouten
38201095a5dSDimitry Andric // Enumerate the ifunc resolvers.
38301095a5dSDimitry Andric for (const GlobalIFunc &GIF : M.ifuncs())
38401095a5dSDimitry Andric EnumerateValue(GIF.getResolver());
38501095a5dSDimitry Andric
386dd58ef01SDimitry Andric // Enumerate any optional Function data.
3873a0822f0SDimitry Andric for (const Function &F : M)
388dd58ef01SDimitry Andric for (const Use &U : F.operands())
389dd58ef01SDimitry Andric EnumerateValue(U.get());
39067c32a98SDimitry Andric
39167c32a98SDimitry Andric // Enumerate the metadata type.
39267c32a98SDimitry Andric //
39367c32a98SDimitry Andric // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
39467c32a98SDimitry Andric // only encodes the metadata type when it's used as a value.
39567c32a98SDimitry Andric EnumerateType(Type::getMetadataTy(M.getContext()));
39667c32a98SDimitry Andric
397829000e0SRoman Divacky // Insert constants and metadata that are named at module level into the slot
398829000e0SRoman Divacky // pool so that the module symbol table can refer to them...
39967c32a98SDimitry Andric EnumerateValueSymbolTable(M.getValueSymbolTable());
400d39c594dSDimitry Andric EnumerateNamedMetadata(M);
401009b1c42SEd Schouten
4021e7804dbSRoman Divacky SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
40301095a5dSDimitry Andric for (const GlobalVariable &GV : M.globals()) {
40401095a5dSDimitry Andric MDs.clear();
40501095a5dSDimitry Andric GV.getAllMetadata(MDs);
40601095a5dSDimitry Andric for (const auto &I : MDs)
40701095a5dSDimitry Andric // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer
40801095a5dSDimitry Andric // to write metadata to the global variable's own metadata block
40901095a5dSDimitry Andric // (PR28134).
41001095a5dSDimitry Andric EnumerateMetadata(nullptr, I.second);
41101095a5dSDimitry Andric }
4121e7804dbSRoman Divacky
413009b1c42SEd Schouten // Enumerate types used by function bodies and argument lists.
41467c32a98SDimitry Andric for (const Function &F : M) {
4155ca98fd9SDimitry Andric for (const Argument &A : F.args())
4165ca98fd9SDimitry Andric EnumerateType(A.getType());
417009b1c42SEd Schouten
4185a5ac124SDimitry Andric // Enumerate metadata attached to this function.
41901095a5dSDimitry Andric MDs.clear();
4205a5ac124SDimitry Andric F.getAllMetadata(MDs);
4215a5ac124SDimitry Andric for (const auto &I : MDs)
42201095a5dSDimitry Andric EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second);
4235a5ac124SDimitry Andric
4245ca98fd9SDimitry Andric for (const BasicBlock &BB : F)
4255ca98fd9SDimitry Andric for (const Instruction &I : BB) {
426ac9a064cSDimitry Andric // Local metadata is enumerated during function-incorporation, but
427ac9a064cSDimitry Andric // any ConstantAsMetadata arguments in a DIArgList should be examined
428ac9a064cSDimitry Andric // now.
429ac9a064cSDimitry Andric auto EnumerateNonLocalValuesFromMetadata = [&](Metadata *MD) {
430ac9a064cSDimitry Andric assert(MD && "Metadata unexpectedly null");
431ac9a064cSDimitry Andric if (const auto *AL = dyn_cast<DIArgList>(MD)) {
432ac9a064cSDimitry Andric for (const auto *VAM : AL->getArgs()) {
433ac9a064cSDimitry Andric if (isa<ConstantAsMetadata>(VAM))
434ac9a064cSDimitry Andric EnumerateMetadata(&F, VAM);
435ac9a064cSDimitry Andric }
436ac9a064cSDimitry Andric return;
437ac9a064cSDimitry Andric }
438ac9a064cSDimitry Andric
439ac9a064cSDimitry Andric if (!isa<LocalAsMetadata>(MD))
440ac9a064cSDimitry Andric EnumerateMetadata(&F, MD);
441ac9a064cSDimitry Andric };
442ac9a064cSDimitry Andric
443ac9a064cSDimitry Andric for (DbgRecord &DR : I.getDbgRecordRange()) {
444ac9a064cSDimitry Andric if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
445ac9a064cSDimitry Andric EnumerateMetadata(&F, DLR->getLabel());
446ac9a064cSDimitry Andric EnumerateMetadata(&F, &*DLR->getDebugLoc());
447ac9a064cSDimitry Andric continue;
448ac9a064cSDimitry Andric }
449ac9a064cSDimitry Andric // Enumerate non-local location metadata.
450ac9a064cSDimitry Andric DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
451ac9a064cSDimitry Andric EnumerateNonLocalValuesFromMetadata(DVR.getRawLocation());
452ac9a064cSDimitry Andric EnumerateMetadata(&F, DVR.getExpression());
453ac9a064cSDimitry Andric EnumerateMetadata(&F, DVR.getVariable());
454ac9a064cSDimitry Andric EnumerateMetadata(&F, &*DVR.getDebugLoc());
455ac9a064cSDimitry Andric if (DVR.isDbgAssign()) {
456ac9a064cSDimitry Andric EnumerateNonLocalValuesFromMetadata(DVR.getRawAddress());
457ac9a064cSDimitry Andric EnumerateMetadata(&F, DVR.getAssignID());
458ac9a064cSDimitry Andric EnumerateMetadata(&F, DVR.getAddressExpression());
459ac9a064cSDimitry Andric }
460ac9a064cSDimitry Andric }
4615ca98fd9SDimitry Andric for (const Use &Op : I.operands()) {
46267c32a98SDimitry Andric auto *MD = dyn_cast<MetadataAsValue>(&Op);
46367c32a98SDimitry Andric if (!MD) {
4645ca98fd9SDimitry Andric EnumerateOperandType(Op);
46567c32a98SDimitry Andric continue;
46667c32a98SDimitry Andric }
46767c32a98SDimitry Andric
468ac9a064cSDimitry Andric EnumerateNonLocalValuesFromMetadata(MD->getMetadata());
469829000e0SRoman Divacky }
470cfca06d7SDimitry Andric if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
471cfca06d7SDimitry Andric EnumerateType(SVI->getShuffleMaskForBitcode()->getType());
472344a3780SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
473344a3780SDimitry Andric EnumerateType(GEP->getSourceElementType());
474344a3780SDimitry Andric if (auto *AI = dyn_cast<AllocaInst>(&I))
475344a3780SDimitry Andric EnumerateType(AI->getAllocatedType());
4765ca98fd9SDimitry Andric EnumerateType(I.getType());
477344a3780SDimitry Andric if (const auto *Call = dyn_cast<CallBase>(&I)) {
478e6d15924SDimitry Andric EnumerateAttributes(Call->getAttributes());
479344a3780SDimitry Andric EnumerateType(Call->getFunctionType());
480344a3780SDimitry Andric }
48159850d08SRoman Divacky
48259850d08SRoman Divacky // Enumerate metadata attached with this instruction.
4834a142eb2SRoman Divacky MDs.clear();
4845ca98fd9SDimitry Andric I.getAllMetadataOtherThanDebugLoc(MDs);
4851e7804dbSRoman Divacky for (unsigned i = 0, e = MDs.size(); i != e; ++i)
48601095a5dSDimitry Andric EnumerateMetadata(&F, MDs[i].second);
487b5efedafSRoman Divacky
4885a5ac124SDimitry Andric // Don't enumerate the location directly -- it has a special record
4895a5ac124SDimitry Andric // type -- but enumerate its operands.
4905a5ac124SDimitry Andric if (DILocation *L = I.getDebugLoc())
49101095a5dSDimitry Andric for (const Metadata *Op : L->operands())
49201095a5dSDimitry Andric EnumerateMetadata(&F, Op);
493009b1c42SEd Schouten }
494009b1c42SEd Schouten }
495009b1c42SEd Schouten
496009b1c42SEd Schouten // Optimize constant ordering.
497009b1c42SEd Schouten OptimizeConstants(FirstConstant, Values.size());
49801095a5dSDimitry Andric
49901095a5dSDimitry Andric // Organize metadata ordering.
50001095a5dSDimitry Andric organizeMetadata();
5016b943ff3SDimitry Andric }
5026b943ff3SDimitry Andric
getInstructionID(const Instruction * Inst) const50359850d08SRoman Divacky unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
50459850d08SRoman Divacky InstructionMapType::const_iterator I = InstructionMap.find(Inst);
50559850d08SRoman Divacky assert(I != InstructionMap.end() && "Instruction is not mapped!");
50659850d08SRoman Divacky return I->second;
50759850d08SRoman Divacky }
50859850d08SRoman Divacky
getComdatID(const Comdat * C) const5095ca98fd9SDimitry Andric unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
5105ca98fd9SDimitry Andric unsigned ComdatID = Comdats.idFor(C);
5115ca98fd9SDimitry Andric assert(ComdatID && "Comdat not found!");
5125ca98fd9SDimitry Andric return ComdatID;
5135ca98fd9SDimitry Andric }
5145ca98fd9SDimitry Andric
setInstructionID(const Instruction * I)51559850d08SRoman Divacky void ValueEnumerator::setInstructionID(const Instruction *I) {
51659850d08SRoman Divacky InstructionMap[I] = InstructionCount++;
51759850d08SRoman Divacky }
51859850d08SRoman Divacky
getValueID(const Value * V) const51959850d08SRoman Divacky unsigned ValueEnumerator::getValueID(const Value *V) const {
52067c32a98SDimitry Andric if (auto *MD = dyn_cast<MetadataAsValue>(V))
52167c32a98SDimitry Andric return getMetadataID(MD->getMetadata());
52259850d08SRoman Divacky
52359850d08SRoman Divacky ValueMapType::const_iterator I = ValueMap.find(V);
52459850d08SRoman Divacky assert(I != ValueMap.end() && "Value not in slotcalculator!");
52559850d08SRoman Divacky return I->second-1;
52659850d08SRoman Divacky }
52759850d08SRoman Divacky
52871d5a254SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const52901095a5dSDimitry Andric LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
53063faed5bSDimitry Andric print(dbgs(), ValueMap, "Default");
53163faed5bSDimitry Andric dbgs() << '\n';
532dd58ef01SDimitry Andric print(dbgs(), MetadataMap, "MetaData");
53363faed5bSDimitry Andric dbgs() << '\n';
53463faed5bSDimitry Andric }
53571d5a254SDimitry Andric #endif
53663faed5bSDimitry Andric
print(raw_ostream & OS,const ValueMapType & Map,const char * Name) const53763faed5bSDimitry Andric void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
53863faed5bSDimitry Andric const char *Name) const {
53963faed5bSDimitry Andric OS << "Map Name: " << Name << "\n";
54063faed5bSDimitry Andric OS << "Size: " << Map.size() << "\n";
54177fc4c14SDimitry Andric for (const auto &I : Map) {
54277fc4c14SDimitry Andric const Value *V = I.first;
54363faed5bSDimitry Andric if (V->hasName())
54463faed5bSDimitry Andric OS << "Value: " << V->getName();
54563faed5bSDimitry Andric else
54663faed5bSDimitry Andric OS << "Value: [null]\n";
54771d5a254SDimitry Andric V->print(errs());
54871d5a254SDimitry Andric errs() << '\n';
54963faed5bSDimitry Andric
550eb11fae6SDimitry Andric OS << " Uses(" << V->getNumUses() << "):";
5515ca98fd9SDimitry Andric for (const Use &U : V->uses()) {
5525ca98fd9SDimitry Andric if (&U != &*V->use_begin())
55363faed5bSDimitry Andric OS << ",";
5545ca98fd9SDimitry Andric if(U->hasName())
5555ca98fd9SDimitry Andric OS << " " << U->getName();
55663faed5bSDimitry Andric else
55763faed5bSDimitry Andric OS << " [null]";
55863faed5bSDimitry Andric
55963faed5bSDimitry Andric }
56063faed5bSDimitry Andric OS << "\n\n";
56163faed5bSDimitry Andric }
56263faed5bSDimitry Andric }
56363faed5bSDimitry Andric
print(raw_ostream & OS,const MetadataMapType & Map,const char * Name) const56467c32a98SDimitry Andric void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
56567c32a98SDimitry Andric const char *Name) const {
56667c32a98SDimitry Andric OS << "Map Name: " << Name << "\n";
56767c32a98SDimitry Andric OS << "Size: " << Map.size() << "\n";
56877fc4c14SDimitry Andric for (const auto &I : Map) {
56977fc4c14SDimitry Andric const Metadata *MD = I.first;
57077fc4c14SDimitry Andric OS << "Metadata: slot = " << I.second.ID << "\n";
57177fc4c14SDimitry Andric OS << "Metadata: function = " << I.second.F << "\n";
57267c32a98SDimitry Andric MD->print(OS);
57301095a5dSDimitry Andric OS << "\n";
57467c32a98SDimitry Andric }
57567c32a98SDimitry Andric }
57667c32a98SDimitry Andric
577009b1c42SEd Schouten /// OptimizeConstants - Reorder constant pool for denser encoding.
OptimizeConstants(unsigned CstStart,unsigned CstEnd)578009b1c42SEd Schouten void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
579009b1c42SEd Schouten if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
580009b1c42SEd Schouten
5815a5ac124SDimitry Andric if (ShouldPreserveUseListOrder)
58267c32a98SDimitry Andric // Optimizing constants makes the use-list order difficult to predict.
58367c32a98SDimitry Andric // Disable it for now when trying to preserve the order.
58467c32a98SDimitry Andric return;
58567c32a98SDimitry Andric
5865ca98fd9SDimitry Andric std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
5875ca98fd9SDimitry Andric [this](const std::pair<const Value *, unsigned> &LHS,
5885ca98fd9SDimitry Andric const std::pair<const Value *, unsigned> &RHS) {
5895ca98fd9SDimitry Andric // Sort by plane.
5905ca98fd9SDimitry Andric if (LHS.first->getType() != RHS.first->getType())
5915ca98fd9SDimitry Andric return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
5925ca98fd9SDimitry Andric // Then by frequency.
5935ca98fd9SDimitry Andric return LHS.second > RHS.second;
5945ca98fd9SDimitry Andric });
595009b1c42SEd Schouten
5964a16efa3SDimitry Andric // Ensure that integer and vector of integer constants are at the start of the
5974a16efa3SDimitry Andric // constant pool. This is important so that GEP structure indices come before
5984a16efa3SDimitry Andric // gep constant exprs.
59901095a5dSDimitry Andric std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
6004a16efa3SDimitry Andric isIntOrIntVectorValue);
601009b1c42SEd Schouten
602009b1c42SEd Schouten // Rebuild the modified portion of ValueMap.
603009b1c42SEd Schouten for (; CstStart != CstEnd; ++CstStart)
604009b1c42SEd Schouten ValueMap[Values[CstStart].first] = CstStart+1;
605009b1c42SEd Schouten }
606009b1c42SEd Schouten
607009b1c42SEd Schouten /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
608009b1c42SEd Schouten /// table into the values table.
EnumerateValueSymbolTable(const ValueSymbolTable & VST)609009b1c42SEd Schouten void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
610009b1c42SEd Schouten for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
611009b1c42SEd Schouten VI != VE; ++VI)
612009b1c42SEd Schouten EnumerateValue(VI->getValue());
613009b1c42SEd Schouten }
614009b1c42SEd Schouten
61567c32a98SDimitry Andric /// Insert all of the values referenced by named metadata in the specified
61667c32a98SDimitry Andric /// module.
EnumerateNamedMetadata(const Module & M)61767c32a98SDimitry Andric void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
618dd58ef01SDimitry Andric for (const auto &I : M.named_metadata())
619dd58ef01SDimitry Andric EnumerateNamedMDNode(&I);
620829000e0SRoman Divacky }
621829000e0SRoman Divacky
EnumerateNamedMDNode(const NamedMDNode * MD)622829000e0SRoman Divacky void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
623ac9a064cSDimitry Andric for (const MDNode *N : MD->operands())
624ac9a064cSDimitry Andric EnumerateMetadata(nullptr, N);
625829000e0SRoman Divacky }
626829000e0SRoman Divacky
getMetadataFunctionID(const Function * F) const62701095a5dSDimitry Andric unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const {
62801095a5dSDimitry Andric return F ? getValueID(F) + 1 : 0;
62901095a5dSDimitry Andric }
63001095a5dSDimitry Andric
EnumerateMetadata(const Function * F,const Metadata * MD)63101095a5dSDimitry Andric void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) {
63201095a5dSDimitry Andric EnumerateMetadata(getMetadataFunctionID(F), MD);
63301095a5dSDimitry Andric }
63401095a5dSDimitry Andric
EnumerateFunctionLocalMetadata(const Function & F,const LocalAsMetadata * Local)63501095a5dSDimitry Andric void ValueEnumerator::EnumerateFunctionLocalMetadata(
63601095a5dSDimitry Andric const Function &F, const LocalAsMetadata *Local) {
63701095a5dSDimitry Andric EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
63801095a5dSDimitry Andric }
63901095a5dSDimitry Andric
EnumerateFunctionLocalListMetadata(const Function & F,const DIArgList * ArgList)640344a3780SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalListMetadata(
641344a3780SDimitry Andric const Function &F, const DIArgList *ArgList) {
642344a3780SDimitry Andric EnumerateFunctionLocalListMetadata(getMetadataFunctionID(&F), ArgList);
643344a3780SDimitry Andric }
644344a3780SDimitry Andric
dropFunctionFromMetadata(MetadataMapType::value_type & FirstMD)64501095a5dSDimitry Andric void ValueEnumerator::dropFunctionFromMetadata(
64601095a5dSDimitry Andric MetadataMapType::value_type &FirstMD) {
64701095a5dSDimitry Andric SmallVector<const MDNode *, 64> Worklist;
64871d5a254SDimitry Andric auto push = [&Worklist](MetadataMapType::value_type &MD) {
64901095a5dSDimitry Andric auto &Entry = MD.second;
65001095a5dSDimitry Andric
65101095a5dSDimitry Andric // Nothing to do if this metadata isn't tagged.
65201095a5dSDimitry Andric if (!Entry.F)
65301095a5dSDimitry Andric return;
65401095a5dSDimitry Andric
65501095a5dSDimitry Andric // Drop the function tag.
65601095a5dSDimitry Andric Entry.F = 0;
65701095a5dSDimitry Andric
65801095a5dSDimitry Andric // If this is has an ID and is an MDNode, then its operands have entries as
65901095a5dSDimitry Andric // well. We need to drop the function from them too.
66001095a5dSDimitry Andric if (Entry.ID)
66101095a5dSDimitry Andric if (auto *N = dyn_cast<MDNode>(MD.first))
66201095a5dSDimitry Andric Worklist.push_back(N);
66301095a5dSDimitry Andric };
66401095a5dSDimitry Andric push(FirstMD);
66501095a5dSDimitry Andric while (!Worklist.empty())
66601095a5dSDimitry Andric for (const Metadata *Op : Worklist.pop_back_val()->operands()) {
66701095a5dSDimitry Andric if (!Op)
66867c32a98SDimitry Andric continue;
66901095a5dSDimitry Andric auto MD = MetadataMap.find(Op);
67001095a5dSDimitry Andric if (MD != MetadataMap.end())
67101095a5dSDimitry Andric push(*MD);
672d39c594dSDimitry Andric }
673829000e0SRoman Divacky }
674829000e0SRoman Divacky
EnumerateMetadata(unsigned F,const Metadata * MD)67501095a5dSDimitry Andric void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) {
67601095a5dSDimitry Andric // It's vital for reader efficiency that uniqued subgraphs are done in
67701095a5dSDimitry Andric // post-order; it's expensive when their operands have forward references.
67801095a5dSDimitry Andric // If a distinct node is referenced from a uniqued node, it'll be delayed
67901095a5dSDimitry Andric // until the uniqued subgraph has been completely traversed.
68001095a5dSDimitry Andric SmallVector<const MDNode *, 32> DelayedDistinctNodes;
68101095a5dSDimitry Andric
68201095a5dSDimitry Andric // Start by enumerating MD, and then work through its transitive operands in
68301095a5dSDimitry Andric // post-order. This requires a depth-first search.
68401095a5dSDimitry Andric SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist;
68501095a5dSDimitry Andric if (const MDNode *N = enumerateMetadataImpl(F, MD))
68601095a5dSDimitry Andric Worklist.push_back(std::make_pair(N, N->op_begin()));
68701095a5dSDimitry Andric
68801095a5dSDimitry Andric while (!Worklist.empty()) {
68901095a5dSDimitry Andric const MDNode *N = Worklist.back().first;
69001095a5dSDimitry Andric
69101095a5dSDimitry Andric // Enumerate operands until we hit a new node. We need to traverse these
69201095a5dSDimitry Andric // nodes' operands before visiting the rest of N's operands.
69301095a5dSDimitry Andric MDNode::op_iterator I = std::find_if(
69401095a5dSDimitry Andric Worklist.back().second, N->op_end(),
69501095a5dSDimitry Andric [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
69601095a5dSDimitry Andric if (I != N->op_end()) {
69701095a5dSDimitry Andric auto *Op = cast<MDNode>(*I);
69801095a5dSDimitry Andric Worklist.back().second = ++I;
69901095a5dSDimitry Andric
70001095a5dSDimitry Andric // Delay traversing Op if it's a distinct node and N is uniqued.
70101095a5dSDimitry Andric if (Op->isDistinct() && !N->isDistinct())
70201095a5dSDimitry Andric DelayedDistinctNodes.push_back(Op);
70301095a5dSDimitry Andric else
70401095a5dSDimitry Andric Worklist.push_back(std::make_pair(Op, Op->op_begin()));
70501095a5dSDimitry Andric continue;
70601095a5dSDimitry Andric }
70701095a5dSDimitry Andric
70801095a5dSDimitry Andric // All the operands have been visited. Now assign an ID.
70901095a5dSDimitry Andric Worklist.pop_back();
71001095a5dSDimitry Andric MDs.push_back(N);
71101095a5dSDimitry Andric MetadataMap[N].ID = MDs.size();
71201095a5dSDimitry Andric
71301095a5dSDimitry Andric // Flush out any delayed distinct nodes; these are all the distinct nodes
71401095a5dSDimitry Andric // that are leaves in last uniqued subgraph.
71501095a5dSDimitry Andric if (Worklist.empty() || Worklist.back().first->isDistinct()) {
71601095a5dSDimitry Andric for (const MDNode *N : DelayedDistinctNodes)
71701095a5dSDimitry Andric Worklist.push_back(std::make_pair(N, N->op_begin()));
71801095a5dSDimitry Andric DelayedDistinctNodes.clear();
71901095a5dSDimitry Andric }
72001095a5dSDimitry Andric }
72101095a5dSDimitry Andric }
72201095a5dSDimitry Andric
enumerateMetadataImpl(unsigned F,const Metadata * MD)72301095a5dSDimitry Andric const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F, const Metadata *MD) {
72401095a5dSDimitry Andric if (!MD)
72501095a5dSDimitry Andric return nullptr;
72601095a5dSDimitry Andric
72767c32a98SDimitry Andric assert(
72867c32a98SDimitry Andric (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
72967c32a98SDimitry Andric "Invalid metadata kind");
730d39c594dSDimitry Andric
73101095a5dSDimitry Andric auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F)));
73201095a5dSDimitry Andric MDIndex &Entry = Insertion.first->second;
73301095a5dSDimitry Andric if (!Insertion.second) {
73401095a5dSDimitry Andric // Already mapped. If F doesn't match the function tag, drop it.
73501095a5dSDimitry Andric if (Entry.hasDifferentFunction(F))
73601095a5dSDimitry Andric dropFunctionFromMetadata(*Insertion.first);
73701095a5dSDimitry Andric return nullptr;
73801095a5dSDimitry Andric }
739d39c594dSDimitry Andric
74001095a5dSDimitry Andric // Don't assign IDs to metadata nodes.
74167c32a98SDimitry Andric if (auto *N = dyn_cast<MDNode>(MD))
74201095a5dSDimitry Andric return N;
74301095a5dSDimitry Andric
74401095a5dSDimitry Andric // Save the metadata.
74501095a5dSDimitry Andric MDs.push_back(MD);
74601095a5dSDimitry Andric Entry.ID = MDs.size();
74701095a5dSDimitry Andric
74801095a5dSDimitry Andric // Enumerate the constant, if any.
74901095a5dSDimitry Andric if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
75067c32a98SDimitry Andric EnumerateValue(C->getValue());
75167c32a98SDimitry Andric
75201095a5dSDimitry Andric return nullptr;
753d39c594dSDimitry Andric }
754d39c594dSDimitry Andric
755344a3780SDimitry Andric /// EnumerateFunctionLocalMetadata - Incorporate function-local metadata
75667c32a98SDimitry Andric /// information reachable from the metadata.
EnumerateFunctionLocalMetadata(unsigned F,const LocalAsMetadata * Local)75767c32a98SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalMetadata(
75801095a5dSDimitry Andric unsigned F, const LocalAsMetadata *Local) {
75901095a5dSDimitry Andric assert(F && "Expected a function");
76001095a5dSDimitry Andric
761d39c594dSDimitry Andric // Check to see if it's already in!
76201095a5dSDimitry Andric MDIndex &Index = MetadataMap[Local];
76301095a5dSDimitry Andric if (Index.ID) {
76401095a5dSDimitry Andric assert(Index.F == F && "Expected the same function");
76559850d08SRoman Divacky return;
76601095a5dSDimitry Andric }
767d39c594dSDimitry Andric
76867c32a98SDimitry Andric MDs.push_back(Local);
76901095a5dSDimitry Andric Index.F = F;
77001095a5dSDimitry Andric Index.ID = MDs.size();
771d39c594dSDimitry Andric
77267c32a98SDimitry Andric EnumerateValue(Local->getValue());
77301095a5dSDimitry Andric }
77467c32a98SDimitry Andric
775344a3780SDimitry Andric /// EnumerateFunctionLocalListMetadata - Incorporate function-local metadata
776344a3780SDimitry Andric /// information reachable from the metadata.
EnumerateFunctionLocalListMetadata(unsigned F,const DIArgList * ArgList)777344a3780SDimitry Andric void ValueEnumerator::EnumerateFunctionLocalListMetadata(
778344a3780SDimitry Andric unsigned F, const DIArgList *ArgList) {
779344a3780SDimitry Andric assert(F && "Expected a function");
780344a3780SDimitry Andric
781344a3780SDimitry Andric // Check to see if it's already in!
782344a3780SDimitry Andric MDIndex &Index = MetadataMap[ArgList];
783344a3780SDimitry Andric if (Index.ID) {
784344a3780SDimitry Andric assert(Index.F == F && "Expected the same function");
785344a3780SDimitry Andric return;
786344a3780SDimitry Andric }
787344a3780SDimitry Andric
788344a3780SDimitry Andric for (ValueAsMetadata *VAM : ArgList->getArgs()) {
789344a3780SDimitry Andric if (isa<LocalAsMetadata>(VAM)) {
790344a3780SDimitry Andric assert(MetadataMap.count(VAM) &&
791344a3780SDimitry Andric "LocalAsMetadata should be enumerated before DIArgList");
792344a3780SDimitry Andric assert(MetadataMap[VAM].F == F &&
793344a3780SDimitry Andric "Expected LocalAsMetadata in the same function");
794344a3780SDimitry Andric } else {
795344a3780SDimitry Andric assert(isa<ConstantAsMetadata>(VAM) &&
796344a3780SDimitry Andric "Expected LocalAsMetadata or ConstantAsMetadata");
797344a3780SDimitry Andric assert(ValueMap.count(VAM->getValue()) &&
798344a3780SDimitry Andric "Constant should be enumerated beforeDIArgList");
799344a3780SDimitry Andric EnumerateMetadata(F, VAM);
800344a3780SDimitry Andric }
801344a3780SDimitry Andric }
802344a3780SDimitry Andric
803344a3780SDimitry Andric MDs.push_back(ArgList);
804344a3780SDimitry Andric Index.F = F;
805344a3780SDimitry Andric Index.ID = MDs.size();
806344a3780SDimitry Andric }
807344a3780SDimitry Andric
getMetadataTypeOrder(const Metadata * MD)80801095a5dSDimitry Andric static unsigned getMetadataTypeOrder(const Metadata *MD) {
80901095a5dSDimitry Andric // Strings are emitted in bulk and must come first.
81001095a5dSDimitry Andric if (isa<MDString>(MD))
81101095a5dSDimitry Andric return 0;
81201095a5dSDimitry Andric
81301095a5dSDimitry Andric // ConstantAsMetadata doesn't reference anything. We may as well shuffle it
81401095a5dSDimitry Andric // to the front since we can detect it.
81501095a5dSDimitry Andric auto *N = dyn_cast<MDNode>(MD);
81601095a5dSDimitry Andric if (!N)
81701095a5dSDimitry Andric return 1;
81801095a5dSDimitry Andric
81901095a5dSDimitry Andric // The reader is fast forward references for distinct node operands, but slow
82001095a5dSDimitry Andric // when uniqued operands are unresolved.
82101095a5dSDimitry Andric return N->isDistinct() ? 2 : 3;
82201095a5dSDimitry Andric }
82301095a5dSDimitry Andric
organizeMetadata()82401095a5dSDimitry Andric void ValueEnumerator::organizeMetadata() {
82501095a5dSDimitry Andric assert(MetadataMap.size() == MDs.size() &&
82601095a5dSDimitry Andric "Metadata map and vector out of sync");
82701095a5dSDimitry Andric
82801095a5dSDimitry Andric if (MDs.empty())
82901095a5dSDimitry Andric return;
83001095a5dSDimitry Andric
83101095a5dSDimitry Andric // Copy out the index information from MetadataMap in order to choose a new
83201095a5dSDimitry Andric // order.
83301095a5dSDimitry Andric SmallVector<MDIndex, 64> Order;
83401095a5dSDimitry Andric Order.reserve(MetadataMap.size());
83501095a5dSDimitry Andric for (const Metadata *MD : MDs)
83601095a5dSDimitry Andric Order.push_back(MetadataMap.lookup(MD));
83701095a5dSDimitry Andric
83801095a5dSDimitry Andric // Partition:
83901095a5dSDimitry Andric // - by function, then
84001095a5dSDimitry Andric // - by isa<MDString>
84101095a5dSDimitry Andric // and then sort by the original/current ID. Since the IDs are guaranteed to
8424b4fe385SDimitry Andric // be unique, the result of llvm::sort will be deterministic. There's no need
84301095a5dSDimitry Andric // for std::stable_sort.
844d8e91e46SDimitry Andric llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
84501095a5dSDimitry Andric return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <
84601095a5dSDimitry Andric std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID);
84701095a5dSDimitry Andric });
84801095a5dSDimitry Andric
84901095a5dSDimitry Andric // Rebuild MDs, index the metadata ranges for each function in FunctionMDs,
85001095a5dSDimitry Andric // and fix up MetadataMap.
851e6d15924SDimitry Andric std::vector<const Metadata *> OldMDs;
852e6d15924SDimitry Andric MDs.swap(OldMDs);
85301095a5dSDimitry Andric MDs.reserve(OldMDs.size());
85401095a5dSDimitry Andric for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) {
85501095a5dSDimitry Andric auto *MD = Order[I].get(OldMDs);
85601095a5dSDimitry Andric MDs.push_back(MD);
85701095a5dSDimitry Andric MetadataMap[MD].ID = I + 1;
85801095a5dSDimitry Andric if (isa<MDString>(MD))
85901095a5dSDimitry Andric ++NumMDStrings;
86001095a5dSDimitry Andric }
86101095a5dSDimitry Andric
86201095a5dSDimitry Andric // Return early if there's nothing for the functions.
86301095a5dSDimitry Andric if (MDs.size() == Order.size())
86401095a5dSDimitry Andric return;
86501095a5dSDimitry Andric
86601095a5dSDimitry Andric // Build the function metadata ranges.
86701095a5dSDimitry Andric MDRange R;
86801095a5dSDimitry Andric FunctionMDs.reserve(OldMDs.size());
86901095a5dSDimitry Andric unsigned PrevF = 0;
87001095a5dSDimitry Andric for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E;
87101095a5dSDimitry Andric ++I) {
87201095a5dSDimitry Andric unsigned F = Order[I].F;
87301095a5dSDimitry Andric if (!PrevF) {
87401095a5dSDimitry Andric PrevF = F;
87501095a5dSDimitry Andric } else if (PrevF != F) {
87601095a5dSDimitry Andric R.Last = FunctionMDs.size();
87701095a5dSDimitry Andric std::swap(R, FunctionMDInfo[PrevF]);
87801095a5dSDimitry Andric R.First = FunctionMDs.size();
87901095a5dSDimitry Andric
88001095a5dSDimitry Andric ID = MDs.size();
88101095a5dSDimitry Andric PrevF = F;
88201095a5dSDimitry Andric }
88301095a5dSDimitry Andric
88401095a5dSDimitry Andric auto *MD = Order[I].get(OldMDs);
88501095a5dSDimitry Andric FunctionMDs.push_back(MD);
88601095a5dSDimitry Andric MetadataMap[MD].ID = ++ID;
88701095a5dSDimitry Andric if (isa<MDString>(MD))
88801095a5dSDimitry Andric ++R.NumStrings;
88901095a5dSDimitry Andric }
89001095a5dSDimitry Andric R.Last = FunctionMDs.size();
89101095a5dSDimitry Andric FunctionMDInfo[PrevF] = R;
89201095a5dSDimitry Andric }
89301095a5dSDimitry Andric
incorporateFunctionMetadata(const Function & F)89401095a5dSDimitry Andric void ValueEnumerator::incorporateFunctionMetadata(const Function &F) {
89501095a5dSDimitry Andric NumModuleMDs = MDs.size();
89601095a5dSDimitry Andric
89701095a5dSDimitry Andric auto R = FunctionMDInfo.lookup(getValueID(&F) + 1);
89801095a5dSDimitry Andric NumMDStrings = R.NumStrings;
89901095a5dSDimitry Andric MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
90001095a5dSDimitry Andric FunctionMDs.begin() + R.Last);
90159850d08SRoman Divacky }
90259850d08SRoman Divacky
EnumerateValue(const Value * V)903009b1c42SEd Schouten void ValueEnumerator::EnumerateValue(const Value *V) {
9041e7804dbSRoman Divacky assert(!V->getType()->isVoidTy() && "Can't insert void values!");
90567c32a98SDimitry Andric assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
906009b1c42SEd Schouten
907009b1c42SEd Schouten // Check to see if it's already in!
908009b1c42SEd Schouten unsigned &ValueID = ValueMap[V];
909009b1c42SEd Schouten if (ValueID) {
910009b1c42SEd Schouten // Increment use count.
911009b1c42SEd Schouten Values[ValueID-1].second++;
912009b1c42SEd Schouten return;
913009b1c42SEd Schouten }
914009b1c42SEd Schouten
9155ca98fd9SDimitry Andric if (auto *GO = dyn_cast<GlobalObject>(V))
9165ca98fd9SDimitry Andric if (const Comdat *C = GO->getComdat())
9175ca98fd9SDimitry Andric Comdats.insert(C);
9185ca98fd9SDimitry Andric
919009b1c42SEd Schouten // Enumerate the type of this value.
920009b1c42SEd Schouten EnumerateType(V->getType());
921009b1c42SEd Schouten
922009b1c42SEd Schouten if (const Constant *C = dyn_cast<Constant>(V)) {
923009b1c42SEd Schouten if (isa<GlobalValue>(C)) {
924009b1c42SEd Schouten // Initializers for globals are handled explicitly elsewhere.
925009b1c42SEd Schouten } else if (C->getNumOperands()) {
926009b1c42SEd Schouten // If a constant has operands, enumerate them. This makes sure that if a
927009b1c42SEd Schouten // constant has uses (for example an array of const ints), that they are
928009b1c42SEd Schouten // inserted also.
929009b1c42SEd Schouten
930009b1c42SEd Schouten // We prefer to enumerate them with values before we enumerate the user
931009b1c42SEd Schouten // itself. This makes it more likely that we can avoid forward references
932009b1c42SEd Schouten // in the reader. We know that there can be no cycles in the constants
933009b1c42SEd Schouten // graph that don't go through a global variable.
934ac9a064cSDimitry Andric for (const Use &U : C->operands())
935ac9a064cSDimitry Andric if (!isa<BasicBlock>(U)) // Don't enumerate BB operand to BlockAddress.
936ac9a064cSDimitry Andric EnumerateValue(U);
937145449b1SDimitry Andric if (auto *CE = dyn_cast<ConstantExpr>(C)) {
938cfca06d7SDimitry Andric if (CE->getOpcode() == Instruction::ShuffleVector)
939cfca06d7SDimitry Andric EnumerateValue(CE->getShuffleMaskForBitcode());
940145449b1SDimitry Andric if (auto *GEP = dyn_cast<GEPOperator>(CE))
941145449b1SDimitry Andric EnumerateType(GEP->getSourceElementType());
942145449b1SDimitry Andric }
943009b1c42SEd Schouten
944009b1c42SEd Schouten // Finally, add the value. Doing this could make the ValueID reference be
945009b1c42SEd Schouten // dangling, don't reuse it.
946009b1c42SEd Schouten Values.push_back(std::make_pair(V, 1U));
947009b1c42SEd Schouten ValueMap[V] = Values.size();
948009b1c42SEd Schouten return;
949009b1c42SEd Schouten }
950009b1c42SEd Schouten }
951009b1c42SEd Schouten
952009b1c42SEd Schouten // Add the value.
953009b1c42SEd Schouten Values.push_back(std::make_pair(V, 1U));
954009b1c42SEd Schouten ValueID = Values.size();
955009b1c42SEd Schouten }
956009b1c42SEd Schouten
957009b1c42SEd Schouten
EnumerateType(Type * Ty)95830815c53SDimitry Andric void ValueEnumerator::EnumerateType(Type *Ty) {
959411bd29eSDimitry Andric unsigned *TypeID = &TypeMap[Ty];
960009b1c42SEd Schouten
9616b943ff3SDimitry Andric // We've already seen this type.
962411bd29eSDimitry Andric if (*TypeID)
963009b1c42SEd Schouten return;
964009b1c42SEd Schouten
965411bd29eSDimitry Andric // If it is a non-anonymous struct, mark the type as being visited so that we
966411bd29eSDimitry Andric // don't recursively visit it. This is safe because we allow forward
967411bd29eSDimitry Andric // references of these in the bitcode reader.
96830815c53SDimitry Andric if (StructType *STy = dyn_cast<StructType>(Ty))
96930815c53SDimitry Andric if (!STy->isLiteral())
970411bd29eSDimitry Andric *TypeID = ~0U;
971009b1c42SEd Schouten
972411bd29eSDimitry Andric // Enumerate all of the subtypes before we enumerate this type. This ensures
973411bd29eSDimitry Andric // that the type will be enumerated in an order that can be directly built.
97467c32a98SDimitry Andric for (Type *SubTy : Ty->subtypes())
97567c32a98SDimitry Andric EnumerateType(SubTy);
976411bd29eSDimitry Andric
977411bd29eSDimitry Andric // Refresh the TypeID pointer in case the table rehashed.
978411bd29eSDimitry Andric TypeID = &TypeMap[Ty];
979411bd29eSDimitry Andric
980411bd29eSDimitry Andric // Check to see if we got the pointer another way. This can happen when
981411bd29eSDimitry Andric // enumerating recursive types that hit the base case deeper than they start.
982411bd29eSDimitry Andric //
983411bd29eSDimitry Andric // If this is actually a struct that we are treating as forward ref'able,
984411bd29eSDimitry Andric // then emit the definition now that all of its contents are available.
985411bd29eSDimitry Andric if (*TypeID && *TypeID != ~0U)
986411bd29eSDimitry Andric return;
987411bd29eSDimitry Andric
988411bd29eSDimitry Andric // Add this type now that its contents are all happily enumerated.
989411bd29eSDimitry Andric Types.push_back(Ty);
990411bd29eSDimitry Andric
991411bd29eSDimitry Andric *TypeID = Types.size();
992009b1c42SEd Schouten }
993009b1c42SEd Schouten
994009b1c42SEd Schouten // Enumerate the types for the specified value. If the value is a constant,
995009b1c42SEd Schouten // walk through it, enumerating the types of the constant.
EnumerateOperandType(const Value * V)996009b1c42SEd Schouten void ValueEnumerator::EnumerateOperandType(const Value *V) {
997009b1c42SEd Schouten EnumerateType(V->getType());
998829000e0SRoman Divacky
99901095a5dSDimitry Andric assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
100067c32a98SDimitry Andric
100167c32a98SDimitry Andric const Constant *C = dyn_cast<Constant>(V);
100267c32a98SDimitry Andric if (!C)
100367c32a98SDimitry Andric return;
100467c32a98SDimitry Andric
1005009b1c42SEd Schouten // If this constant is already enumerated, ignore it, we know its type must
1006009b1c42SEd Schouten // be enumerated.
100767c32a98SDimitry Andric if (ValueMap.count(C))
100867c32a98SDimitry Andric return;
1009009b1c42SEd Schouten
1010009b1c42SEd Schouten // This constant may have operands, make sure to enumerate the types in
1011009b1c42SEd Schouten // them.
10121a82d4c0SDimitry Andric for (const Value *Op : C->operands()) {
101336bf506aSRoman Divacky // Don't enumerate basic blocks here, this happens as operands to
101436bf506aSRoman Divacky // blockaddress.
101567c32a98SDimitry Andric if (isa<BasicBlock>(Op))
101667c32a98SDimitry Andric continue;
101736bf506aSRoman Divacky
1018d39c594dSDimitry Andric EnumerateOperandType(Op);
101936bf506aSRoman Divacky }
1020344a3780SDimitry Andric if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1021cfca06d7SDimitry Andric if (CE->getOpcode() == Instruction::ShuffleVector)
1022cfca06d7SDimitry Andric EnumerateOperandType(CE->getShuffleMaskForBitcode());
1023344a3780SDimitry Andric if (CE->getOpcode() == Instruction::GetElementPtr)
1024344a3780SDimitry Andric EnumerateType(cast<GEPOperator>(CE)->getSourceElementType());
1025344a3780SDimitry Andric }
1026009b1c42SEd Schouten }
1027009b1c42SEd Schouten
EnumerateAttributes(AttributeList PAL)102871d5a254SDimitry Andric void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
1029009b1c42SEd Schouten if (PAL.isEmpty()) return; // null is always 0.
10304a16efa3SDimitry Andric
1031009b1c42SEd Schouten // Do a lookup.
103212f3ca4cSDimitry Andric unsigned &Entry = AttributeListMap[PAL];
1033009b1c42SEd Schouten if (Entry == 0) {
1034009b1c42SEd Schouten // Never saw this before, add it.
103512f3ca4cSDimitry Andric AttributeLists.push_back(PAL);
103612f3ca4cSDimitry Andric Entry = AttributeLists.size();
10374a16efa3SDimitry Andric }
10384a16efa3SDimitry Andric
10394a16efa3SDimitry Andric // Do lookups for all attribute groups.
1040c0981da4SDimitry Andric for (unsigned i : PAL.indexes()) {
1041ab44ce3dSDimitry Andric AttributeSet AS = PAL.getAttributes(i);
1042ab44ce3dSDimitry Andric if (!AS.hasAttributes())
1043ab44ce3dSDimitry Andric continue;
1044ab44ce3dSDimitry Andric IndexAndAttrSet Pair = {i, AS};
104512f3ca4cSDimitry Andric unsigned &Entry = AttributeGroupMap[Pair];
10464a16efa3SDimitry Andric if (Entry == 0) {
104712f3ca4cSDimitry Andric AttributeGroups.push_back(Pair);
10484a16efa3SDimitry Andric Entry = AttributeGroups.size();
1049344a3780SDimitry Andric
1050344a3780SDimitry Andric for (Attribute Attr : AS) {
1051344a3780SDimitry Andric if (Attr.isTypeAttribute())
1052344a3780SDimitry Andric EnumerateType(Attr.getValueAsType());
1053344a3780SDimitry Andric }
10544a16efa3SDimitry Andric }
1055009b1c42SEd Schouten }
1056009b1c42SEd Schouten }
1057009b1c42SEd Schouten
incorporateFunction(const Function & F)1058009b1c42SEd Schouten void ValueEnumerator::incorporateFunction(const Function &F) {
105967a71b31SRoman Divacky InstructionCount = 0;
1060009b1c42SEd Schouten NumModuleValues = Values.size();
106101095a5dSDimitry Andric
106201095a5dSDimitry Andric // Add global metadata to the function block. This doesn't include
106301095a5dSDimitry Andric // LocalAsMetadata.
106401095a5dSDimitry Andric incorporateFunctionMetadata(F);
1065009b1c42SEd Schouten
1066009b1c42SEd Schouten // Adding function arguments to the value table.
1067e6d15924SDimitry Andric for (const auto &I : F.args()) {
1068dd58ef01SDimitry Andric EnumerateValue(&I);
1069e6d15924SDimitry Andric if (I.hasAttribute(Attribute::ByVal))
1070e6d15924SDimitry Andric EnumerateType(I.getParamByValType());
1071b60736ecSDimitry Andric else if (I.hasAttribute(Attribute::StructRet))
1072b60736ecSDimitry Andric EnumerateType(I.getParamStructRetType());
1073344a3780SDimitry Andric else if (I.hasAttribute(Attribute::ByRef))
1074344a3780SDimitry Andric EnumerateType(I.getParamByRefType());
1075e6d15924SDimitry Andric }
1076009b1c42SEd Schouten FirstFuncConstantID = Values.size();
1077009b1c42SEd Schouten
1078009b1c42SEd Schouten // Add all function-level constants to the value table.
1079dd58ef01SDimitry Andric for (const BasicBlock &BB : F) {
1080cfca06d7SDimitry Andric for (const Instruction &I : BB) {
1081dd58ef01SDimitry Andric for (const Use &OI : I.operands()) {
1082dd58ef01SDimitry Andric if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
1083dd58ef01SDimitry Andric EnumerateValue(OI);
1084009b1c42SEd Schouten }
1085cfca06d7SDimitry Andric if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
1086cfca06d7SDimitry Andric EnumerateValue(SVI->getShuffleMaskForBitcode());
1087cfca06d7SDimitry Andric }
1088dd58ef01SDimitry Andric BasicBlocks.push_back(&BB);
1089dd58ef01SDimitry Andric ValueMap[&BB] = BasicBlocks.size();
1090009b1c42SEd Schouten }
1091009b1c42SEd Schouten
1092009b1c42SEd Schouten // Optimize the constant layout.
1093009b1c42SEd Schouten OptimizeConstants(FirstFuncConstantID, Values.size());
1094009b1c42SEd Schouten
1095009b1c42SEd Schouten // Add the function's parameter attributes so they are available for use in
1096009b1c42SEd Schouten // the function's instruction.
1097009b1c42SEd Schouten EnumerateAttributes(F.getAttributes());
1098009b1c42SEd Schouten
1099009b1c42SEd Schouten FirstInstID = Values.size();
1100009b1c42SEd Schouten
110167c32a98SDimitry Andric SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
1102344a3780SDimitry Andric SmallVector<DIArgList *, 8> ArgListMDVector;
1103ac9a064cSDimitry Andric
1104ac9a064cSDimitry Andric auto AddFnLocalMetadata = [&](Metadata *MD) {
1105ac9a064cSDimitry Andric if (!MD)
1106ac9a064cSDimitry Andric return;
1107ac9a064cSDimitry Andric if (auto *Local = dyn_cast<LocalAsMetadata>(MD)) {
11086fe5c7aaSRoman Divacky // Enumerate metadata after the instructions they might refer to.
110967c32a98SDimitry Andric FnLocalMDVector.push_back(Local);
1110ac9a064cSDimitry Andric } else if (auto *ArgList = dyn_cast<DIArgList>(MD)) {
1111344a3780SDimitry Andric ArgListMDVector.push_back(ArgList);
1112344a3780SDimitry Andric for (ValueAsMetadata *VMD : ArgList->getArgs()) {
1113344a3780SDimitry Andric if (auto *Local = dyn_cast<LocalAsMetadata>(VMD)) {
1114344a3780SDimitry Andric // Enumerate metadata after the instructions they might refer
1115344a3780SDimitry Andric // to.
1116344a3780SDimitry Andric FnLocalMDVector.push_back(Local);
1117344a3780SDimitry Andric }
1118344a3780SDimitry Andric }
1119344a3780SDimitry Andric }
1120ac9a064cSDimitry Andric };
1121d39c594dSDimitry Andric
1122ac9a064cSDimitry Andric // Add all of the instructions.
1123ac9a064cSDimitry Andric for (const BasicBlock &BB : F) {
1124ac9a064cSDimitry Andric for (const Instruction &I : BB) {
1125ac9a064cSDimitry Andric for (const Use &OI : I.operands()) {
1126ac9a064cSDimitry Andric if (auto *MD = dyn_cast<MetadataAsValue>(&OI))
1127ac9a064cSDimitry Andric AddFnLocalMetadata(MD->getMetadata());
1128ac9a064cSDimitry Andric }
1129ac9a064cSDimitry Andric /// RemoveDIs: Add non-instruction function-local metadata uses.
1130ac9a064cSDimitry Andric for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
1131ac9a064cSDimitry Andric assert(DVR.getRawLocation() &&
1132ac9a064cSDimitry Andric "DbgVariableRecord location unexpectedly null");
1133ac9a064cSDimitry Andric AddFnLocalMetadata(DVR.getRawLocation());
1134ac9a064cSDimitry Andric if (DVR.isDbgAssign()) {
1135ac9a064cSDimitry Andric assert(DVR.getRawAddress() &&
1136ac9a064cSDimitry Andric "DbgVariableRecord location unexpectedly null");
1137ac9a064cSDimitry Andric AddFnLocalMetadata(DVR.getRawAddress());
1138ac9a064cSDimitry Andric }
1139ac9a064cSDimitry Andric }
1140dd58ef01SDimitry Andric if (!I.getType()->isVoidTy())
1141dd58ef01SDimitry Andric EnumerateValue(&I);
1142009b1c42SEd Schouten }
1143009b1c42SEd Schouten }
11446fe5c7aaSRoman Divacky
11456fe5c7aaSRoman Divacky // Add all of the function-local metadata.
1146ac9a064cSDimitry Andric for (const LocalAsMetadata *Local : FnLocalMDVector) {
114701095a5dSDimitry Andric // At this point, every local values have been incorporated, we shouldn't
114801095a5dSDimitry Andric // have a metadata operand that references a value that hasn't been seen.
1149ac9a064cSDimitry Andric assert(ValueMap.count(Local->getValue()) &&
115001095a5dSDimitry Andric "Missing value for metadata operand");
1151ac9a064cSDimitry Andric EnumerateFunctionLocalMetadata(F, Local);
115201095a5dSDimitry Andric }
1153344a3780SDimitry Andric // DIArgList entries must come after function-local metadata, as it is not
1154344a3780SDimitry Andric // possible to forward-reference them.
1155344a3780SDimitry Andric for (const DIArgList *ArgList : ArgListMDVector)
1156344a3780SDimitry Andric EnumerateFunctionLocalListMetadata(F, ArgList);
1157009b1c42SEd Schouten }
1158009b1c42SEd Schouten
purgeFunction()1159009b1c42SEd Schouten void ValueEnumerator::purgeFunction() {
1160009b1c42SEd Schouten /// Remove purged values from the ValueMap.
1161ac9a064cSDimitry Andric for (const auto &V : llvm::drop_begin(Values, NumModuleValues))
1162ac9a064cSDimitry Andric ValueMap.erase(V.first);
11634df029ccSDimitry Andric for (const Metadata *MD : llvm::drop_begin(MDs, NumModuleMDs))
11644df029ccSDimitry Andric MetadataMap.erase(MD);
1165f65dcba8SDimitry Andric for (const BasicBlock *BB : BasicBlocks)
1166f65dcba8SDimitry Andric ValueMap.erase(BB);
1167009b1c42SEd Schouten
1168009b1c42SEd Schouten Values.resize(NumModuleValues);
116967c32a98SDimitry Andric MDs.resize(NumModuleMDs);
1170009b1c42SEd Schouten BasicBlocks.clear();
117101095a5dSDimitry Andric NumMDStrings = 0;
1172009b1c42SEd Schouten }
117336bf506aSRoman Divacky
IncorporateFunctionInfoGlobalBBIDs(const Function * F,DenseMap<const BasicBlock *,unsigned> & IDMap)117436bf506aSRoman Divacky static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
117536bf506aSRoman Divacky DenseMap<const BasicBlock*, unsigned> &IDMap) {
117636bf506aSRoman Divacky unsigned Counter = 0;
1177dd58ef01SDimitry Andric for (const BasicBlock &BB : *F)
1178dd58ef01SDimitry Andric IDMap[&BB] = ++Counter;
117936bf506aSRoman Divacky }
118036bf506aSRoman Divacky
118136bf506aSRoman Divacky /// getGlobalBasicBlockID - This returns the function-specific ID for the
118236bf506aSRoman Divacky /// specified basic block. This is relatively expensive information, so it
118336bf506aSRoman Divacky /// should only be used by rare constructs such as address-of-label.
getGlobalBasicBlockID(const BasicBlock * BB) const118436bf506aSRoman Divacky unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
118536bf506aSRoman Divacky unsigned &Idx = GlobalBasicBlockIDs[BB];
118636bf506aSRoman Divacky if (Idx != 0)
118736bf506aSRoman Divacky return Idx-1;
118836bf506aSRoman Divacky
118936bf506aSRoman Divacky IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
119036bf506aSRoman Divacky return getGlobalBasicBlockID(BB);
119136bf506aSRoman Divacky }
11925a5ac124SDimitry Andric
computeBitsRequiredForTypeIndices() const1193ac9a064cSDimitry Andric uint64_t ValueEnumerator::computeBitsRequiredForTypeIndices() const {
11945a5ac124SDimitry Andric return Log2_32_Ceil(getTypes().size() + 1);
11955a5ac124SDimitry Andric }
1196