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