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