LLVM API Documentation

ValueEnumerator.cpp
Go to the documentation of this file.
00001 //===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the ValueEnumerator class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ValueEnumerator.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/IR/Constants.h"
00018 #include "llvm/IR/DerivedTypes.h"
00019 #include "llvm/IR/Instructions.h"
00020 #include "llvm/IR/Module.h"
00021 #include "llvm/IR/UseListOrder.h"
00022 #include "llvm/IR/ValueSymbolTable.h"
00023 #include "llvm/Support/Debug.h"
00024 #include "llvm/Support/raw_ostream.h"
00025 #include <algorithm>
00026 using namespace llvm;
00027 
00028 namespace {
00029 struct OrderMap {
00030   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
00031   unsigned LastGlobalConstantID;
00032   unsigned LastGlobalValueID;
00033 
00034   OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
00035 
00036   bool isGlobalConstant(unsigned ID) const {
00037     return ID <= LastGlobalConstantID;
00038   }
00039   bool isGlobalValue(unsigned ID) const {
00040     return ID <= LastGlobalValueID && !isGlobalConstant(ID);
00041   }
00042 
00043   unsigned size() const { return IDs.size(); }
00044   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
00045   std::pair<unsigned, bool> lookup(const Value *V) const {
00046     return IDs.lookup(V);
00047   }
00048   void index(const Value *V) {
00049     // Explicitly sequence get-size and insert-value operations to avoid UB.
00050     unsigned ID = IDs.size() + 1;
00051     IDs[V].first = ID;
00052   }
00053 };
00054 }
00055 
00056 static void orderValue(const Value *V, OrderMap &OM) {
00057   if (OM.lookup(V).first)
00058     return;
00059 
00060   if (const Constant *C = dyn_cast<Constant>(V))
00061     if (C->getNumOperands() && !isa<GlobalValue>(C))
00062       for (const Value *Op : C->operands())
00063         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
00064           orderValue(Op, OM);
00065 
00066   // Note: we cannot cache this lookup above, since inserting into the map
00067   // changes the map's size, and thus affects the other IDs.
00068   OM.index(V);
00069 }
00070 
00071 static OrderMap orderModule(const Module *M) {
00072   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
00073   // and ValueEnumerator::incorporateFunction().
00074   OrderMap OM;
00075 
00076   // In the reader, initializers of GlobalValues are set *after* all the
00077   // globals have been read.  Rather than awkwardly modeling this behaviour
00078   // directly in predictValueUseListOrderImpl(), just assign IDs to
00079   // initializers of GlobalValues before GlobalValues themselves to model this
00080   // implicitly.
00081   for (const GlobalVariable &G : M->globals())
00082     if (G.hasInitializer())
00083       if (!isa<GlobalValue>(G.getInitializer()))
00084         orderValue(G.getInitializer(), OM);
00085   for (const GlobalAlias &A : M->aliases())
00086     if (!isa<GlobalValue>(A.getAliasee()))
00087       orderValue(A.getAliasee(), OM);
00088   for (const Function &F : *M)
00089     if (F.hasPrefixData())
00090       if (!isa<GlobalValue>(F.getPrefixData()))
00091         orderValue(F.getPrefixData(), OM);
00092   OM.LastGlobalConstantID = OM.size();
00093 
00094   // Initializers of GlobalValues are processed in
00095   // BitcodeReader::ResolveGlobalAndAliasInits().  Match the order there rather
00096   // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
00097   // by giving IDs in reverse order.
00098   //
00099   // Since GlobalValues never reference each other directly (just through
00100   // initializers), their relative IDs only matter for determining order of
00101   // uses in their initializers.
00102   for (const Function &F : *M)
00103     orderValue(&F, OM);
00104   for (const GlobalAlias &A : M->aliases())
00105     orderValue(&A, OM);
00106   for (const GlobalVariable &G : M->globals())
00107     orderValue(&G, OM);
00108   OM.LastGlobalValueID = OM.size();
00109 
00110   for (const Function &F : *M) {
00111     if (F.isDeclaration())
00112       continue;
00113     // Here we need to match the union of ValueEnumerator::incorporateFunction()
00114     // and WriteFunction().  Basic blocks are implicitly declared before
00115     // anything else (by declaring their size).
00116     for (const BasicBlock &BB : F)
00117       orderValue(&BB, OM);
00118     for (const Argument &A : F.args())
00119       orderValue(&A, OM);
00120     for (const BasicBlock &BB : F)
00121       for (const Instruction &I : BB)
00122         for (const Value *Op : I.operands())
00123           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
00124               isa<InlineAsm>(*Op))
00125             orderValue(Op, OM);
00126     for (const BasicBlock &BB : F)
00127       for (const Instruction &I : BB)
00128         orderValue(&I, OM);
00129   }
00130   return OM;
00131 }
00132 
00133 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
00134                                          unsigned ID, const OrderMap &OM,
00135                                          UseListOrderStack &Stack) {
00136   // Predict use-list order for this one.
00137   typedef std::pair<const Use *, unsigned> Entry;
00138   SmallVector<Entry, 64> List;
00139   for (const Use &U : V->uses())
00140     // Check if this user will be serialized.
00141     if (OM.lookup(U.getUser()).first)
00142       List.push_back(std::make_pair(&U, List.size()));
00143 
00144   if (List.size() < 2)
00145     // We may have lost some users.
00146     return;
00147 
00148   bool IsGlobalValue = OM.isGlobalValue(ID);
00149   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
00150     const Use *LU = L.first;
00151     const Use *RU = R.first;
00152     if (LU == RU)
00153       return false;
00154 
00155     auto LID = OM.lookup(LU->getUser()).first;
00156     auto RID = OM.lookup(RU->getUser()).first;
00157 
00158     // Global values are processed in reverse order.
00159     //
00160     // Moreover, initializers of GlobalValues are set *after* all the globals
00161     // have been read (despite having earlier IDs).  Rather than awkwardly
00162     // modeling this behaviour here, orderModule() has assigned IDs to
00163     // initializers of GlobalValues before GlobalValues themselves.
00164     if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
00165       return LID < RID;
00166 
00167     // If ID is 4, then expect: 7 6 5 1 2 3.
00168     if (LID < RID) {
00169       if (RID <= ID)
00170         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
00171           return true;
00172       return false;
00173     }
00174     if (RID < LID) {
00175       if (LID <= ID)
00176         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
00177           return false;
00178       return true;
00179     }
00180 
00181     // LID and RID are equal, so we have different operands of the same user.
00182     // Assume operands are added in order for all instructions.
00183     if (LID <= ID)
00184       if (!IsGlobalValue) // GlobalValue uses don't get reversed.
00185         return LU->getOperandNo() < RU->getOperandNo();
00186     return LU->getOperandNo() > RU->getOperandNo();
00187   });
00188 
00189   if (std::is_sorted(
00190           List.begin(), List.end(),
00191           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
00192     // Order is already correct.
00193     return;
00194 
00195   // Store the shuffle.
00196   Stack.emplace_back(V, F, List.size());
00197   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
00198   for (size_t I = 0, E = List.size(); I != E; ++I)
00199     Stack.back().Shuffle[I] = List[I].second;
00200 }
00201 
00202 static void predictValueUseListOrder(const Value *V, const Function *F,
00203                                      OrderMap &OM, UseListOrderStack &Stack) {
00204   auto &IDPair = OM[V];
00205   assert(IDPair.first && "Unmapped value");
00206   if (IDPair.second)
00207     // Already predicted.
00208     return;
00209 
00210   // Do the actual prediction.
00211   IDPair.second = true;
00212   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
00213     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
00214 
00215   // Recursive descent into constants.
00216   if (const Constant *C = dyn_cast<Constant>(V))
00217     if (C->getNumOperands()) // Visit GlobalValues.
00218       for (const Value *Op : C->operands())
00219         if (isa<Constant>(Op)) // Visit GlobalValues.
00220           predictValueUseListOrder(Op, F, OM, Stack);
00221 }
00222 
00223 static UseListOrderStack predictUseListOrder(const Module *M) {
00224   OrderMap OM = orderModule(M);
00225 
00226   // Use-list orders need to be serialized after all the users have been added
00227   // to a value, or else the shuffles will be incomplete.  Store them per
00228   // function in a stack.
00229   //
00230   // Aside from function order, the order of values doesn't matter much here.
00231   UseListOrderStack Stack;
00232 
00233   // We want to visit the functions backward now so we can list function-local
00234   // constants in the last Function they're used in.  Module-level constants
00235   // have already been visited above.
00236   for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
00237     const Function &F = *I;
00238     if (F.isDeclaration())
00239       continue;
00240     for (const BasicBlock &BB : F)
00241       predictValueUseListOrder(&BB, &F, OM, Stack);
00242     for (const Argument &A : F.args())
00243       predictValueUseListOrder(&A, &F, OM, Stack);
00244     for (const BasicBlock &BB : F)
00245       for (const Instruction &I : BB)
00246         for (const Value *Op : I.operands())
00247           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
00248             predictValueUseListOrder(Op, &F, OM, Stack);
00249     for (const BasicBlock &BB : F)
00250       for (const Instruction &I : BB)
00251         predictValueUseListOrder(&I, &F, OM, Stack);
00252   }
00253 
00254   // Visit globals last, since the module-level use-list block will be seen
00255   // before the function bodies are processed.
00256   for (const GlobalVariable &G : M->globals())
00257     predictValueUseListOrder(&G, nullptr, OM, Stack);
00258   for (const Function &F : *M)
00259     predictValueUseListOrder(&F, nullptr, OM, Stack);
00260   for (const GlobalAlias &A : M->aliases())
00261     predictValueUseListOrder(&A, nullptr, OM, Stack);
00262   for (const GlobalVariable &G : M->globals())
00263     if (G.hasInitializer())
00264       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
00265   for (const GlobalAlias &A : M->aliases())
00266     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
00267   for (const Function &F : *M)
00268     if (F.hasPrefixData())
00269       predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
00270 
00271   return Stack;
00272 }
00273 
00274 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
00275   return V.first->getType()->isIntOrIntVectorTy();
00276 }
00277 
00278 /// ValueEnumerator - Enumerate module-level information.
00279 ValueEnumerator::ValueEnumerator(const Module *M) {
00280   if (shouldPreserveBitcodeUseListOrder())
00281     UseListOrders = predictUseListOrder(M);
00282 
00283   // Enumerate the global variables.
00284   for (Module::const_global_iterator I = M->global_begin(),
00285 
00286          E = M->global_end(); I != E; ++I)
00287     EnumerateValue(I);
00288 
00289   // Enumerate the functions.
00290   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
00291     EnumerateValue(I);
00292     EnumerateAttributes(cast<Function>(I)->getAttributes());
00293   }
00294 
00295   // Enumerate the aliases.
00296   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
00297        I != E; ++I)
00298     EnumerateValue(I);
00299 
00300   // Remember what is the cutoff between globalvalue's and other constants.
00301   unsigned FirstConstant = Values.size();
00302 
00303   // Enumerate the global variable initializers.
00304   for (Module::const_global_iterator I = M->global_begin(),
00305          E = M->global_end(); I != E; ++I)
00306     if (I->hasInitializer())
00307       EnumerateValue(I->getInitializer());
00308 
00309   // Enumerate the aliasees.
00310   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
00311        I != E; ++I)
00312     EnumerateValue(I->getAliasee());
00313 
00314   // Enumerate the prefix data constants.
00315   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
00316     if (I->hasPrefixData())
00317       EnumerateValue(I->getPrefixData());
00318 
00319   // Insert constants and metadata that are named at module level into the slot
00320   // pool so that the module symbol table can refer to them...
00321   EnumerateValueSymbolTable(M->getValueSymbolTable());
00322   EnumerateNamedMetadata(M);
00323 
00324   SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
00325 
00326   // Enumerate types used by function bodies and argument lists.
00327   for (const Function &F : *M) {
00328     for (const Argument &A : F.args())
00329       EnumerateType(A.getType());
00330 
00331     for (const BasicBlock &BB : F)
00332       for (const Instruction &I : BB) {
00333         for (const Use &Op : I.operands()) {
00334           if (MDNode *MD = dyn_cast<MDNode>(&Op))
00335             if (MD->isFunctionLocal() && MD->getFunction())
00336               // These will get enumerated during function-incorporation.
00337               continue;
00338           EnumerateOperandType(Op);
00339         }
00340         EnumerateType(I.getType());
00341         if (const CallInst *CI = dyn_cast<CallInst>(&I))
00342           EnumerateAttributes(CI->getAttributes());
00343         else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
00344           EnumerateAttributes(II->getAttributes());
00345 
00346         // Enumerate metadata attached with this instruction.
00347         MDs.clear();
00348         I.getAllMetadataOtherThanDebugLoc(MDs);
00349         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
00350           EnumerateMetadata(MDs[i].second);
00351 
00352         if (!I.getDebugLoc().isUnknown()) {
00353           MDNode *Scope, *IA;
00354           I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
00355           if (Scope) EnumerateMetadata(Scope);
00356           if (IA) EnumerateMetadata(IA);
00357         }
00358       }
00359   }
00360 
00361   // Optimize constant ordering.
00362   OptimizeConstants(FirstConstant, Values.size());
00363 }
00364 
00365 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
00366   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
00367   assert(I != InstructionMap.end() && "Instruction is not mapped!");
00368   return I->second;
00369 }
00370 
00371 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
00372   unsigned ComdatID = Comdats.idFor(C);
00373   assert(ComdatID && "Comdat not found!");
00374   return ComdatID;
00375 }
00376 
00377 void ValueEnumerator::setInstructionID(const Instruction *I) {
00378   InstructionMap[I] = InstructionCount++;
00379 }
00380 
00381 unsigned ValueEnumerator::getValueID(const Value *V) const {
00382   if (isa<MDNode>(V) || isa<MDString>(V)) {
00383     ValueMapType::const_iterator I = MDValueMap.find(V);
00384     assert(I != MDValueMap.end() && "Value not in slotcalculator!");
00385     return I->second-1;
00386   }
00387 
00388   ValueMapType::const_iterator I = ValueMap.find(V);
00389   assert(I != ValueMap.end() && "Value not in slotcalculator!");
00390   return I->second-1;
00391 }
00392 
00393 void ValueEnumerator::dump() const {
00394   print(dbgs(), ValueMap, "Default");
00395   dbgs() << '\n';
00396   print(dbgs(), MDValueMap, "MetaData");
00397   dbgs() << '\n';
00398 }
00399 
00400 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
00401                             const char *Name) const {
00402 
00403   OS << "Map Name: " << Name << "\n";
00404   OS << "Size: " << Map.size() << "\n";
00405   for (ValueMapType::const_iterator I = Map.begin(),
00406          E = Map.end(); I != E; ++I) {
00407 
00408     const Value *V = I->first;
00409     if (V->hasName())
00410       OS << "Value: " << V->getName();
00411     else
00412       OS << "Value: [null]\n";
00413     V->dump();
00414 
00415     OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
00416     for (const Use &U : V->uses()) {
00417       if (&U != &*V->use_begin())
00418         OS << ",";
00419       if(U->hasName())
00420         OS << " " << U->getName();
00421       else
00422         OS << " [null]";
00423 
00424     }
00425     OS <<  "\n\n";
00426   }
00427 }
00428 
00429 /// OptimizeConstants - Reorder constant pool for denser encoding.
00430 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
00431   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
00432 
00433   if (shouldPreserveBitcodeUseListOrder())
00434     // Optimizing constants makes the use-list order difficult to predict.
00435     // Disable it for now when trying to preserve the order.
00436     return;
00437 
00438   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
00439                    [this](const std::pair<const Value *, unsigned> &LHS,
00440                           const std::pair<const Value *, unsigned> &RHS) {
00441     // Sort by plane.
00442     if (LHS.first->getType() != RHS.first->getType())
00443       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
00444     // Then by frequency.
00445     return LHS.second > RHS.second;
00446   });
00447 
00448   // Ensure that integer and vector of integer constants are at the start of the
00449   // constant pool.  This is important so that GEP structure indices come before
00450   // gep constant exprs.
00451   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
00452                  isIntOrIntVectorValue);
00453 
00454   // Rebuild the modified portion of ValueMap.
00455   for (; CstStart != CstEnd; ++CstStart)
00456     ValueMap[Values[CstStart].first] = CstStart+1;
00457 }
00458 
00459 
00460 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
00461 /// table into the values table.
00462 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
00463   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
00464        VI != VE; ++VI)
00465     EnumerateValue(VI->getValue());
00466 }
00467 
00468 /// EnumerateNamedMetadata - Insert all of the values referenced by
00469 /// named metadata in the specified module.
00470 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
00471   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
00472        E = M->named_metadata_end(); I != E; ++I)
00473     EnumerateNamedMDNode(I);
00474 }
00475 
00476 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
00477   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
00478     EnumerateMetadata(MD->getOperand(i));
00479 }
00480 
00481 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
00482 /// and types referenced by the given MDNode.
00483 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
00484   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00485     if (Value *V = N->getOperand(i)) {
00486       if (isa<MDNode>(V) || isa<MDString>(V))
00487         EnumerateMetadata(V);
00488       else if (!isa<Instruction>(V) && !isa<Argument>(V))
00489         EnumerateValue(V);
00490     } else
00491       EnumerateType(Type::getVoidTy(N->getContext()));
00492   }
00493 }
00494 
00495 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
00496   assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
00497 
00498   // Skip function-local nodes themselves, but walk their operands.
00499   const MDNode *N = dyn_cast<MDNode>(MD);
00500   if (N && N->isFunctionLocal() && N->getFunction()) {
00501     EnumerateMDNodeOperands(N);
00502     return;
00503   }
00504 
00505   // Insert a dummy ID to block the co-recursive call to
00506   // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
00507   //
00508   // Return early if there's already an ID.
00509   if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
00510     return;
00511 
00512   // Enumerate the type of this value.
00513   EnumerateType(MD->getType());
00514 
00515   // Visit operands first to minimize RAUW.
00516   if (N)
00517     EnumerateMDNodeOperands(N);
00518 
00519   // Replace the dummy ID inserted above with the correct one.  MDValueMap may
00520   // have changed by inserting operands, so we need a fresh lookup here.
00521   MDValues.push_back(MD);
00522   MDValueMap[MD] = MDValues.size();
00523 }
00524 
00525 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
00526 /// information reachable from the given MDNode.
00527 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
00528   assert(N->isFunctionLocal() && N->getFunction() &&
00529          "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
00530 
00531   // Enumerate the type of this value.
00532   EnumerateType(N->getType());
00533 
00534   // Check to see if it's already in!
00535   unsigned &MDValueID = MDValueMap[N];
00536   if (MDValueID)
00537     return;
00538 
00539   MDValues.push_back(N);
00540   MDValueID = MDValues.size();
00541 
00542   // To incoroporate function-local information visit all function-local
00543   // MDNodes and all function-local values they reference.
00544   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00545     if (Value *V = N->getOperand(i)) {
00546       if (MDNode *O = dyn_cast<MDNode>(V)) {
00547         if (O->isFunctionLocal() && O->getFunction())
00548           EnumerateFunctionLocalMetadata(O);
00549       } else if (isa<Instruction>(V) || isa<Argument>(V))
00550         EnumerateValue(V);
00551     }
00552 
00553   // Also, collect all function-local MDNodes for easy access.
00554   FunctionLocalMDs.push_back(N);
00555 }
00556 
00557 void ValueEnumerator::EnumerateValue(const Value *V) {
00558   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
00559   assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
00560          "EnumerateValue doesn't handle Metadata!");
00561 
00562   // Check to see if it's already in!
00563   unsigned &ValueID = ValueMap[V];
00564   if (ValueID) {
00565     // Increment use count.
00566     Values[ValueID-1].second++;
00567     return;
00568   }
00569 
00570   if (auto *GO = dyn_cast<GlobalObject>(V))
00571     if (const Comdat *C = GO->getComdat())
00572       Comdats.insert(C);
00573 
00574   // Enumerate the type of this value.
00575   EnumerateType(V->getType());
00576 
00577   if (const Constant *C = dyn_cast<Constant>(V)) {
00578     if (isa<GlobalValue>(C)) {
00579       // Initializers for globals are handled explicitly elsewhere.
00580     } else if (C->getNumOperands()) {
00581       // If a constant has operands, enumerate them.  This makes sure that if a
00582       // constant has uses (for example an array of const ints), that they are
00583       // inserted also.
00584 
00585       // We prefer to enumerate them with values before we enumerate the user
00586       // itself.  This makes it more likely that we can avoid forward references
00587       // in the reader.  We know that there can be no cycles in the constants
00588       // graph that don't go through a global variable.
00589       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
00590            I != E; ++I)
00591         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
00592           EnumerateValue(*I);
00593 
00594       // Finally, add the value.  Doing this could make the ValueID reference be
00595       // dangling, don't reuse it.
00596       Values.push_back(std::make_pair(V, 1U));
00597       ValueMap[V] = Values.size();
00598       return;
00599     }
00600   }
00601 
00602   // Add the value.
00603   Values.push_back(std::make_pair(V, 1U));
00604   ValueID = Values.size();
00605 }
00606 
00607 
00608 void ValueEnumerator::EnumerateType(Type *Ty) {
00609   unsigned *TypeID = &TypeMap[Ty];
00610 
00611   // We've already seen this type.
00612   if (*TypeID)
00613     return;
00614 
00615   // If it is a non-anonymous struct, mark the type as being visited so that we
00616   // don't recursively visit it.  This is safe because we allow forward
00617   // references of these in the bitcode reader.
00618   if (StructType *STy = dyn_cast<StructType>(Ty))
00619     if (!STy->isLiteral())
00620       *TypeID = ~0U;
00621 
00622   // Enumerate all of the subtypes before we enumerate this type.  This ensures
00623   // that the type will be enumerated in an order that can be directly built.
00624   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00625        I != E; ++I)
00626     EnumerateType(*I);
00627 
00628   // Refresh the TypeID pointer in case the table rehashed.
00629   TypeID = &TypeMap[Ty];
00630 
00631   // Check to see if we got the pointer another way.  This can happen when
00632   // enumerating recursive types that hit the base case deeper than they start.
00633   //
00634   // If this is actually a struct that we are treating as forward ref'able,
00635   // then emit the definition now that all of its contents are available.
00636   if (*TypeID && *TypeID != ~0U)
00637     return;
00638 
00639   // Add this type now that its contents are all happily enumerated.
00640   Types.push_back(Ty);
00641 
00642   *TypeID = Types.size();
00643 }
00644 
00645 // Enumerate the types for the specified value.  If the value is a constant,
00646 // walk through it, enumerating the types of the constant.
00647 void ValueEnumerator::EnumerateOperandType(const Value *V) {
00648   EnumerateType(V->getType());
00649 
00650   if (const Constant *C = dyn_cast<Constant>(V)) {
00651     // If this constant is already enumerated, ignore it, we know its type must
00652     // be enumerated.
00653     if (ValueMap.count(V)) return;
00654 
00655     // This constant may have operands, make sure to enumerate the types in
00656     // them.
00657     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
00658       const Value *Op = C->getOperand(i);
00659 
00660       // Don't enumerate basic blocks here, this happens as operands to
00661       // blockaddress.
00662       if (isa<BasicBlock>(Op)) continue;
00663 
00664       EnumerateOperandType(Op);
00665     }
00666 
00667     if (const MDNode *N = dyn_cast<MDNode>(V)) {
00668       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00669         if (Value *Elem = N->getOperand(i))
00670           EnumerateOperandType(Elem);
00671     }
00672   } else if (isa<MDString>(V) || isa<MDNode>(V))
00673     EnumerateMetadata(V);
00674 }
00675 
00676 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
00677   if (PAL.isEmpty()) return;  // null is always 0.
00678 
00679   // Do a lookup.
00680   unsigned &Entry = AttributeMap[PAL];
00681   if (Entry == 0) {
00682     // Never saw this before, add it.
00683     Attribute.push_back(PAL);
00684     Entry = Attribute.size();
00685   }
00686 
00687   // Do lookups for all attribute groups.
00688   for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
00689     AttributeSet AS = PAL.getSlotAttributes(i);
00690     unsigned &Entry = AttributeGroupMap[AS];
00691     if (Entry == 0) {
00692       AttributeGroups.push_back(AS);
00693       Entry = AttributeGroups.size();
00694     }
00695   }
00696 }
00697 
00698 void ValueEnumerator::incorporateFunction(const Function &F) {
00699   InstructionCount = 0;
00700   NumModuleValues = Values.size();
00701   NumModuleMDValues = MDValues.size();
00702 
00703   // Adding function arguments to the value table.
00704   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
00705        I != E; ++I)
00706     EnumerateValue(I);
00707 
00708   FirstFuncConstantID = Values.size();
00709 
00710   // Add all function-level constants to the value table.
00711   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00712     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
00713       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00714            OI != E; ++OI) {
00715         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
00716             isa<InlineAsm>(*OI))
00717           EnumerateValue(*OI);
00718       }
00719     BasicBlocks.push_back(BB);
00720     ValueMap[BB] = BasicBlocks.size();
00721   }
00722 
00723   // Optimize the constant layout.
00724   OptimizeConstants(FirstFuncConstantID, Values.size());
00725 
00726   // Add the function's parameter attributes so they are available for use in
00727   // the function's instruction.
00728   EnumerateAttributes(F.getAttributes());
00729 
00730   FirstInstID = Values.size();
00731 
00732   SmallVector<MDNode *, 8> FnLocalMDVector;
00733   // Add all of the instructions.
00734   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00735     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
00736       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00737            OI != E; ++OI) {
00738         if (MDNode *MD = dyn_cast<MDNode>(*OI))
00739           if (MD->isFunctionLocal() && MD->getFunction())
00740             // Enumerate metadata after the instructions they might refer to.
00741             FnLocalMDVector.push_back(MD);
00742       }
00743 
00744       SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
00745       I->getAllMetadataOtherThanDebugLoc(MDs);
00746       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
00747         MDNode *N = MDs[i].second;
00748         if (N->isFunctionLocal() && N->getFunction())
00749           FnLocalMDVector.push_back(N);
00750       }
00751 
00752       if (!I->getType()->isVoidTy())
00753         EnumerateValue(I);
00754     }
00755   }
00756 
00757   // Add all of the function-local metadata.
00758   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
00759     EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
00760 }
00761 
00762 void ValueEnumerator::purgeFunction() {
00763   /// Remove purged values from the ValueMap.
00764   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
00765     ValueMap.erase(Values[i].first);
00766   for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
00767     MDValueMap.erase(MDValues[i]);
00768   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
00769     ValueMap.erase(BasicBlocks[i]);
00770 
00771   Values.resize(NumModuleValues);
00772   MDValues.resize(NumModuleMDValues);
00773   BasicBlocks.clear();
00774   FunctionLocalMDs.clear();
00775 }
00776 
00777 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
00778                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
00779   unsigned Counter = 0;
00780   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00781     IDMap[BB] = ++Counter;
00782 }
00783 
00784 /// getGlobalBasicBlockID - This returns the function-specific ID for the
00785 /// specified basic block.  This is relatively expensive information, so it
00786 /// should only be used by rare constructs such as address-of-label.
00787 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
00788   unsigned &Idx = GlobalBasicBlockIDs[BB];
00789   if (Idx != 0)
00790     return Idx-1;
00791 
00792   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
00793   return getGlobalBasicBlockID(BB);
00794 }
00795