OSDN Git Service

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