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