xref: /llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp (revision 18d7e822ab22e6747f01b0409ace5044733be162)
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     EnumerateType(GV.getValueType());
371   }
372 
373   // Enumerate the functions.
374   for (const Function & F : M) {
375     EnumerateValue(&F);
376     EnumerateType(F.getValueType());
377     EnumerateAttributes(F.getAttributes());
378   }
379 
380   // Enumerate the aliases.
381   for (const GlobalAlias &GA : M.aliases())
382     EnumerateValue(&GA);
383 
384   // Enumerate the ifuncs.
385   for (const GlobalIFunc &GIF : M.ifuncs())
386     EnumerateValue(&GIF);
387 
388   // Remember what is the cutoff between globalvalue's and other constants.
389   unsigned FirstConstant = Values.size();
390 
391   // Enumerate the global variable initializers and attributes.
392   for (const GlobalVariable &GV : M.globals()) {
393     if (GV.hasInitializer())
394       EnumerateValue(GV.getInitializer());
395     if (GV.hasAttributes())
396       EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
397   }
398 
399   // Enumerate the aliasees.
400   for (const GlobalAlias &GA : M.aliases())
401     EnumerateValue(GA.getAliasee());
402 
403   // Enumerate the ifunc resolvers.
404   for (const GlobalIFunc &GIF : M.ifuncs())
405     EnumerateValue(GIF.getResolver());
406 
407   // Enumerate any optional Function data.
408   for (const Function &F : M)
409     for (const Use &U : F.operands())
410       EnumerateValue(U.get());
411 
412   // Enumerate the metadata type.
413   //
414   // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
415   // only encodes the metadata type when it's used as a value.
416   EnumerateType(Type::getMetadataTy(M.getContext()));
417 
418   // Insert constants and metadata that are named at module level into the slot
419   // pool so that the module symbol table can refer to them...
420   EnumerateValueSymbolTable(M.getValueSymbolTable());
421   EnumerateNamedMetadata(M);
422 
423   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
424   for (const GlobalVariable &GV : M.globals()) {
425     MDs.clear();
426     GV.getAllMetadata(MDs);
427     for (const auto &I : MDs)
428       // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer
429       // to write metadata to the global variable's own metadata block
430       // (PR28134).
431       EnumerateMetadata(nullptr, I.second);
432   }
433 
434   // Enumerate types used by function bodies and argument lists.
435   for (const Function &F : M) {
436     for (const Argument &A : F.args())
437       EnumerateType(A.getType());
438 
439     // Enumerate metadata attached to this function.
440     MDs.clear();
441     F.getAllMetadata(MDs);
442     for (const auto &I : MDs)
443       EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second);
444 
445     for (const BasicBlock &BB : F)
446       for (const Instruction &I : BB) {
447         for (const Use &Op : I.operands()) {
448           auto *MD = dyn_cast<MetadataAsValue>(&Op);
449           if (!MD) {
450             EnumerateOperandType(Op);
451             continue;
452           }
453 
454           // Local metadata is enumerated during function-incorporation, but
455           // any ConstantAsMetadata arguments in a DIArgList should be examined
456           // now.
457           if (isa<LocalAsMetadata>(MD->getMetadata()))
458             continue;
459           if (auto *AL = dyn_cast<DIArgList>(MD->getMetadata())) {
460             for (auto *VAM : AL->getArgs())
461               if (isa<ConstantAsMetadata>(VAM))
462                 EnumerateMetadata(&F, VAM);
463             continue;
464           }
465 
466           EnumerateMetadata(&F, MD->getMetadata());
467         }
468         if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
469           EnumerateType(SVI->getShuffleMaskForBitcode()->getType());
470         if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
471           EnumerateType(GEP->getSourceElementType());
472         if (auto *AI = dyn_cast<AllocaInst>(&I))
473           EnumerateType(AI->getAllocatedType());
474         EnumerateType(I.getType());
475         if (const auto *Call = dyn_cast<CallBase>(&I)) {
476           EnumerateAttributes(Call->getAttributes());
477           EnumerateType(Call->getFunctionType());
478         }
479 
480         // Enumerate metadata attached with this instruction.
481         MDs.clear();
482         I.getAllMetadataOtherThanDebugLoc(MDs);
483         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
484           EnumerateMetadata(&F, MDs[i].second);
485 
486         // Don't enumerate the location directly -- it has a special record
487         // type -- but enumerate its operands.
488         if (DILocation *L = I.getDebugLoc())
489           for (const Metadata *Op : L->operands())
490             EnumerateMetadata(&F, Op);
491       }
492   }
493 
494   // Optimize constant ordering.
495   OptimizeConstants(FirstConstant, Values.size());
496 
497   // Organize metadata ordering.
498   organizeMetadata();
499 }
500 
501 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
502   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
503   assert(I != InstructionMap.end() && "Instruction is not mapped!");
504   return I->second;
505 }
506 
507 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
508   unsigned ComdatID = Comdats.idFor(C);
509   assert(ComdatID && "Comdat not found!");
510   return ComdatID;
511 }
512 
513 void ValueEnumerator::setInstructionID(const Instruction *I) {
514   InstructionMap[I] = InstructionCount++;
515 }
516 
517 unsigned ValueEnumerator::getValueID(const Value *V) const {
518   if (auto *MD = dyn_cast<MetadataAsValue>(V))
519     return getMetadataID(MD->getMetadata());
520 
521   ValueMapType::const_iterator I = ValueMap.find(V);
522   assert(I != ValueMap.end() && "Value not in slotcalculator!");
523   return I->second-1;
524 }
525 
526 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
527 LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
528   print(dbgs(), ValueMap, "Default");
529   dbgs() << '\n';
530   print(dbgs(), MetadataMap, "MetaData");
531   dbgs() << '\n';
532 }
533 #endif
534 
535 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
536                             const char *Name) const {
537   OS << "Map Name: " << Name << "\n";
538   OS << "Size: " << Map.size() << "\n";
539   for (ValueMapType::const_iterator I = Map.begin(),
540          E = Map.end(); I != E; ++I) {
541     const Value *V = I->first;
542     if (V->hasName())
543       OS << "Value: " << V->getName();
544     else
545       OS << "Value: [null]\n";
546     V->print(errs());
547     errs() << '\n';
548 
549     OS << " Uses(" << V->getNumUses() << "):";
550     for (const Use &U : V->uses()) {
551       if (&U != &*V->use_begin())
552         OS << ",";
553       if(U->hasName())
554         OS << " " << U->getName();
555       else
556         OS << " [null]";
557 
558     }
559     OS <<  "\n\n";
560   }
561 }
562 
563 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
564                             const char *Name) const {
565   OS << "Map Name: " << Name << "\n";
566   OS << "Size: " << Map.size() << "\n";
567   for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
568     const Metadata *MD = I->first;
569     OS << "Metadata: slot = " << I->second.ID << "\n";
570     OS << "Metadata: function = " << I->second.F << "\n";
571     MD->print(OS);
572     OS << "\n";
573   }
574 }
575 
576 /// OptimizeConstants - Reorder constant pool for denser encoding.
577 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
578   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
579 
580   if (ShouldPreserveUseListOrder)
581     // Optimizing constants makes the use-list order difficult to predict.
582     // Disable it for now when trying to preserve the order.
583     return;
584 
585   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
586                    [this](const std::pair<const Value *, unsigned> &LHS,
587                           const std::pair<const Value *, unsigned> &RHS) {
588     // Sort by plane.
589     if (LHS.first->getType() != RHS.first->getType())
590       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
591     // Then by frequency.
592     return LHS.second > RHS.second;
593   });
594 
595   // Ensure that integer and vector of integer constants are at the start of the
596   // constant pool.  This is important so that GEP structure indices come before
597   // gep constant exprs.
598   std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
599                         isIntOrIntVectorValue);
600 
601   // Rebuild the modified portion of ValueMap.
602   for (; CstStart != CstEnd; ++CstStart)
603     ValueMap[Values[CstStart].first] = CstStart+1;
604 }
605 
606 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
607 /// table into the values table.
608 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
609   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
610        VI != VE; ++VI)
611     EnumerateValue(VI->getValue());
612 }
613 
614 /// Insert all of the values referenced by named metadata in the specified
615 /// module.
616 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
617   for (const auto &I : M.named_metadata())
618     EnumerateNamedMDNode(&I);
619 }
620 
621 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
622   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
623     EnumerateMetadata(nullptr, MD->getOperand(i));
624 }
625 
626 unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const {
627   return F ? getValueID(F) + 1 : 0;
628 }
629 
630 void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) {
631   EnumerateMetadata(getMetadataFunctionID(F), MD);
632 }
633 
634 void ValueEnumerator::EnumerateFunctionLocalMetadata(
635     const Function &F, const LocalAsMetadata *Local) {
636   EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
637 }
638 
639 void ValueEnumerator::EnumerateFunctionLocalListMetadata(
640     const Function &F, const DIArgList *ArgList) {
641   EnumerateFunctionLocalListMetadata(getMetadataFunctionID(&F), ArgList);
642 }
643 
644 void ValueEnumerator::dropFunctionFromMetadata(
645     MetadataMapType::value_type &FirstMD) {
646   SmallVector<const MDNode *, 64> Worklist;
647   auto push = [&Worklist](MetadataMapType::value_type &MD) {
648     auto &Entry = MD.second;
649 
650     // Nothing to do if this metadata isn't tagged.
651     if (!Entry.F)
652       return;
653 
654     // Drop the function tag.
655     Entry.F = 0;
656 
657     // If this is has an ID and is an MDNode, then its operands have entries as
658     // well.  We need to drop the function from them too.
659     if (Entry.ID)
660       if (auto *N = dyn_cast<MDNode>(MD.first))
661         Worklist.push_back(N);
662   };
663   push(FirstMD);
664   while (!Worklist.empty())
665     for (const Metadata *Op : Worklist.pop_back_val()->operands()) {
666       if (!Op)
667         continue;
668       auto MD = MetadataMap.find(Op);
669       if (MD != MetadataMap.end())
670         push(*MD);
671     }
672 }
673 
674 void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) {
675   // It's vital for reader efficiency that uniqued subgraphs are done in
676   // post-order; it's expensive when their operands have forward references.
677   // If a distinct node is referenced from a uniqued node, it'll be delayed
678   // until the uniqued subgraph has been completely traversed.
679   SmallVector<const MDNode *, 32> DelayedDistinctNodes;
680 
681   // Start by enumerating MD, and then work through its transitive operands in
682   // post-order.  This requires a depth-first search.
683   SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist;
684   if (const MDNode *N = enumerateMetadataImpl(F, MD))
685     Worklist.push_back(std::make_pair(N, N->op_begin()));
686 
687   while (!Worklist.empty()) {
688     const MDNode *N = Worklist.back().first;
689 
690     // Enumerate operands until we hit a new node.  We need to traverse these
691     // nodes' operands before visiting the rest of N's operands.
692     MDNode::op_iterator I = std::find_if(
693         Worklist.back().second, N->op_end(),
694         [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
695     if (I != N->op_end()) {
696       auto *Op = cast<MDNode>(*I);
697       Worklist.back().second = ++I;
698 
699       // Delay traversing Op if it's a distinct node and N is uniqued.
700       if (Op->isDistinct() && !N->isDistinct())
701         DelayedDistinctNodes.push_back(Op);
702       else
703         Worklist.push_back(std::make_pair(Op, Op->op_begin()));
704       continue;
705     }
706 
707     // All the operands have been visited.  Now assign an ID.
708     Worklist.pop_back();
709     MDs.push_back(N);
710     MetadataMap[N].ID = MDs.size();
711 
712     // Flush out any delayed distinct nodes; these are all the distinct nodes
713     // that are leaves in last uniqued subgraph.
714     if (Worklist.empty() || Worklist.back().first->isDistinct()) {
715       for (const MDNode *N : DelayedDistinctNodes)
716         Worklist.push_back(std::make_pair(N, N->op_begin()));
717       DelayedDistinctNodes.clear();
718     }
719   }
720 }
721 
722 const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F, const Metadata *MD) {
723   if (!MD)
724     return nullptr;
725 
726   assert(
727       (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
728       "Invalid metadata kind");
729 
730   auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F)));
731   MDIndex &Entry = Insertion.first->second;
732   if (!Insertion.second) {
733     // Already mapped.  If F doesn't match the function tag, drop it.
734     if (Entry.hasDifferentFunction(F))
735       dropFunctionFromMetadata(*Insertion.first);
736     return nullptr;
737   }
738 
739   // Don't assign IDs to metadata nodes.
740   if (auto *N = dyn_cast<MDNode>(MD))
741     return N;
742 
743   // Save the metadata.
744   MDs.push_back(MD);
745   Entry.ID = MDs.size();
746 
747   // Enumerate the constant, if any.
748   if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
749     EnumerateValue(C->getValue());
750 
751   return nullptr;
752 }
753 
754 /// EnumerateFunctionLocalMetadata - Incorporate function-local metadata
755 /// information reachable from the metadata.
756 void ValueEnumerator::EnumerateFunctionLocalMetadata(
757     unsigned F, const LocalAsMetadata *Local) {
758   assert(F && "Expected a function");
759 
760   // Check to see if it's already in!
761   MDIndex &Index = MetadataMap[Local];
762   if (Index.ID) {
763     assert(Index.F == F && "Expected the same function");
764     return;
765   }
766 
767   MDs.push_back(Local);
768   Index.F = F;
769   Index.ID = MDs.size();
770 
771   EnumerateValue(Local->getValue());
772 }
773 
774 /// EnumerateFunctionLocalListMetadata - Incorporate function-local metadata
775 /// information reachable from the metadata.
776 void ValueEnumerator::EnumerateFunctionLocalListMetadata(
777     unsigned F, const DIArgList *ArgList) {
778   assert(F && "Expected a function");
779 
780   // Check to see if it's already in!
781   MDIndex &Index = MetadataMap[ArgList];
782   if (Index.ID) {
783     assert(Index.F == F && "Expected the same function");
784     return;
785   }
786 
787   for (ValueAsMetadata *VAM : ArgList->getArgs()) {
788     if (isa<LocalAsMetadata>(VAM)) {
789       assert(MetadataMap.count(VAM) &&
790              "LocalAsMetadata should be enumerated before DIArgList");
791       assert(MetadataMap[VAM].F == F &&
792              "Expected LocalAsMetadata in the same function");
793     } else {
794       assert(isa<ConstantAsMetadata>(VAM) &&
795              "Expected LocalAsMetadata or ConstantAsMetadata");
796       assert(ValueMap.count(VAM->getValue()) &&
797              "Constant should be enumerated beforeDIArgList");
798       EnumerateMetadata(F, VAM);
799     }
800   }
801 
802   MDs.push_back(ArgList);
803   Index.F = F;
804   Index.ID = MDs.size();
805 }
806 
807 static unsigned getMetadataTypeOrder(const Metadata *MD) {
808   // Strings are emitted in bulk and must come first.
809   if (isa<MDString>(MD))
810     return 0;
811 
812   // ConstantAsMetadata doesn't reference anything.  We may as well shuffle it
813   // to the front since we can detect it.
814   auto *N = dyn_cast<MDNode>(MD);
815   if (!N)
816     return 1;
817 
818   // The reader is fast forward references for distinct node operands, but slow
819   // when uniqued operands are unresolved.
820   return N->isDistinct() ? 2 : 3;
821 }
822 
823 void ValueEnumerator::organizeMetadata() {
824   assert(MetadataMap.size() == MDs.size() &&
825          "Metadata map and vector out of sync");
826 
827   if (MDs.empty())
828     return;
829 
830   // Copy out the index information from MetadataMap in order to choose a new
831   // order.
832   SmallVector<MDIndex, 64> Order;
833   Order.reserve(MetadataMap.size());
834   for (const Metadata *MD : MDs)
835     Order.push_back(MetadataMap.lookup(MD));
836 
837   // Partition:
838   //   - by function, then
839   //   - by isa<MDString>
840   // and then sort by the original/current ID.  Since the IDs are guaranteed to
841   // be unique, the result of std::sort will be deterministic.  There's no need
842   // for std::stable_sort.
843   llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
844     return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <
845            std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID);
846   });
847 
848   // Rebuild MDs, index the metadata ranges for each function in FunctionMDs,
849   // and fix up MetadataMap.
850   std::vector<const Metadata *> OldMDs;
851   MDs.swap(OldMDs);
852   MDs.reserve(OldMDs.size());
853   for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) {
854     auto *MD = Order[I].get(OldMDs);
855     MDs.push_back(MD);
856     MetadataMap[MD].ID = I + 1;
857     if (isa<MDString>(MD))
858       ++NumMDStrings;
859   }
860 
861   // Return early if there's nothing for the functions.
862   if (MDs.size() == Order.size())
863     return;
864 
865   // Build the function metadata ranges.
866   MDRange R;
867   FunctionMDs.reserve(OldMDs.size());
868   unsigned PrevF = 0;
869   for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E;
870        ++I) {
871     unsigned F = Order[I].F;
872     if (!PrevF) {
873       PrevF = F;
874     } else if (PrevF != F) {
875       R.Last = FunctionMDs.size();
876       std::swap(R, FunctionMDInfo[PrevF]);
877       R.First = FunctionMDs.size();
878 
879       ID = MDs.size();
880       PrevF = F;
881     }
882 
883     auto *MD = Order[I].get(OldMDs);
884     FunctionMDs.push_back(MD);
885     MetadataMap[MD].ID = ++ID;
886     if (isa<MDString>(MD))
887       ++R.NumStrings;
888   }
889   R.Last = FunctionMDs.size();
890   FunctionMDInfo[PrevF] = R;
891 }
892 
893 void ValueEnumerator::incorporateFunctionMetadata(const Function &F) {
894   NumModuleMDs = MDs.size();
895 
896   auto R = FunctionMDInfo.lookup(getValueID(&F) + 1);
897   NumMDStrings = R.NumStrings;
898   MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
899              FunctionMDs.begin() + R.Last);
900 }
901 
902 void ValueEnumerator::EnumerateValue(const Value *V) {
903   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
904   assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
905 
906   // Check to see if it's already in!
907   unsigned &ValueID = ValueMap[V];
908   if (ValueID) {
909     // Increment use count.
910     Values[ValueID-1].second++;
911     return;
912   }
913 
914   if (auto *GO = dyn_cast<GlobalObject>(V))
915     if (const Comdat *C = GO->getComdat())
916       Comdats.insert(C);
917 
918   // Enumerate the type of this value.
919   EnumerateType(V->getType());
920 
921   if (const Constant *C = dyn_cast<Constant>(V)) {
922     if (isa<GlobalValue>(C)) {
923       // Initializers for globals are handled explicitly elsewhere.
924     } else if (C->getNumOperands()) {
925       // If a constant has operands, enumerate them.  This makes sure that if a
926       // constant has uses (for example an array of const ints), that they are
927       // inserted also.
928 
929       // We prefer to enumerate them with values before we enumerate the user
930       // itself.  This makes it more likely that we can avoid forward references
931       // in the reader.  We know that there can be no cycles in the constants
932       // graph that don't go through a global variable.
933       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
934            I != E; ++I)
935         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
936           EnumerateValue(*I);
937       if (auto *CE = dyn_cast<ConstantExpr>(C))
938         if (CE->getOpcode() == Instruction::ShuffleVector)
939           EnumerateValue(CE->getShuffleMaskForBitcode());
940 
941       // Finally, add the value.  Doing this could make the ValueID reference be
942       // dangling, don't reuse it.
943       Values.push_back(std::make_pair(V, 1U));
944       ValueMap[V] = Values.size();
945       return;
946     }
947   }
948 
949   // Add the value.
950   Values.push_back(std::make_pair(V, 1U));
951   ValueID = Values.size();
952 }
953 
954 
955 void ValueEnumerator::EnumerateType(Type *Ty) {
956   unsigned *TypeID = &TypeMap[Ty];
957 
958   // We've already seen this type.
959   if (*TypeID)
960     return;
961 
962   // If it is a non-anonymous struct, mark the type as being visited so that we
963   // don't recursively visit it.  This is safe because we allow forward
964   // references of these in the bitcode reader.
965   if (StructType *STy = dyn_cast<StructType>(Ty))
966     if (!STy->isLiteral())
967       *TypeID = ~0U;
968 
969   // Enumerate all of the subtypes before we enumerate this type.  This ensures
970   // that the type will be enumerated in an order that can be directly built.
971   for (Type *SubTy : Ty->subtypes())
972     EnumerateType(SubTy);
973 
974   // Refresh the TypeID pointer in case the table rehashed.
975   TypeID = &TypeMap[Ty];
976 
977   // Check to see if we got the pointer another way.  This can happen when
978   // enumerating recursive types that hit the base case deeper than they start.
979   //
980   // If this is actually a struct that we are treating as forward ref'able,
981   // then emit the definition now that all of its contents are available.
982   if (*TypeID && *TypeID != ~0U)
983     return;
984 
985   // Add this type now that its contents are all happily enumerated.
986   Types.push_back(Ty);
987 
988   *TypeID = Types.size();
989 }
990 
991 // Enumerate the types for the specified value.  If the value is a constant,
992 // walk through it, enumerating the types of the constant.
993 void ValueEnumerator::EnumerateOperandType(const Value *V) {
994   EnumerateType(V->getType());
995 
996   assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
997 
998   const Constant *C = dyn_cast<Constant>(V);
999   if (!C)
1000     return;
1001 
1002   // If this constant is already enumerated, ignore it, we know its type must
1003   // be enumerated.
1004   if (ValueMap.count(C))
1005     return;
1006 
1007   // This constant may have operands, make sure to enumerate the types in
1008   // them.
1009   for (const Value *Op : C->operands()) {
1010     // Don't enumerate basic blocks here, this happens as operands to
1011     // blockaddress.
1012     if (isa<BasicBlock>(Op))
1013       continue;
1014 
1015     EnumerateOperandType(Op);
1016   }
1017   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1018     if (CE->getOpcode() == Instruction::ShuffleVector)
1019       EnumerateOperandType(CE->getShuffleMaskForBitcode());
1020     if (CE->getOpcode() == Instruction::GetElementPtr)
1021       EnumerateType(cast<GEPOperator>(CE)->getSourceElementType());
1022   }
1023 }
1024 
1025 void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
1026   if (PAL.isEmpty()) return;  // null is always 0.
1027 
1028   // Do a lookup.
1029   unsigned &Entry = AttributeListMap[PAL];
1030   if (Entry == 0) {
1031     // Never saw this before, add it.
1032     AttributeLists.push_back(PAL);
1033     Entry = AttributeLists.size();
1034   }
1035 
1036   // Do lookups for all attribute groups.
1037   for (unsigned i = PAL.index_begin(), e = PAL.index_end(); i != e; ++i) {
1038     AttributeSet AS = PAL.getAttributes(i);
1039     if (!AS.hasAttributes())
1040       continue;
1041     IndexAndAttrSet Pair = {i, AS};
1042     unsigned &Entry = AttributeGroupMap[Pair];
1043     if (Entry == 0) {
1044       AttributeGroups.push_back(Pair);
1045       Entry = AttributeGroups.size();
1046     }
1047   }
1048 }
1049 
1050 void ValueEnumerator::incorporateFunction(const Function &F) {
1051   InstructionCount = 0;
1052   NumModuleValues = Values.size();
1053 
1054   // Add global metadata to the function block.  This doesn't include
1055   // LocalAsMetadata.
1056   incorporateFunctionMetadata(F);
1057 
1058   // Adding function arguments to the value table.
1059   for (const auto &I : F.args()) {
1060     EnumerateValue(&I);
1061     if (I.hasAttribute(Attribute::ByVal))
1062       EnumerateType(I.getParamByValType());
1063     else if (I.hasAttribute(Attribute::StructRet))
1064       EnumerateType(I.getParamStructRetType());
1065     else if (I.hasAttribute(Attribute::ByRef))
1066       EnumerateType(I.getParamByRefType());
1067   }
1068   FirstFuncConstantID = Values.size();
1069 
1070   // Add all function-level constants to the value table.
1071   for (const BasicBlock &BB : F) {
1072     for (const Instruction &I : BB) {
1073       for (const Use &OI : I.operands()) {
1074         if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
1075           EnumerateValue(OI);
1076       }
1077       if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
1078         EnumerateValue(SVI->getShuffleMaskForBitcode());
1079     }
1080     BasicBlocks.push_back(&BB);
1081     ValueMap[&BB] = BasicBlocks.size();
1082   }
1083 
1084   // Optimize the constant layout.
1085   OptimizeConstants(FirstFuncConstantID, Values.size());
1086 
1087   // Add the function's parameter attributes so they are available for use in
1088   // the function's instruction.
1089   EnumerateAttributes(F.getAttributes());
1090 
1091   FirstInstID = Values.size();
1092 
1093   SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
1094   SmallVector<DIArgList *, 8> ArgListMDVector;
1095   // Add all of the instructions.
1096   for (const BasicBlock &BB : F) {
1097     for (const Instruction &I : BB) {
1098       for (const Use &OI : I.operands()) {
1099         if (auto *MD = dyn_cast<MetadataAsValue>(&OI)) {
1100           if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata())) {
1101             // Enumerate metadata after the instructions they might refer to.
1102             FnLocalMDVector.push_back(Local);
1103           } else if (auto *ArgList = dyn_cast<DIArgList>(MD->getMetadata())) {
1104             ArgListMDVector.push_back(ArgList);
1105             for (ValueAsMetadata *VMD : ArgList->getArgs()) {
1106               if (auto *Local = dyn_cast<LocalAsMetadata>(VMD)) {
1107                 // Enumerate metadata after the instructions they might refer
1108                 // to.
1109                 FnLocalMDVector.push_back(Local);
1110               }
1111             }
1112           }
1113         }
1114       }
1115 
1116       if (!I.getType()->isVoidTy())
1117         EnumerateValue(&I);
1118     }
1119   }
1120 
1121   // Add all of the function-local metadata.
1122   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) {
1123     // At this point, every local values have been incorporated, we shouldn't
1124     // have a metadata operand that references a value that hasn't been seen.
1125     assert(ValueMap.count(FnLocalMDVector[i]->getValue()) &&
1126            "Missing value for metadata operand");
1127     EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
1128   }
1129   // DIArgList entries must come after function-local metadata, as it is not
1130   // possible to forward-reference them.
1131   for (const DIArgList *ArgList : ArgListMDVector)
1132     EnumerateFunctionLocalListMetadata(F, ArgList);
1133 }
1134 
1135 void ValueEnumerator::purgeFunction() {
1136   /// Remove purged values from the ValueMap.
1137   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
1138     ValueMap.erase(Values[i].first);
1139   for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
1140     MetadataMap.erase(MDs[i]);
1141   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
1142     ValueMap.erase(BasicBlocks[i]);
1143 
1144   Values.resize(NumModuleValues);
1145   MDs.resize(NumModuleMDs);
1146   BasicBlocks.clear();
1147   NumMDStrings = 0;
1148 }
1149 
1150 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
1151                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
1152   unsigned Counter = 0;
1153   for (const BasicBlock &BB : *F)
1154     IDMap[&BB] = ++Counter;
1155 }
1156 
1157 /// getGlobalBasicBlockID - This returns the function-specific ID for the
1158 /// specified basic block.  This is relatively expensive information, so it
1159 /// should only be used by rare constructs such as address-of-label.
1160 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
1161   unsigned &Idx = GlobalBasicBlockIDs[BB];
1162   if (Idx != 0)
1163     return Idx-1;
1164 
1165   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
1166   return getGlobalBasicBlockID(BB);
1167 }
1168 
1169 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
1170   return Log2_32_Ceil(getTypes().size() + 1);
1171 }
1172