xref: /llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp (revision d9fe96fe264e72c0a5c58cdd40b4efa14d18f475)
1 //===- ValueEnumerator.cpp - Number values and types for bitcode writer ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the ValueEnumerator class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ValueEnumerator.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/Config/llvm-config.h"
16 #include "llvm/IR/Argument.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/Constant.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GlobalAlias.h"
23 #include "llvm/IR/GlobalIFunc.h"
24 #include "llvm/IR/GlobalObject.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Use.h"
34 #include "llvm/IR/User.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/IR/ValueSymbolTable.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <algorithm>
43 #include <cstddef>
44 #include <iterator>
45 #include <tuple>
46 
47 using namespace llvm;
48 
49 namespace {
50 
51 struct OrderMap {
52   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
53   unsigned LastGlobalConstantID = 0;
54   unsigned LastGlobalValueID = 0;
55 
56   OrderMap() = default;
57 
58   bool isGlobalConstant(unsigned ID) const {
59     return ID <= LastGlobalConstantID;
60   }
61 
62   bool isGlobalValue(unsigned ID) const {
63     return ID <= LastGlobalValueID && !isGlobalConstant(ID);
64   }
65 
66   unsigned size() const { return IDs.size(); }
67   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
68 
69   std::pair<unsigned, bool> lookup(const Value *V) const {
70     return IDs.lookup(V);
71   }
72 
73   void index(const Value *V) {
74     // Explicitly sequence get-size and insert-value operations to avoid UB.
75     unsigned ID = IDs.size() + 1;
76     IDs[V].first = ID;
77   }
78 };
79 
80 } // end anonymous namespace
81 
82 static void orderValue(const Value *V, OrderMap &OM) {
83   if (OM.lookup(V).first)
84     return;
85 
86   if (const Constant *C = dyn_cast<Constant>(V)) {
87     if (C->getNumOperands() && !isa<GlobalValue>(C)) {
88       for (const Value *Op : C->operands())
89         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
90           orderValue(Op, OM);
91       if (auto *CE = dyn_cast<ConstantExpr>(C))
92         if (CE->getOpcode() == Instruction::ShuffleVector)
93           orderValue(CE->getShuffleMaskForBitcode(), OM);
94     }
95   }
96 
97   // Note: we cannot cache this lookup above, since inserting into the map
98   // changes the map's size, and thus affects the other IDs.
99   OM.index(V);
100 }
101 
102 static OrderMap orderModule(const Module &M) {
103   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
104   // and ValueEnumerator::incorporateFunction().
105   OrderMap OM;
106 
107   // In the reader, initializers of GlobalValues are set *after* all the
108   // globals have been read.  Rather than awkwardly modeling this behaviour
109   // directly in predictValueUseListOrderImpl(), just assign IDs to
110   // initializers of GlobalValues before GlobalValues themselves to model this
111   // implicitly.
112   for (const GlobalVariable &G : M.globals())
113     if (G.hasInitializer())
114       if (!isa<GlobalValue>(G.getInitializer()))
115         orderValue(G.getInitializer(), OM);
116   for (const GlobalAlias &A : M.aliases())
117     if (!isa<GlobalValue>(A.getAliasee()))
118       orderValue(A.getAliasee(), OM);
119   for (const GlobalIFunc &I : M.ifuncs())
120     if (!isa<GlobalValue>(I.getResolver()))
121       orderValue(I.getResolver(), OM);
122   for (const Function &F : M) {
123     for (const Use &U : F.operands())
124       if (!isa<GlobalValue>(U.get()))
125         orderValue(U.get(), OM);
126   }
127 
128   // As constants used in metadata operands are emitted as module-level
129   // constants, we must order them before other operands. Also, we must order
130   // these before global values, as these will be read before setting the
131   // global values' initializers. The latter matters for constants which have
132   // uses towards other constants that are used as initializers.
133   auto orderConstantValue = [&OM](const Value *V) {
134     if ((isa<Constant>(V) && !isa<GlobalValue>(V)) || isa<InlineAsm>(V))
135       orderValue(V, OM);
136   };
137   for (const Function &F : M) {
138     if (F.isDeclaration())
139       continue;
140     for (const BasicBlock &BB : F)
141       for (const Instruction &I : BB)
142         for (const Value *V : I.operands()) {
143           if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
144             if (const auto *VAM =
145                     dyn_cast<ValueAsMetadata>(MAV->getMetadata())) {
146               orderConstantValue(VAM->getValue());
147             } else if (const auto *AL =
148                            dyn_cast<DIArgList>(MAV->getMetadata())) {
149               for (const auto *VAM : AL->getArgs())
150                 orderConstantValue(VAM->getValue());
151             }
152           }
153         }
154   }
155   OM.LastGlobalConstantID = OM.size();
156 
157   // Initializers of GlobalValues are processed in
158   // BitcodeReader::ResolveGlobalAndAliasInits().  Match the order there rather
159   // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
160   // by giving IDs in reverse order.
161   //
162   // Since GlobalValues never reference each other directly (just through
163   // initializers), their relative IDs only matter for determining order of
164   // uses in their initializers.
165   for (const Function &F : M)
166     orderValue(&F, OM);
167   for (const GlobalAlias &A : M.aliases())
168     orderValue(&A, OM);
169   for (const GlobalIFunc &I : M.ifuncs())
170     orderValue(&I, OM);
171   for (const GlobalVariable &G : M.globals())
172     orderValue(&G, OM);
173   OM.LastGlobalValueID = OM.size();
174 
175   for (const Function &F : M) {
176     if (F.isDeclaration())
177       continue;
178     // Here we need to match the union of ValueEnumerator::incorporateFunction()
179     // and WriteFunction().  Basic blocks are implicitly declared before
180     // anything else (by declaring their size).
181     for (const BasicBlock &BB : F)
182       orderValue(&BB, OM);
183     for (const Argument &A : F.args())
184       orderValue(&A, OM);
185     for (const BasicBlock &BB : F)
186       for (const Instruction &I : BB) {
187         for (const Value *Op : I.operands())
188           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
189               isa<InlineAsm>(*Op))
190             orderValue(Op, OM);
191         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
192           orderValue(SVI->getShuffleMaskForBitcode(), OM);
193       }
194     for (const BasicBlock &BB : F)
195       for (const Instruction &I : BB)
196         orderValue(&I, OM);
197   }
198   return OM;
199 }
200 
201 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
202                                          unsigned ID, const OrderMap &OM,
203                                          UseListOrderStack &Stack) {
204   // Predict use-list order for this one.
205   using Entry = std::pair<const Use *, unsigned>;
206   SmallVector<Entry, 64> List;
207   for (const Use &U : V->uses())
208     // Check if this user will be serialized.
209     if (OM.lookup(U.getUser()).first)
210       List.push_back(std::make_pair(&U, List.size()));
211 
212   if (List.size() < 2)
213     // We may have lost some users.
214     return;
215 
216   bool IsGlobalValue = OM.isGlobalValue(ID);
217   llvm::sort(List, [&](const Entry &L, const Entry &R) {
218     const Use *LU = L.first;
219     const Use *RU = R.first;
220     if (LU == RU)
221       return false;
222 
223     auto LID = OM.lookup(LU->getUser()).first;
224     auto RID = OM.lookup(RU->getUser()).first;
225 
226     // Global values are processed in reverse order.
227     //
228     // Moreover, initializers of GlobalValues are set *after* all the globals
229     // have been read (despite having earlier IDs).  Rather than awkwardly
230     // modeling this behaviour here, orderModule() has assigned IDs to
231     // initializers of GlobalValues before GlobalValues themselves.
232     if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
233       return LID < RID;
234 
235     // If ID is 4, then expect: 7 6 5 1 2 3.
236     if (LID < RID) {
237       if (RID <= ID)
238         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
239           return true;
240       return false;
241     }
242     if (RID < LID) {
243       if (LID <= ID)
244         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
245           return false;
246       return true;
247     }
248 
249     // LID and RID are equal, so we have different operands of the same user.
250     // Assume operands are added in order for all instructions.
251     if (LID <= ID)
252       if (!IsGlobalValue) // GlobalValue uses don't get reversed.
253         return LU->getOperandNo() < RU->getOperandNo();
254     return LU->getOperandNo() > RU->getOperandNo();
255   });
256 
257   if (llvm::is_sorted(List, [](const Entry &L, const Entry &R) {
258         return L.second < R.second;
259       }))
260     // Order is already correct.
261     return;
262 
263   // Store the shuffle.
264   Stack.emplace_back(V, F, List.size());
265   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
266   for (size_t I = 0, E = List.size(); I != E; ++I)
267     Stack.back().Shuffle[I] = List[I].second;
268 }
269 
270 static void predictValueUseListOrder(const Value *V, const Function *F,
271                                      OrderMap &OM, UseListOrderStack &Stack) {
272   auto &IDPair = OM[V];
273   assert(IDPair.first && "Unmapped value");
274   if (IDPair.second)
275     // Already predicted.
276     return;
277 
278   // Do the actual prediction.
279   IDPair.second = true;
280   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
281     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
282 
283   // Recursive descent into constants.
284   if (const Constant *C = dyn_cast<Constant>(V)) {
285     if (C->getNumOperands()) { // Visit GlobalValues.
286       for (const Value *Op : C->operands())
287         if (isa<Constant>(Op)) // Visit GlobalValues.
288           predictValueUseListOrder(Op, F, OM, Stack);
289       if (auto *CE = dyn_cast<ConstantExpr>(C))
290         if (CE->getOpcode() == Instruction::ShuffleVector)
291           predictValueUseListOrder(CE->getShuffleMaskForBitcode(), F, OM,
292                                    Stack);
293     }
294   }
295 }
296 
297 static UseListOrderStack predictUseListOrder(const Module &M) {
298   OrderMap OM = orderModule(M);
299 
300   // Use-list orders need to be serialized after all the users have been added
301   // to a value, or else the shuffles will be incomplete.  Store them per
302   // function in a stack.
303   //
304   // Aside from function order, the order of values doesn't matter much here.
305   UseListOrderStack Stack;
306 
307   // We want to visit the functions backward now so we can list function-local
308   // constants in the last Function they're used in.  Module-level constants
309   // have already been visited above.
310   for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
311     const Function &F = *I;
312     if (F.isDeclaration())
313       continue;
314     for (const BasicBlock &BB : F)
315       predictValueUseListOrder(&BB, &F, OM, Stack);
316     for (const Argument &A : F.args())
317       predictValueUseListOrder(&A, &F, OM, Stack);
318     for (const BasicBlock &BB : F)
319       for (const Instruction &I : BB) {
320         for (const Value *Op : I.operands())
321           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
322             predictValueUseListOrder(Op, &F, OM, Stack);
323         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
324           predictValueUseListOrder(SVI->getShuffleMaskForBitcode(), &F, OM,
325                                    Stack);
326       }
327     for (const BasicBlock &BB : F)
328       for (const Instruction &I : BB)
329         predictValueUseListOrder(&I, &F, OM, Stack);
330   }
331 
332   // Visit globals last, since the module-level use-list block will be seen
333   // before the function bodies are processed.
334   for (const GlobalVariable &G : M.globals())
335     predictValueUseListOrder(&G, nullptr, OM, Stack);
336   for (const Function &F : M)
337     predictValueUseListOrder(&F, nullptr, OM, Stack);
338   for (const GlobalAlias &A : M.aliases())
339     predictValueUseListOrder(&A, nullptr, OM, Stack);
340   for (const GlobalIFunc &I : M.ifuncs())
341     predictValueUseListOrder(&I, nullptr, OM, Stack);
342   for (const GlobalVariable &G : M.globals())
343     if (G.hasInitializer())
344       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
345   for (const GlobalAlias &A : M.aliases())
346     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
347   for (const GlobalIFunc &I : M.ifuncs())
348     predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
349   for (const Function &F : M) {
350     for (const Use &U : F.operands())
351       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
352   }
353 
354   return Stack;
355 }
356 
357 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
358   return V.first->getType()->isIntOrIntVectorTy();
359 }
360 
361 ValueEnumerator::ValueEnumerator(const Module &M,
362                                  bool ShouldPreserveUseListOrder)
363     : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
364   if (ShouldPreserveUseListOrder)
365     UseListOrders = predictUseListOrder(M);
366 
367   // Enumerate the global variables.
368   for (const GlobalVariable &GV : M.globals())
369     EnumerateValue(&GV);
370 
371   // Enumerate the functions.
372   for (const Function & F : M) {
373     EnumerateValue(&F);
374     EnumerateAttributes(F.getAttributes());
375   }
376 
377   // Enumerate the aliases.
378   for (const GlobalAlias &GA : M.aliases())
379     EnumerateValue(&GA);
380 
381   // Enumerate the ifuncs.
382   for (const GlobalIFunc &GIF : M.ifuncs())
383     EnumerateValue(&GIF);
384 
385   // Remember what is the cutoff between globalvalue's and other constants.
386   unsigned FirstConstant = Values.size();
387 
388   // Enumerate the global variable initializers and attributes.
389   for (const GlobalVariable &GV : M.globals()) {
390     if (GV.hasInitializer())
391       EnumerateValue(GV.getInitializer());
392     if (GV.hasAttributes())
393       EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
394   }
395 
396   // Enumerate the aliasees.
397   for (const GlobalAlias &GA : M.aliases())
398     EnumerateValue(GA.getAliasee());
399 
400   // Enumerate the ifunc resolvers.
401   for (const GlobalIFunc &GIF : M.ifuncs())
402     EnumerateValue(GIF.getResolver());
403 
404   // Enumerate any optional Function data.
405   for (const Function &F : M)
406     for (const Use &U : F.operands())
407       EnumerateValue(U.get());
408 
409   // Enumerate the metadata type.
410   //
411   // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
412   // only encodes the metadata type when it's used as a value.
413   EnumerateType(Type::getMetadataTy(M.getContext()));
414 
415   // Insert constants and metadata that are named at module level into the slot
416   // pool so that the module symbol table can refer to them...
417   EnumerateValueSymbolTable(M.getValueSymbolTable());
418   EnumerateNamedMetadata(M);
419 
420   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
421   for (const GlobalVariable &GV : M.globals()) {
422     MDs.clear();
423     GV.getAllMetadata(MDs);
424     for (const auto &I : MDs)
425       // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer
426       // to write metadata to the global variable's own metadata block
427       // (PR28134).
428       EnumerateMetadata(nullptr, I.second);
429   }
430 
431   // Enumerate types used by function bodies and argument lists.
432   for (const Function &F : M) {
433     for (const Argument &A : F.args())
434       EnumerateType(A.getType());
435 
436     // Enumerate metadata attached to this function.
437     MDs.clear();
438     F.getAllMetadata(MDs);
439     for (const auto &I : MDs)
440       EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second);
441 
442     for (const BasicBlock &BB : F)
443       for (const Instruction &I : BB) {
444         for (const Use &Op : I.operands()) {
445           auto *MD = dyn_cast<MetadataAsValue>(&Op);
446           if (!MD) {
447             EnumerateOperandType(Op);
448             continue;
449           }
450 
451           // Local metadata is enumerated during function-incorporation, but
452           // any ConstantAsMetadata arguments in a DIArgList should be examined
453           // now.
454           if (isa<LocalAsMetadata>(MD->getMetadata()))
455             continue;
456           if (auto *AL = dyn_cast<DIArgList>(MD->getMetadata())) {
457             for (auto *VAM : AL->getArgs())
458               if (isa<ConstantAsMetadata>(VAM))
459                 EnumerateMetadata(&F, VAM);
460             continue;
461           }
462 
463           EnumerateMetadata(&F, MD->getMetadata());
464         }
465         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
466           EnumerateType(SVI->getShuffleMaskForBitcode()->getType());
467         if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
468           EnumerateType(GEP->getSourceElementType());
469         EnumerateType(I.getType());
470         if (const auto *Call = dyn_cast<CallBase>(&I))
471           EnumerateAttributes(Call->getAttributes());
472 
473         // Enumerate metadata attached with this instruction.
474         MDs.clear();
475         I.getAllMetadataOtherThanDebugLoc(MDs);
476         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
477           EnumerateMetadata(&F, MDs[i].second);
478 
479         // Don't enumerate the location directly -- it has a special record
480         // type -- but enumerate its operands.
481         if (DILocation *L = I.getDebugLoc())
482           for (const Metadata *Op : L->operands())
483             EnumerateMetadata(&F, Op);
484       }
485   }
486 
487   // Optimize constant ordering.
488   OptimizeConstants(FirstConstant, Values.size());
489 
490   // Organize metadata ordering.
491   organizeMetadata();
492 }
493 
494 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
495   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
496   assert(I != InstructionMap.end() && "Instruction is not mapped!");
497   return I->second;
498 }
499 
500 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
501   unsigned ComdatID = Comdats.idFor(C);
502   assert(ComdatID && "Comdat not found!");
503   return ComdatID;
504 }
505 
506 void ValueEnumerator::setInstructionID(const Instruction *I) {
507   InstructionMap[I] = InstructionCount++;
508 }
509 
510 unsigned ValueEnumerator::getValueID(const Value *V) const {
511   if (auto *MD = dyn_cast<MetadataAsValue>(V))
512     return getMetadataID(MD->getMetadata());
513 
514   ValueMapType::const_iterator I = ValueMap.find(V);
515   assert(I != ValueMap.end() && "Value not in slotcalculator!");
516   return I->second-1;
517 }
518 
519 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
520 LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
521   print(dbgs(), ValueMap, "Default");
522   dbgs() << '\n';
523   print(dbgs(), MetadataMap, "MetaData");
524   dbgs() << '\n';
525 }
526 #endif
527 
528 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
529                             const char *Name) const {
530   OS << "Map Name: " << Name << "\n";
531   OS << "Size: " << Map.size() << "\n";
532   for (ValueMapType::const_iterator I = Map.begin(),
533          E = Map.end(); I != E; ++I) {
534     const Value *V = I->first;
535     if (V->hasName())
536       OS << "Value: " << V->getName();
537     else
538       OS << "Value: [null]\n";
539     V->print(errs());
540     errs() << '\n';
541 
542     OS << " Uses(" << V->getNumUses() << "):";
543     for (const Use &U : V->uses()) {
544       if (&U != &*V->use_begin())
545         OS << ",";
546       if(U->hasName())
547         OS << " " << U->getName();
548       else
549         OS << " [null]";
550 
551     }
552     OS <<  "\n\n";
553   }
554 }
555 
556 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
557                             const char *Name) const {
558   OS << "Map Name: " << Name << "\n";
559   OS << "Size: " << Map.size() << "\n";
560   for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
561     const Metadata *MD = I->first;
562     OS << "Metadata: slot = " << I->second.ID << "\n";
563     OS << "Metadata: function = " << I->second.F << "\n";
564     MD->print(OS);
565     OS << "\n";
566   }
567 }
568 
569 /// OptimizeConstants - Reorder constant pool for denser encoding.
570 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
571   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
572 
573   if (ShouldPreserveUseListOrder)
574     // Optimizing constants makes the use-list order difficult to predict.
575     // Disable it for now when trying to preserve the order.
576     return;
577 
578   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
579                    [this](const std::pair<const Value *, unsigned> &LHS,
580                           const std::pair<const Value *, unsigned> &RHS) {
581     // Sort by plane.
582     if (LHS.first->getType() != RHS.first->getType())
583       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
584     // Then by frequency.
585     return LHS.second > RHS.second;
586   });
587 
588   // Ensure that integer and vector of integer constants are at the start of the
589   // constant pool.  This is important so that GEP structure indices come before
590   // gep constant exprs.
591   std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
592                         isIntOrIntVectorValue);
593 
594   // Rebuild the modified portion of ValueMap.
595   for (; CstStart != CstEnd; ++CstStart)
596     ValueMap[Values[CstStart].first] = CstStart+1;
597 }
598 
599 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
600 /// table into the values table.
601 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
602   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
603        VI != VE; ++VI)
604     EnumerateValue(VI->getValue());
605 }
606 
607 /// Insert all of the values referenced by named metadata in the specified
608 /// module.
609 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
610   for (const auto &I : M.named_metadata())
611     EnumerateNamedMDNode(&I);
612 }
613 
614 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
615   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
616     EnumerateMetadata(nullptr, MD->getOperand(i));
617 }
618 
619 unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const {
620   return F ? getValueID(F) + 1 : 0;
621 }
622 
623 void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) {
624   EnumerateMetadata(getMetadataFunctionID(F), MD);
625 }
626 
627 void ValueEnumerator::EnumerateFunctionLocalMetadata(
628     const Function &F, const LocalAsMetadata *Local) {
629   EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
630 }
631 
632 void ValueEnumerator::EnumerateFunctionLocalListMetadata(
633     const Function &F, const DIArgList *ArgList) {
634   EnumerateFunctionLocalListMetadata(getMetadataFunctionID(&F), ArgList);
635 }
636 
637 void ValueEnumerator::dropFunctionFromMetadata(
638     MetadataMapType::value_type &FirstMD) {
639   SmallVector<const MDNode *, 64> Worklist;
640   auto push = [&Worklist](MetadataMapType::value_type &MD) {
641     auto &Entry = MD.second;
642 
643     // Nothing to do if this metadata isn't tagged.
644     if (!Entry.F)
645       return;
646 
647     // Drop the function tag.
648     Entry.F = 0;
649 
650     // If this is has an ID and is an MDNode, then its operands have entries as
651     // well.  We need to drop the function from them too.
652     if (Entry.ID)
653       if (auto *N = dyn_cast<MDNode>(MD.first))
654         Worklist.push_back(N);
655   };
656   push(FirstMD);
657   while (!Worklist.empty())
658     for (const Metadata *Op : Worklist.pop_back_val()->operands()) {
659       if (!Op)
660         continue;
661       auto MD = MetadataMap.find(Op);
662       if (MD != MetadataMap.end())
663         push(*MD);
664     }
665 }
666 
667 void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) {
668   // It's vital for reader efficiency that uniqued subgraphs are done in
669   // post-order; it's expensive when their operands have forward references.
670   // If a distinct node is referenced from a uniqued node, it'll be delayed
671   // until the uniqued subgraph has been completely traversed.
672   SmallVector<const MDNode *, 32> DelayedDistinctNodes;
673 
674   // Start by enumerating MD, and then work through its transitive operands in
675   // post-order.  This requires a depth-first search.
676   SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist;
677   if (const MDNode *N = enumerateMetadataImpl(F, MD))
678     Worklist.push_back(std::make_pair(N, N->op_begin()));
679 
680   while (!Worklist.empty()) {
681     const MDNode *N = Worklist.back().first;
682 
683     // Enumerate operands until we hit a new node.  We need to traverse these
684     // nodes' operands before visiting the rest of N's operands.
685     MDNode::op_iterator I = std::find_if(
686         Worklist.back().second, N->op_end(),
687         [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
688     if (I != N->op_end()) {
689       auto *Op = cast<MDNode>(*I);
690       Worklist.back().second = ++I;
691 
692       // Delay traversing Op if it's a distinct node and N is uniqued.
693       if (Op->isDistinct() && !N->isDistinct())
694         DelayedDistinctNodes.push_back(Op);
695       else
696         Worklist.push_back(std::make_pair(Op, Op->op_begin()));
697       continue;
698     }
699 
700     // All the operands have been visited.  Now assign an ID.
701     Worklist.pop_back();
702     MDs.push_back(N);
703     MetadataMap[N].ID = MDs.size();
704 
705     // Flush out any delayed distinct nodes; these are all the distinct nodes
706     // that are leaves in last uniqued subgraph.
707     if (Worklist.empty() || Worklist.back().first->isDistinct()) {
708       for (const MDNode *N : DelayedDistinctNodes)
709         Worklist.push_back(std::make_pair(N, N->op_begin()));
710       DelayedDistinctNodes.clear();
711     }
712   }
713 }
714 
715 const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F, const Metadata *MD) {
716   if (!MD)
717     return nullptr;
718 
719   assert(
720       (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
721       "Invalid metadata kind");
722 
723   auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F)));
724   MDIndex &Entry = Insertion.first->second;
725   if (!Insertion.second) {
726     // Already mapped.  If F doesn't match the function tag, drop it.
727     if (Entry.hasDifferentFunction(F))
728       dropFunctionFromMetadata(*Insertion.first);
729     return nullptr;
730   }
731 
732   // Don't assign IDs to metadata nodes.
733   if (auto *N = dyn_cast<MDNode>(MD))
734     return N;
735 
736   // Save the metadata.
737   MDs.push_back(MD);
738   Entry.ID = MDs.size();
739 
740   // Enumerate the constant, if any.
741   if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
742     EnumerateValue(C->getValue());
743 
744   return nullptr;
745 }
746 
747 /// EnumerateFunctionLocalMetadata - Incorporate function-local metadata
748 /// information reachable from the metadata.
749 void ValueEnumerator::EnumerateFunctionLocalMetadata(
750     unsigned F, const LocalAsMetadata *Local) {
751   assert(F && "Expected a function");
752 
753   // Check to see if it's already in!
754   MDIndex &Index = MetadataMap[Local];
755   if (Index.ID) {
756     assert(Index.F == F && "Expected the same function");
757     return;
758   }
759 
760   MDs.push_back(Local);
761   Index.F = F;
762   Index.ID = MDs.size();
763 
764   EnumerateValue(Local->getValue());
765 }
766 
767 /// EnumerateFunctionLocalListMetadata - Incorporate function-local metadata
768 /// information reachable from the metadata.
769 void ValueEnumerator::EnumerateFunctionLocalListMetadata(
770     unsigned F, const DIArgList *ArgList) {
771   assert(F && "Expected a function");
772 
773   // Check to see if it's already in!
774   MDIndex &Index = MetadataMap[ArgList];
775   if (Index.ID) {
776     assert(Index.F == F && "Expected the same function");
777     return;
778   }
779 
780   for (ValueAsMetadata *VAM : ArgList->getArgs()) {
781     if (isa<LocalAsMetadata>(VAM)) {
782       assert(MetadataMap.count(VAM) &&
783              "LocalAsMetadata should be enumerated before DIArgList");
784       assert(MetadataMap[VAM].F == F &&
785              "Expected LocalAsMetadata in the same function");
786     } else {
787       assert(isa<ConstantAsMetadata>(VAM) &&
788              "Expected LocalAsMetadata or ConstantAsMetadata");
789       assert(ValueMap.count(VAM->getValue()) &&
790              "Constant should be enumerated beforeDIArgList");
791       EnumerateMetadata(F, VAM);
792     }
793   }
794 
795   MDs.push_back(ArgList);
796   Index.F = F;
797   Index.ID = MDs.size();
798 }
799 
800 static unsigned getMetadataTypeOrder(const Metadata *MD) {
801   // Strings are emitted in bulk and must come first.
802   if (isa<MDString>(MD))
803     return 0;
804 
805   // ConstantAsMetadata doesn't reference anything.  We may as well shuffle it
806   // to the front since we can detect it.
807   auto *N = dyn_cast<MDNode>(MD);
808   if (!N)
809     return 1;
810 
811   // The reader is fast forward references for distinct node operands, but slow
812   // when uniqued operands are unresolved.
813   return N->isDistinct() ? 2 : 3;
814 }
815 
816 void ValueEnumerator::organizeMetadata() {
817   assert(MetadataMap.size() == MDs.size() &&
818          "Metadata map and vector out of sync");
819 
820   if (MDs.empty())
821     return;
822 
823   // Copy out the index information from MetadataMap in order to choose a new
824   // order.
825   SmallVector<MDIndex, 64> Order;
826   Order.reserve(MetadataMap.size());
827   for (const Metadata *MD : MDs)
828     Order.push_back(MetadataMap.lookup(MD));
829 
830   // Partition:
831   //   - by function, then
832   //   - by isa<MDString>
833   // and then sort by the original/current ID.  Since the IDs are guaranteed to
834   // be unique, the result of std::sort will be deterministic.  There's no need
835   // for std::stable_sort.
836   llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
837     return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <
838            std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID);
839   });
840 
841   // Rebuild MDs, index the metadata ranges for each function in FunctionMDs,
842   // and fix up MetadataMap.
843   std::vector<const Metadata *> OldMDs;
844   MDs.swap(OldMDs);
845   MDs.reserve(OldMDs.size());
846   for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) {
847     auto *MD = Order[I].get(OldMDs);
848     MDs.push_back(MD);
849     MetadataMap[MD].ID = I + 1;
850     if (isa<MDString>(MD))
851       ++NumMDStrings;
852   }
853 
854   // Return early if there's nothing for the functions.
855   if (MDs.size() == Order.size())
856     return;
857 
858   // Build the function metadata ranges.
859   MDRange R;
860   FunctionMDs.reserve(OldMDs.size());
861   unsigned PrevF = 0;
862   for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E;
863        ++I) {
864     unsigned F = Order[I].F;
865     if (!PrevF) {
866       PrevF = F;
867     } else if (PrevF != F) {
868       R.Last = FunctionMDs.size();
869       std::swap(R, FunctionMDInfo[PrevF]);
870       R.First = FunctionMDs.size();
871 
872       ID = MDs.size();
873       PrevF = F;
874     }
875 
876     auto *MD = Order[I].get(OldMDs);
877     FunctionMDs.push_back(MD);
878     MetadataMap[MD].ID = ++ID;
879     if (isa<MDString>(MD))
880       ++R.NumStrings;
881   }
882   R.Last = FunctionMDs.size();
883   FunctionMDInfo[PrevF] = R;
884 }
885 
886 void ValueEnumerator::incorporateFunctionMetadata(const Function &F) {
887   NumModuleMDs = MDs.size();
888 
889   auto R = FunctionMDInfo.lookup(getValueID(&F) + 1);
890   NumMDStrings = R.NumStrings;
891   MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
892              FunctionMDs.begin() + R.Last);
893 }
894 
895 void ValueEnumerator::EnumerateValue(const Value *V) {
896   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
897   assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
898 
899   // Check to see if it's already in!
900   unsigned &ValueID = ValueMap[V];
901   if (ValueID) {
902     // Increment use count.
903     Values[ValueID-1].second++;
904     return;
905   }
906 
907   if (auto *GO = dyn_cast<GlobalObject>(V))
908     if (const Comdat *C = GO->getComdat())
909       Comdats.insert(C);
910 
911   // Enumerate the type of this value.
912   EnumerateType(V->getType());
913 
914   if (const Constant *C = dyn_cast<Constant>(V)) {
915     if (isa<GlobalValue>(C)) {
916       // Initializers for globals are handled explicitly elsewhere.
917     } else if (C->getNumOperands()) {
918       // If a constant has operands, enumerate them.  This makes sure that if a
919       // constant has uses (for example an array of const ints), that they are
920       // inserted also.
921 
922       // We prefer to enumerate them with values before we enumerate the user
923       // itself.  This makes it more likely that we can avoid forward references
924       // in the reader.  We know that there can be no cycles in the constants
925       // graph that don't go through a global variable.
926       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
927            I != E; ++I)
928         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
929           EnumerateValue(*I);
930       if (auto *CE = dyn_cast<ConstantExpr>(C))
931         if (CE->getOpcode() == Instruction::ShuffleVector)
932           EnumerateValue(CE->getShuffleMaskForBitcode());
933 
934       // Finally, add the value.  Doing this could make the ValueID reference be
935       // dangling, don't reuse it.
936       Values.push_back(std::make_pair(V, 1U));
937       ValueMap[V] = Values.size();
938       return;
939     }
940   }
941 
942   // Add the value.
943   Values.push_back(std::make_pair(V, 1U));
944   ValueID = Values.size();
945 }
946 
947 
948 void ValueEnumerator::EnumerateType(Type *Ty) {
949   unsigned *TypeID = &TypeMap[Ty];
950 
951   // We've already seen this type.
952   if (*TypeID)
953     return;
954 
955   // If it is a non-anonymous struct, mark the type as being visited so that we
956   // don't recursively visit it.  This is safe because we allow forward
957   // references of these in the bitcode reader.
958   if (StructType *STy = dyn_cast<StructType>(Ty))
959     if (!STy->isLiteral())
960       *TypeID = ~0U;
961 
962   // Enumerate all of the subtypes before we enumerate this type.  This ensures
963   // that the type will be enumerated in an order that can be directly built.
964   for (Type *SubTy : Ty->subtypes())
965     EnumerateType(SubTy);
966 
967   // Refresh the TypeID pointer in case the table rehashed.
968   TypeID = &TypeMap[Ty];
969 
970   // Check to see if we got the pointer another way.  This can happen when
971   // enumerating recursive types that hit the base case deeper than they start.
972   //
973   // If this is actually a struct that we are treating as forward ref'able,
974   // then emit the definition now that all of its contents are available.
975   if (*TypeID && *TypeID != ~0U)
976     return;
977 
978   // Add this type now that its contents are all happily enumerated.
979   Types.push_back(Ty);
980 
981   *TypeID = Types.size();
982 }
983 
984 // Enumerate the types for the specified value.  If the value is a constant,
985 // walk through it, enumerating the types of the constant.
986 void ValueEnumerator::EnumerateOperandType(const Value *V) {
987   EnumerateType(V->getType());
988 
989   assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
990 
991   const Constant *C = dyn_cast<Constant>(V);
992   if (!C)
993     return;
994 
995   // If this constant is already enumerated, ignore it, we know its type must
996   // be enumerated.
997   if (ValueMap.count(C))
998     return;
999 
1000   // This constant may have operands, make sure to enumerate the types in
1001   // them.
1002   for (const Value *Op : C->operands()) {
1003     // Don't enumerate basic blocks here, this happens as operands to
1004     // blockaddress.
1005     if (isa<BasicBlock>(Op))
1006       continue;
1007 
1008     EnumerateOperandType(Op);
1009   }
1010   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1011     if (CE->getOpcode() == Instruction::ShuffleVector)
1012       EnumerateOperandType(CE->getShuffleMaskForBitcode());
1013     if (CE->getOpcode() == Instruction::GetElementPtr)
1014       EnumerateType(cast<GEPOperator>(CE)->getSourceElementType());
1015   }
1016 }
1017 
1018 void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
1019   if (PAL.isEmpty()) return;  // null is always 0.
1020 
1021   // Do a lookup.
1022   unsigned &Entry = AttributeListMap[PAL];
1023   if (Entry == 0) {
1024     // Never saw this before, add it.
1025     AttributeLists.push_back(PAL);
1026     Entry = AttributeLists.size();
1027   }
1028 
1029   // Do lookups for all attribute groups.
1030   for (unsigned i = PAL.index_begin(), e = PAL.index_end(); i != e; ++i) {
1031     AttributeSet AS = PAL.getAttributes(i);
1032     if (!AS.hasAttributes())
1033       continue;
1034     IndexAndAttrSet Pair = {i, AS};
1035     unsigned &Entry = AttributeGroupMap[Pair];
1036     if (Entry == 0) {
1037       AttributeGroups.push_back(Pair);
1038       Entry = AttributeGroups.size();
1039     }
1040   }
1041 }
1042 
1043 void ValueEnumerator::incorporateFunction(const Function &F) {
1044   InstructionCount = 0;
1045   NumModuleValues = Values.size();
1046 
1047   // Add global metadata to the function block.  This doesn't include
1048   // LocalAsMetadata.
1049   incorporateFunctionMetadata(F);
1050 
1051   // Adding function arguments to the value table.
1052   for (const auto &I : F.args()) {
1053     EnumerateValue(&I);
1054     if (I.hasAttribute(Attribute::ByVal))
1055       EnumerateType(I.getParamByValType());
1056     else if (I.hasAttribute(Attribute::StructRet))
1057       EnumerateType(I.getParamStructRetType());
1058     else if (I.hasAttribute(Attribute::ByRef))
1059       EnumerateType(I.getParamByRefType());
1060   }
1061   FirstFuncConstantID = Values.size();
1062 
1063   // Add all function-level constants to the value table.
1064   for (const BasicBlock &BB : F) {
1065     for (const Instruction &I : BB) {
1066       for (const Use &OI : I.operands()) {
1067         if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
1068           EnumerateValue(OI);
1069       }
1070       if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
1071         EnumerateValue(SVI->getShuffleMaskForBitcode());
1072     }
1073     BasicBlocks.push_back(&BB);
1074     ValueMap[&BB] = BasicBlocks.size();
1075   }
1076 
1077   // Optimize the constant layout.
1078   OptimizeConstants(FirstFuncConstantID, Values.size());
1079 
1080   // Add the function's parameter attributes so they are available for use in
1081   // the function's instruction.
1082   EnumerateAttributes(F.getAttributes());
1083 
1084   FirstInstID = Values.size();
1085 
1086   SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
1087   SmallVector<DIArgList *, 8> ArgListMDVector;
1088   // Add all of the instructions.
1089   for (const BasicBlock &BB : F) {
1090     for (const Instruction &I : BB) {
1091       for (const Use &OI : I.operands()) {
1092         if (auto *MD = dyn_cast<MetadataAsValue>(&OI)) {
1093           if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata())) {
1094             // Enumerate metadata after the instructions they might refer to.
1095             FnLocalMDVector.push_back(Local);
1096           } else if (auto *ArgList = dyn_cast<DIArgList>(MD->getMetadata())) {
1097             ArgListMDVector.push_back(ArgList);
1098             for (ValueAsMetadata *VMD : ArgList->getArgs()) {
1099               if (auto *Local = dyn_cast<LocalAsMetadata>(VMD)) {
1100                 // Enumerate metadata after the instructions they might refer
1101                 // to.
1102                 FnLocalMDVector.push_back(Local);
1103               }
1104             }
1105           }
1106         }
1107       }
1108 
1109       if (!I.getType()->isVoidTy())
1110         EnumerateValue(&I);
1111     }
1112   }
1113 
1114   // Add all of the function-local metadata.
1115   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) {
1116     // At this point, every local values have been incorporated, we shouldn't
1117     // have a metadata operand that references a value that hasn't been seen.
1118     assert(ValueMap.count(FnLocalMDVector[i]->getValue()) &&
1119            "Missing value for metadata operand");
1120     EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
1121   }
1122   // DIArgList entries must come after function-local metadata, as it is not
1123   // possible to forward-reference them.
1124   for (const DIArgList *ArgList : ArgListMDVector)
1125     EnumerateFunctionLocalListMetadata(F, ArgList);
1126 }
1127 
1128 void ValueEnumerator::purgeFunction() {
1129   /// Remove purged values from the ValueMap.
1130   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
1131     ValueMap.erase(Values[i].first);
1132   for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
1133     MetadataMap.erase(MDs[i]);
1134   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
1135     ValueMap.erase(BasicBlocks[i]);
1136 
1137   Values.resize(NumModuleValues);
1138   MDs.resize(NumModuleMDs);
1139   BasicBlocks.clear();
1140   NumMDStrings = 0;
1141 }
1142 
1143 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
1144                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
1145   unsigned Counter = 0;
1146   for (const BasicBlock &BB : *F)
1147     IDMap[&BB] = ++Counter;
1148 }
1149 
1150 /// getGlobalBasicBlockID - This returns the function-specific ID for the
1151 /// specified basic block.  This is relatively expensive information, so it
1152 /// should only be used by rare constructs such as address-of-label.
1153 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
1154   unsigned &Idx = GlobalBasicBlockIDs[BB];
1155   if (Idx != 0)
1156     return Idx-1;
1157 
1158   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
1159   return getGlobalBasicBlockID(BB);
1160 }
1161 
1162 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
1163   return Log2_32_Ceil(getTypes().size() + 1);
1164 }
1165