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