LLVM API Documentation
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 // Enumerate the type of this value. 00499 EnumerateType(MD->getType()); 00500 00501 const MDNode *N = dyn_cast<MDNode>(MD); 00502 00503 // In the module-level pass, skip function-local nodes themselves, but 00504 // do walk their operands. 00505 if (N && N->isFunctionLocal() && N->getFunction()) { 00506 EnumerateMDNodeOperands(N); 00507 return; 00508 } 00509 00510 // Check to see if it's already in! 00511 unsigned &MDValueID = MDValueMap[MD]; 00512 if (MDValueID) { 00513 // Increment use count. 00514 MDValues[MDValueID-1].second++; 00515 return; 00516 } 00517 MDValues.push_back(std::make_pair(MD, 1U)); 00518 MDValueID = MDValues.size(); 00519 00520 // Enumerate all non-function-local operands. 00521 if (N) 00522 EnumerateMDNodeOperands(N); 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 // Increment use count. 00538 MDValues[MDValueID-1].second++; 00539 return; 00540 } 00541 MDValues.push_back(std::make_pair(N, 1U)); 00542 MDValueID = MDValues.size(); 00543 00544 // To incoroporate function-local information visit all function-local 00545 // MDNodes and all function-local values they reference. 00546 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 00547 if (Value *V = N->getOperand(i)) { 00548 if (MDNode *O = dyn_cast<MDNode>(V)) { 00549 if (O->isFunctionLocal() && O->getFunction()) 00550 EnumerateFunctionLocalMetadata(O); 00551 } else if (isa<Instruction>(V) || isa<Argument>(V)) 00552 EnumerateValue(V); 00553 } 00554 00555 // Also, collect all function-local MDNodes for easy access. 00556 FunctionLocalMDs.push_back(N); 00557 } 00558 00559 void ValueEnumerator::EnumerateValue(const Value *V) { 00560 assert(!V->getType()->isVoidTy() && "Can't insert void values!"); 00561 assert(!isa<MDNode>(V) && !isa<MDString>(V) && 00562 "EnumerateValue doesn't handle Metadata!"); 00563 00564 // Check to see if it's already in! 00565 unsigned &ValueID = ValueMap[V]; 00566 if (ValueID) { 00567 // Increment use count. 00568 Values[ValueID-1].second++; 00569 return; 00570 } 00571 00572 if (auto *GO = dyn_cast<GlobalObject>(V)) 00573 if (const Comdat *C = GO->getComdat()) 00574 Comdats.insert(C); 00575 00576 // Enumerate the type of this value. 00577 EnumerateType(V->getType()); 00578 00579 if (const Constant *C = dyn_cast<Constant>(V)) { 00580 if (isa<GlobalValue>(C)) { 00581 // Initializers for globals are handled explicitly elsewhere. 00582 } else if (C->getNumOperands()) { 00583 // If a constant has operands, enumerate them. This makes sure that if a 00584 // constant has uses (for example an array of const ints), that they are 00585 // inserted also. 00586 00587 // We prefer to enumerate them with values before we enumerate the user 00588 // itself. This makes it more likely that we can avoid forward references 00589 // in the reader. We know that there can be no cycles in the constants 00590 // graph that don't go through a global variable. 00591 for (User::const_op_iterator I = C->op_begin(), E = C->op_end(); 00592 I != E; ++I) 00593 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress. 00594 EnumerateValue(*I); 00595 00596 // Finally, add the value. Doing this could make the ValueID reference be 00597 // dangling, don't reuse it. 00598 Values.push_back(std::make_pair(V, 1U)); 00599 ValueMap[V] = Values.size(); 00600 return; 00601 } 00602 } 00603 00604 // Add the value. 00605 Values.push_back(std::make_pair(V, 1U)); 00606 ValueID = Values.size(); 00607 } 00608 00609 00610 void ValueEnumerator::EnumerateType(Type *Ty) { 00611 unsigned *TypeID = &TypeMap[Ty]; 00612 00613 // We've already seen this type. 00614 if (*TypeID) 00615 return; 00616 00617 // If it is a non-anonymous struct, mark the type as being visited so that we 00618 // don't recursively visit it. This is safe because we allow forward 00619 // references of these in the bitcode reader. 00620 if (StructType *STy = dyn_cast<StructType>(Ty)) 00621 if (!STy->isLiteral()) 00622 *TypeID = ~0U; 00623 00624 // Enumerate all of the subtypes before we enumerate this type. This ensures 00625 // that the type will be enumerated in an order that can be directly built. 00626 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 00627 I != E; ++I) 00628 EnumerateType(*I); 00629 00630 // Refresh the TypeID pointer in case the table rehashed. 00631 TypeID = &TypeMap[Ty]; 00632 00633 // Check to see if we got the pointer another way. This can happen when 00634 // enumerating recursive types that hit the base case deeper than they start. 00635 // 00636 // If this is actually a struct that we are treating as forward ref'able, 00637 // then emit the definition now that all of its contents are available. 00638 if (*TypeID && *TypeID != ~0U) 00639 return; 00640 00641 // Add this type now that its contents are all happily enumerated. 00642 Types.push_back(Ty); 00643 00644 *TypeID = Types.size(); 00645 } 00646 00647 // Enumerate the types for the specified value. If the value is a constant, 00648 // walk through it, enumerating the types of the constant. 00649 void ValueEnumerator::EnumerateOperandType(const Value *V) { 00650 EnumerateType(V->getType()); 00651 00652 if (const Constant *C = dyn_cast<Constant>(V)) { 00653 // If this constant is already enumerated, ignore it, we know its type must 00654 // be enumerated. 00655 if (ValueMap.count(V)) return; 00656 00657 // This constant may have operands, make sure to enumerate the types in 00658 // them. 00659 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) { 00660 const Value *Op = C->getOperand(i); 00661 00662 // Don't enumerate basic blocks here, this happens as operands to 00663 // blockaddress. 00664 if (isa<BasicBlock>(Op)) continue; 00665 00666 EnumerateOperandType(Op); 00667 } 00668 00669 if (const MDNode *N = dyn_cast<MDNode>(V)) { 00670 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 00671 if (Value *Elem = N->getOperand(i)) 00672 EnumerateOperandType(Elem); 00673 } 00674 } else if (isa<MDString>(V) || isa<MDNode>(V)) 00675 EnumerateMetadata(V); 00676 } 00677 00678 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) { 00679 if (PAL.isEmpty()) return; // null is always 0. 00680 00681 // Do a lookup. 00682 unsigned &Entry = AttributeMap[PAL]; 00683 if (Entry == 0) { 00684 // Never saw this before, add it. 00685 Attribute.push_back(PAL); 00686 Entry = Attribute.size(); 00687 } 00688 00689 // Do lookups for all attribute groups. 00690 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) { 00691 AttributeSet AS = PAL.getSlotAttributes(i); 00692 unsigned &Entry = AttributeGroupMap[AS]; 00693 if (Entry == 0) { 00694 AttributeGroups.push_back(AS); 00695 Entry = AttributeGroups.size(); 00696 } 00697 } 00698 } 00699 00700 void ValueEnumerator::incorporateFunction(const Function &F) { 00701 InstructionCount = 0; 00702 NumModuleValues = Values.size(); 00703 NumModuleMDValues = MDValues.size(); 00704 00705 // Adding function arguments to the value table. 00706 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 00707 I != E; ++I) 00708 EnumerateValue(I); 00709 00710 FirstFuncConstantID = Values.size(); 00711 00712 // Add all function-level constants to the value table. 00713 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 00714 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) 00715 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 00716 OI != E; ++OI) { 00717 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) || 00718 isa<InlineAsm>(*OI)) 00719 EnumerateValue(*OI); 00720 } 00721 BasicBlocks.push_back(BB); 00722 ValueMap[BB] = BasicBlocks.size(); 00723 } 00724 00725 // Optimize the constant layout. 00726 OptimizeConstants(FirstFuncConstantID, Values.size()); 00727 00728 // Add the function's parameter attributes so they are available for use in 00729 // the function's instruction. 00730 EnumerateAttributes(F.getAttributes()); 00731 00732 FirstInstID = Values.size(); 00733 00734 SmallVector<MDNode *, 8> FnLocalMDVector; 00735 // Add all of the instructions. 00736 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 00737 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) { 00738 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 00739 OI != E; ++OI) { 00740 if (MDNode *MD = dyn_cast<MDNode>(*OI)) 00741 if (MD->isFunctionLocal() && MD->getFunction()) 00742 // Enumerate metadata after the instructions they might refer to. 00743 FnLocalMDVector.push_back(MD); 00744 } 00745 00746 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs; 00747 I->getAllMetadataOtherThanDebugLoc(MDs); 00748 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 00749 MDNode *N = MDs[i].second; 00750 if (N->isFunctionLocal() && N->getFunction()) 00751 FnLocalMDVector.push_back(N); 00752 } 00753 00754 if (!I->getType()->isVoidTy()) 00755 EnumerateValue(I); 00756 } 00757 } 00758 00759 // Add all of the function-local metadata. 00760 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) 00761 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]); 00762 } 00763 00764 void ValueEnumerator::purgeFunction() { 00765 /// Remove purged values from the ValueMap. 00766 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i) 00767 ValueMap.erase(Values[i].first); 00768 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i) 00769 MDValueMap.erase(MDValues[i].first); 00770 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i) 00771 ValueMap.erase(BasicBlocks[i]); 00772 00773 Values.resize(NumModuleValues); 00774 MDValues.resize(NumModuleMDValues); 00775 BasicBlocks.clear(); 00776 FunctionLocalMDs.clear(); 00777 } 00778 00779 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, 00780 DenseMap<const BasicBlock*, unsigned> &IDMap) { 00781 unsigned Counter = 0; 00782 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 00783 IDMap[BB] = ++Counter; 00784 } 00785 00786 /// getGlobalBasicBlockID - This returns the function-specific ID for the 00787 /// specified basic block. This is relatively expensive information, so it 00788 /// should only be used by rare constructs such as address-of-label. 00789 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const { 00790 unsigned &Idx = GlobalBasicBlockIDs[BB]; 00791 if (Idx != 0) 00792 return Idx-1; 00793 00794 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs); 00795 return getGlobalBasicBlockID(BB); 00796 } 00797