UseListOrder: Fix undefined behaviour
[oota-llvm.git] / 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/DerivedTypes.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/UseListOrder.h"
22 #include "llvm/IR/ValueSymbolTable.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 namespace {
29 struct OrderMap {
30   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
31
32   unsigned size() const { return IDs.size(); }
33   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
34   std::pair<unsigned, bool> lookup(const Value *V) const {
35     return IDs.lookup(V);
36   }
37   void index(const Value *V) {
38     // Explicitly sequence get-size and insert-value operations to avoid UB.
39     unsigned ID = IDs.size() + 1;
40     IDs[V].first = ID;
41   }
42 };
43 }
44
45 static void orderValue(const Value *V, OrderMap &OM) {
46   if (OM.lookup(V).first)
47     return;
48
49   if (const Constant *C = dyn_cast<Constant>(V))
50     if (C->getNumOperands() && !isa<GlobalValue>(C))
51       for (const Value *Op : C->operands())
52         if (!isa<BasicBlock>(Op))
53           orderValue(Op, OM);
54
55   // Note: we cannot cache this lookup above, since inserting into the map
56   // changes the map's size, and thus affects the other IDs.
57   OM.index(V);
58 }
59
60 static OrderMap orderModule(const Module *M) {
61   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
62   // and ValueEnumerator::incorporateFunction().
63   OrderMap OM;
64
65   for (const GlobalVariable &G : M->globals())
66     orderValue(&G, OM);
67   for (const Function &F : *M)
68     orderValue(&F, OM);
69   for (const GlobalAlias &A : M->aliases())
70     orderValue(&A, OM);
71   for (const GlobalVariable &G : M->globals())
72     if (G.hasInitializer())
73       orderValue(G.getInitializer(), OM);
74   for (const GlobalAlias &A : M->aliases())
75     orderValue(A.getAliasee(), OM);
76   for (const Function &F : *M)
77     if (F.hasPrefixData())
78       orderValue(F.getPrefixData(), OM);
79
80   for (const Function &F : *M) {
81     if (F.isDeclaration())
82       continue;
83     // Here we need to match the union of ValueEnumerator::incorporateFunction()
84     // and WriteFunction().  Basic blocks are implicitly declared before
85     // anything else (by declaring their size).
86     for (const BasicBlock &BB : F)
87       orderValue(&BB, OM);
88     for (const Argument &A : F.args())
89       orderValue(&A, OM);
90     for (const BasicBlock &BB : F)
91       for (const Instruction &I : BB)
92         for (const Value *Op : I.operands())
93           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
94               isa<InlineAsm>(*Op))
95             orderValue(Op, OM);
96     for (const BasicBlock &BB : F)
97       for (const Instruction &I : BB)
98         orderValue(&I, OM);
99   }
100   return OM;
101 }
102
103 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
104                                          unsigned ID, const OrderMap &OM,
105                                          UseListOrderStack &Stack) {
106   // Predict use-list order for this one.
107   typedef std::pair<const Use *, unsigned> Entry;
108   SmallVector<Entry, 64> List;
109   for (const Use &U : V->uses())
110     // Check if this user will be serialized.
111     if (OM.lookup(U.getUser()).first)
112       List.push_back(std::make_pair(&U, List.size()));
113
114   if (List.size() < 2)
115     // We may have lost some users.
116     return;
117
118   std::sort(List.begin(), List.end(),
119             [&OM, ID](const Entry &L, const Entry &R) {
120     const Use *LU = L.first;
121     const Use *RU = R.first;
122     if (LU == RU)
123       return false;
124
125     auto LID = OM.lookup(LU->getUser()).first;
126     auto RID = OM.lookup(RU->getUser()).first;
127     // If ID is 4, then expect: 7 6 5 1 2 3.
128     if (LID < RID) {
129       if (RID < ID)
130         return true;
131       return false;
132     }
133     if (RID < LID) {
134       if (LID < ID)
135         return false;
136       return true;
137     }
138     // LID and RID are equal, so we have different operands of the same user.
139     // Assume operands are added in order for all instructions.
140     if (LU->getOperandNo() < RU->getOperandNo())
141       return LID < ID;
142     return ID < LID;
143   });
144
145   if (std::is_sorted(
146           List.begin(), List.end(),
147           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
148     // Order is already correct.
149     return;
150
151   // Store the shuffle.
152   Stack.emplace_back(V, F, List.size());
153   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
154   for (size_t I = 0, E = List.size(); I != E; ++I)
155     Stack.back().Shuffle[I] = List[I].second;
156 }
157
158 static void predictValueUseListOrder(const Value *V, const Function *F,
159                                      OrderMap &OM, UseListOrderStack &Stack) {
160   auto &IDPair = OM[V];
161   assert(IDPair.first && "Unmapped value");
162   if (IDPair.second)
163     // Already predicted.
164     return;
165
166   // Do the actual prediction.
167   IDPair.second = true;
168   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
169     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
170
171   // Recursive descent into constants.
172   if (const Constant *C = dyn_cast<Constant>(V))
173     if (C->getNumOperands() && !isa<GlobalValue>(C))
174       for (const Value *Op : C->operands())
175         if (isa<Constant>(Op) && !isa<GlobalValue>(Op))
176           predictValueUseListOrder(Op, F, OM, Stack);
177 }
178
179 static UseListOrderStack predictUseListOrder(const Module *M) {
180   OrderMap OM = orderModule(M);
181
182   // Use-list orders need to be serialized after all the users have been added
183   // to a value, or else the shuffles will be incomplete.  Store them per
184   // function in a stack.
185   //
186   // Aside from function order, the order of values doesn't matter much here.
187   UseListOrderStack Stack;
188
189   // We want to visit the functions backward now so we can list function-local
190   // constants in the last Function they're used in.  Module-level constants
191   // have already been visited above.
192   for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
193     const Function &F = *I;
194     if (F.isDeclaration())
195       continue;
196     for (const BasicBlock &BB : F)
197       predictValueUseListOrder(&BB, &F, OM, Stack);
198     for (const Argument &A : F.args())
199       predictValueUseListOrder(&A, &F, OM, Stack);
200     for (const BasicBlock &BB : F)
201       for (const Instruction &I : BB)
202         for (const Value *Op : I.operands())
203           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
204               isa<InlineAsm>(*Op))
205             predictValueUseListOrder(Op, &F, OM, Stack);
206     for (const BasicBlock &BB : F)
207       for (const Instruction &I : BB)
208         predictValueUseListOrder(&I, &F, OM, Stack);
209   }
210
211   // Visit globals last, since the module-level use-list block will be seen
212   // before the function bodies are processed.
213   for (const GlobalVariable &G : M->globals())
214     predictValueUseListOrder(&G, nullptr, OM, Stack);
215   for (const Function &F : *M)
216     predictValueUseListOrder(&F, nullptr, OM, Stack);
217   for (const GlobalAlias &A : M->aliases())
218     predictValueUseListOrder(&A, nullptr, OM, Stack);
219   for (const GlobalVariable &G : M->globals())
220     if (G.hasInitializer())
221       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
222   for (const GlobalAlias &A : M->aliases())
223     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
224   for (const Function &F : *M)
225     if (F.hasPrefixData())
226       predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
227
228   return Stack;
229 }
230
231 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
232   return V.first->getType()->isIntOrIntVectorTy();
233 }
234
235 /// ValueEnumerator - Enumerate module-level information.
236 ValueEnumerator::ValueEnumerator(const Module *M) {
237   if (shouldPreserveBitcodeUseListOrder())
238     UseListOrders = predictUseListOrder(M);
239
240   // Enumerate the global variables.
241   for (Module::const_global_iterator I = M->global_begin(),
242
243          E = M->global_end(); I != E; ++I)
244     EnumerateValue(I);
245
246   // Enumerate the functions.
247   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
248     EnumerateValue(I);
249     EnumerateAttributes(cast<Function>(I)->getAttributes());
250   }
251
252   // Enumerate the aliases.
253   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
254        I != E; ++I)
255     EnumerateValue(I);
256
257   // Remember what is the cutoff between globalvalue's and other constants.
258   unsigned FirstConstant = Values.size();
259
260   // Enumerate the global variable initializers.
261   for (Module::const_global_iterator I = M->global_begin(),
262          E = M->global_end(); I != E; ++I)
263     if (I->hasInitializer())
264       EnumerateValue(I->getInitializer());
265
266   // Enumerate the aliasees.
267   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
268        I != E; ++I)
269     EnumerateValue(I->getAliasee());
270
271   // Enumerate the prefix data constants.
272   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
273     if (I->hasPrefixData())
274       EnumerateValue(I->getPrefixData());
275
276   // Insert constants and metadata that are named at module level into the slot
277   // pool so that the module symbol table can refer to them...
278   EnumerateValueSymbolTable(M->getValueSymbolTable());
279   EnumerateNamedMetadata(M);
280
281   SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
282
283   // Enumerate types used by function bodies and argument lists.
284   for (const Function &F : *M) {
285     for (const Argument &A : F.args())
286       EnumerateType(A.getType());
287
288     for (const BasicBlock &BB : F)
289       for (const Instruction &I : BB) {
290         for (const Use &Op : I.operands()) {
291           if (MDNode *MD = dyn_cast<MDNode>(&Op))
292             if (MD->isFunctionLocal() && MD->getFunction())
293               // These will get enumerated during function-incorporation.
294               continue;
295           EnumerateOperandType(Op);
296         }
297         EnumerateType(I.getType());
298         if (const CallInst *CI = dyn_cast<CallInst>(&I))
299           EnumerateAttributes(CI->getAttributes());
300         else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
301           EnumerateAttributes(II->getAttributes());
302
303         // Enumerate metadata attached with this instruction.
304         MDs.clear();
305         I.getAllMetadataOtherThanDebugLoc(MDs);
306         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
307           EnumerateMetadata(MDs[i].second);
308
309         if (!I.getDebugLoc().isUnknown()) {
310           MDNode *Scope, *IA;
311           I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
312           if (Scope) EnumerateMetadata(Scope);
313           if (IA) EnumerateMetadata(IA);
314         }
315       }
316   }
317
318   // Optimize constant ordering.
319   OptimizeConstants(FirstConstant, Values.size());
320 }
321
322 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
323   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
324   assert(I != InstructionMap.end() && "Instruction is not mapped!");
325   return I->second;
326 }
327
328 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
329   unsigned ComdatID = Comdats.idFor(C);
330   assert(ComdatID && "Comdat not found!");
331   return ComdatID;
332 }
333
334 void ValueEnumerator::setInstructionID(const Instruction *I) {
335   InstructionMap[I] = InstructionCount++;
336 }
337
338 unsigned ValueEnumerator::getValueID(const Value *V) const {
339   if (isa<MDNode>(V) || isa<MDString>(V)) {
340     ValueMapType::const_iterator I = MDValueMap.find(V);
341     assert(I != MDValueMap.end() && "Value not in slotcalculator!");
342     return I->second-1;
343   }
344
345   ValueMapType::const_iterator I = ValueMap.find(V);
346   assert(I != ValueMap.end() && "Value not in slotcalculator!");
347   return I->second-1;
348 }
349
350 void ValueEnumerator::dump() const {
351   print(dbgs(), ValueMap, "Default");
352   dbgs() << '\n';
353   print(dbgs(), MDValueMap, "MetaData");
354   dbgs() << '\n';
355 }
356
357 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
358                             const char *Name) const {
359
360   OS << "Map Name: " << Name << "\n";
361   OS << "Size: " << Map.size() << "\n";
362   for (ValueMapType::const_iterator I = Map.begin(),
363          E = Map.end(); I != E; ++I) {
364
365     const Value *V = I->first;
366     if (V->hasName())
367       OS << "Value: " << V->getName();
368     else
369       OS << "Value: [null]\n";
370     V->dump();
371
372     OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
373     for (const Use &U : V->uses()) {
374       if (&U != &*V->use_begin())
375         OS << ",";
376       if(U->hasName())
377         OS << " " << U->getName();
378       else
379         OS << " [null]";
380
381     }
382     OS <<  "\n\n";
383   }
384 }
385
386 /// OptimizeConstants - Reorder constant pool for denser encoding.
387 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
388   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
389
390   if (shouldPreserveBitcodeUseListOrder())
391     // Optimizing constants makes the use-list order difficult to predict.
392     // Disable it for now when trying to preserve the order.
393     return;
394
395   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
396                    [this](const std::pair<const Value *, unsigned> &LHS,
397                           const std::pair<const Value *, unsigned> &RHS) {
398     // Sort by plane.
399     if (LHS.first->getType() != RHS.first->getType())
400       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
401     // Then by frequency.
402     return LHS.second > RHS.second;
403   });
404
405   // Ensure that integer and vector of integer constants are at the start of the
406   // constant pool.  This is important so that GEP structure indices come before
407   // gep constant exprs.
408   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
409                  isIntOrIntVectorValue);
410
411   // Rebuild the modified portion of ValueMap.
412   for (; CstStart != CstEnd; ++CstStart)
413     ValueMap[Values[CstStart].first] = CstStart+1;
414 }
415
416
417 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
418 /// table into the values table.
419 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
420   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
421        VI != VE; ++VI)
422     EnumerateValue(VI->getValue());
423 }
424
425 /// EnumerateNamedMetadata - Insert all of the values referenced by
426 /// named metadata in the specified module.
427 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
428   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
429        E = M->named_metadata_end(); I != E; ++I)
430     EnumerateNamedMDNode(I);
431 }
432
433 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
434   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
435     EnumerateMetadata(MD->getOperand(i));
436 }
437
438 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
439 /// and types referenced by the given MDNode.
440 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
441   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
442     if (Value *V = N->getOperand(i)) {
443       if (isa<MDNode>(V) || isa<MDString>(V))
444         EnumerateMetadata(V);
445       else if (!isa<Instruction>(V) && !isa<Argument>(V))
446         EnumerateValue(V);
447     } else
448       EnumerateType(Type::getVoidTy(N->getContext()));
449   }
450 }
451
452 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
453   assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
454
455   // Enumerate the type of this value.
456   EnumerateType(MD->getType());
457
458   const MDNode *N = dyn_cast<MDNode>(MD);
459
460   // In the module-level pass, skip function-local nodes themselves, but
461   // do walk their operands.
462   if (N && N->isFunctionLocal() && N->getFunction()) {
463     EnumerateMDNodeOperands(N);
464     return;
465   }
466
467   // Check to see if it's already in!
468   unsigned &MDValueID = MDValueMap[MD];
469   if (MDValueID) {
470     // Increment use count.
471     MDValues[MDValueID-1].second++;
472     return;
473   }
474   MDValues.push_back(std::make_pair(MD, 1U));
475   MDValueID = MDValues.size();
476
477   // Enumerate all non-function-local operands.
478   if (N)
479     EnumerateMDNodeOperands(N);
480 }
481
482 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
483 /// information reachable from the given MDNode.
484 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
485   assert(N->isFunctionLocal() && N->getFunction() &&
486          "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
487
488   // Enumerate the type of this value.
489   EnumerateType(N->getType());
490
491   // Check to see if it's already in!
492   unsigned &MDValueID = MDValueMap[N];
493   if (MDValueID) {
494     // Increment use count.
495     MDValues[MDValueID-1].second++;
496     return;
497   }
498   MDValues.push_back(std::make_pair(N, 1U));
499   MDValueID = MDValues.size();
500
501   // To incoroporate function-local information visit all function-local
502   // MDNodes and all function-local values they reference.
503   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
504     if (Value *V = N->getOperand(i)) {
505       if (MDNode *O = dyn_cast<MDNode>(V)) {
506         if (O->isFunctionLocal() && O->getFunction())
507           EnumerateFunctionLocalMetadata(O);
508       } else if (isa<Instruction>(V) || isa<Argument>(V))
509         EnumerateValue(V);
510     }
511
512   // Also, collect all function-local MDNodes for easy access.
513   FunctionLocalMDs.push_back(N);
514 }
515
516 void ValueEnumerator::EnumerateValue(const Value *V) {
517   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
518   assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
519          "EnumerateValue doesn't handle Metadata!");
520
521   // Check to see if it's already in!
522   unsigned &ValueID = ValueMap[V];
523   if (ValueID) {
524     // Increment use count.
525     Values[ValueID-1].second++;
526     return;
527   }
528
529   if (auto *GO = dyn_cast<GlobalObject>(V))
530     if (const Comdat *C = GO->getComdat())
531       Comdats.insert(C);
532
533   // Enumerate the type of this value.
534   EnumerateType(V->getType());
535
536   if (const Constant *C = dyn_cast<Constant>(V)) {
537     if (isa<GlobalValue>(C)) {
538       // Initializers for globals are handled explicitly elsewhere.
539     } else if (C->getNumOperands()) {
540       // If a constant has operands, enumerate them.  This makes sure that if a
541       // constant has uses (for example an array of const ints), that they are
542       // inserted also.
543
544       // We prefer to enumerate them with values before we enumerate the user
545       // itself.  This makes it more likely that we can avoid forward references
546       // in the reader.  We know that there can be no cycles in the constants
547       // graph that don't go through a global variable.
548       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
549            I != E; ++I)
550         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
551           EnumerateValue(*I);
552
553       // Finally, add the value.  Doing this could make the ValueID reference be
554       // dangling, don't reuse it.
555       Values.push_back(std::make_pair(V, 1U));
556       ValueMap[V] = Values.size();
557       return;
558     }
559   }
560
561   // Add the value.
562   Values.push_back(std::make_pair(V, 1U));
563   ValueID = Values.size();
564 }
565
566
567 void ValueEnumerator::EnumerateType(Type *Ty) {
568   unsigned *TypeID = &TypeMap[Ty];
569
570   // We've already seen this type.
571   if (*TypeID)
572     return;
573
574   // If it is a non-anonymous struct, mark the type as being visited so that we
575   // don't recursively visit it.  This is safe because we allow forward
576   // references of these in the bitcode reader.
577   if (StructType *STy = dyn_cast<StructType>(Ty))
578     if (!STy->isLiteral())
579       *TypeID = ~0U;
580
581   // Enumerate all of the subtypes before we enumerate this type.  This ensures
582   // that the type will be enumerated in an order that can be directly built.
583   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
584        I != E; ++I)
585     EnumerateType(*I);
586
587   // Refresh the TypeID pointer in case the table rehashed.
588   TypeID = &TypeMap[Ty];
589
590   // Check to see if we got the pointer another way.  This can happen when
591   // enumerating recursive types that hit the base case deeper than they start.
592   //
593   // If this is actually a struct that we are treating as forward ref'able,
594   // then emit the definition now that all of its contents are available.
595   if (*TypeID && *TypeID != ~0U)
596     return;
597
598   // Add this type now that its contents are all happily enumerated.
599   Types.push_back(Ty);
600
601   *TypeID = Types.size();
602 }
603
604 // Enumerate the types for the specified value.  If the value is a constant,
605 // walk through it, enumerating the types of the constant.
606 void ValueEnumerator::EnumerateOperandType(const Value *V) {
607   EnumerateType(V->getType());
608
609   if (const Constant *C = dyn_cast<Constant>(V)) {
610     // If this constant is already enumerated, ignore it, we know its type must
611     // be enumerated.
612     if (ValueMap.count(V)) return;
613
614     // This constant may have operands, make sure to enumerate the types in
615     // them.
616     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
617       const Value *Op = C->getOperand(i);
618
619       // Don't enumerate basic blocks here, this happens as operands to
620       // blockaddress.
621       if (isa<BasicBlock>(Op)) continue;
622
623       EnumerateOperandType(Op);
624     }
625
626     if (const MDNode *N = dyn_cast<MDNode>(V)) {
627       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
628         if (Value *Elem = N->getOperand(i))
629           EnumerateOperandType(Elem);
630     }
631   } else if (isa<MDString>(V) || isa<MDNode>(V))
632     EnumerateMetadata(V);
633 }
634
635 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
636   if (PAL.isEmpty()) return;  // null is always 0.
637
638   // Do a lookup.
639   unsigned &Entry = AttributeMap[PAL];
640   if (Entry == 0) {
641     // Never saw this before, add it.
642     Attribute.push_back(PAL);
643     Entry = Attribute.size();
644   }
645
646   // Do lookups for all attribute groups.
647   for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
648     AttributeSet AS = PAL.getSlotAttributes(i);
649     unsigned &Entry = AttributeGroupMap[AS];
650     if (Entry == 0) {
651       AttributeGroups.push_back(AS);
652       Entry = AttributeGroups.size();
653     }
654   }
655 }
656
657 void ValueEnumerator::incorporateFunction(const Function &F) {
658   InstructionCount = 0;
659   NumModuleValues = Values.size();
660   NumModuleMDValues = MDValues.size();
661
662   // Adding function arguments to the value table.
663   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
664        I != E; ++I)
665     EnumerateValue(I);
666
667   FirstFuncConstantID = Values.size();
668
669   // Add all function-level constants to the value table.
670   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
671     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
672       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
673            OI != E; ++OI) {
674         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
675             isa<InlineAsm>(*OI))
676           EnumerateValue(*OI);
677       }
678     BasicBlocks.push_back(BB);
679     ValueMap[BB] = BasicBlocks.size();
680   }
681
682   // Optimize the constant layout.
683   OptimizeConstants(FirstFuncConstantID, Values.size());
684
685   // Add the function's parameter attributes so they are available for use in
686   // the function's instruction.
687   EnumerateAttributes(F.getAttributes());
688
689   FirstInstID = Values.size();
690
691   SmallVector<MDNode *, 8> FnLocalMDVector;
692   // Add all of the instructions.
693   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
694     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
695       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
696            OI != E; ++OI) {
697         if (MDNode *MD = dyn_cast<MDNode>(*OI))
698           if (MD->isFunctionLocal() && MD->getFunction())
699             // Enumerate metadata after the instructions they might refer to.
700             FnLocalMDVector.push_back(MD);
701       }
702
703       SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
704       I->getAllMetadataOtherThanDebugLoc(MDs);
705       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
706         MDNode *N = MDs[i].second;
707         if (N->isFunctionLocal() && N->getFunction())
708           FnLocalMDVector.push_back(N);
709       }
710
711       if (!I->getType()->isVoidTy())
712         EnumerateValue(I);
713     }
714   }
715
716   // Add all of the function-local metadata.
717   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
718     EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
719 }
720
721 void ValueEnumerator::purgeFunction() {
722   /// Remove purged values from the ValueMap.
723   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
724     ValueMap.erase(Values[i].first);
725   for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
726     MDValueMap.erase(MDValues[i].first);
727   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
728     ValueMap.erase(BasicBlocks[i]);
729
730   Values.resize(NumModuleValues);
731   MDValues.resize(NumModuleMDValues);
732   BasicBlocks.clear();
733   FunctionLocalMDs.clear();
734 }
735
736 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
737                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
738   unsigned Counter = 0;
739   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
740     IDMap[BB] = ++Counter;
741 }
742
743 /// getGlobalBasicBlockID - This returns the function-specific ID for the
744 /// specified basic block.  This is relatively expensive information, so it
745 /// should only be used by rare constructs such as address-of-label.
746 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
747   unsigned &Idx = GlobalBasicBlockIDs[BB];
748   if (Idx != 0)
749     return Idx-1;
750
751   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
752   return getGlobalBasicBlockID(BB);
753 }
754