1 //===-- Module.cpp - Implement the Module class ---------------------------===// 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 Module class for the IR library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Module.h" 15 #include "SymbolTableListTraitsImpl.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/GVMaterializer.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DerivedTypes.h" 23 #include "llvm/IR/InstrTypes.h" 24 #include "llvm/IR/LLVMContext.h" 25 #include "llvm/Support/LeakDetector.h" 26 #include <algorithm> 27 #include <cstdarg> 28 #include <cstdlib> 29 using namespace llvm; 30 31 //===----------------------------------------------------------------------===// 32 // Methods to implement the globals and functions lists. 33 // 34 35 // Explicit instantiations of SymbolTableListTraits since some of the methods 36 // are not in the public header file. 37 template class llvm::SymbolTableListTraits<Function, Module>; 38 template class llvm::SymbolTableListTraits<GlobalVariable, Module>; 39 template class llvm::SymbolTableListTraits<GlobalAlias, Module>; 40 41 //===----------------------------------------------------------------------===// 42 // Primitive Module methods. 43 // 44 45 Module::Module(StringRef MID, LLVMContext& C) 46 : Context(C), Materializer(NULL), ModuleID(MID) { 47 ValSymTab = new ValueSymbolTable(); 48 NamedMDSymTab = new StringMap<NamedMDNode *>(); 49 Context.addModule(this); 50 } 51 52 Module::~Module() { 53 Context.removeModule(this); 54 dropAllReferences(); 55 GlobalList.clear(); 56 FunctionList.clear(); 57 AliasList.clear(); 58 NamedMDList.clear(); 59 delete ValSymTab; 60 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab); 61 } 62 63 /// Target endian information. 64 Module::Endianness Module::getEndianness() const { 65 StringRef temp = DataLayout; 66 Module::Endianness ret = AnyEndianness; 67 68 while (!temp.empty()) { 69 std::pair<StringRef, StringRef> P = getToken(temp, "-"); 70 71 StringRef token = P.first; 72 temp = P.second; 73 74 if (token[0] == 'e') { 75 ret = LittleEndian; 76 } else if (token[0] == 'E') { 77 ret = BigEndian; 78 } 79 } 80 81 return ret; 82 } 83 84 /// Target Pointer Size information. 85 Module::PointerSize Module::getPointerSize() const { 86 StringRef temp = DataLayout; 87 Module::PointerSize ret = AnyPointerSize; 88 89 while (!temp.empty()) { 90 std::pair<StringRef, StringRef> TmpP = getToken(temp, "-"); 91 temp = TmpP.second; 92 TmpP = getToken(TmpP.first, ":"); 93 StringRef token = TmpP.second, signalToken = TmpP.first; 94 95 if (signalToken[0] == 'p') { 96 int size = 0; 97 getToken(token, ":").first.getAsInteger(10, size); 98 if (size == 32) 99 ret = Pointer32; 100 else if (size == 64) 101 ret = Pointer64; 102 } 103 } 104 105 return ret; 106 } 107 108 /// getNamedValue - Return the first global value in the module with 109 /// the specified name, of arbitrary type. This method returns null 110 /// if a global with the specified name is not found. 111 GlobalValue *Module::getNamedValue(StringRef Name) const { 112 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name)); 113 } 114 115 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind. 116 /// This ID is uniqued across modules in the current LLVMContext. 117 unsigned Module::getMDKindID(StringRef Name) const { 118 return Context.getMDKindID(Name); 119 } 120 121 /// getMDKindNames - Populate client supplied SmallVector with the name for 122 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used, 123 /// so it is filled in as an empty string. 124 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const { 125 return Context.getMDKindNames(Result); 126 } 127 128 129 //===----------------------------------------------------------------------===// 130 // Methods for easy access to the functions in the module. 131 // 132 133 // getOrInsertFunction - Look up the specified function in the module symbol 134 // table. If it does not exist, add a prototype for the function and return 135 // it. This is nice because it allows most passes to get away with not handling 136 // the symbol table directly for this common task. 137 // 138 Constant *Module::getOrInsertFunction(StringRef Name, 139 FunctionType *Ty, 140 AttributeSet AttributeList) { 141 // See if we have a definition for the specified function already. 142 GlobalValue *F = getNamedValue(Name); 143 if (F == 0) { 144 // Nope, add it 145 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name); 146 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction 147 New->setAttributes(AttributeList); 148 FunctionList.push_back(New); 149 return New; // Return the new prototype. 150 } 151 152 // Okay, the function exists. Does it have externally visible linkage? 153 if (F->hasLocalLinkage()) { 154 // Clear the function's name. 155 F->setName(""); 156 // Retry, now there won't be a conflict. 157 Constant *NewF = getOrInsertFunction(Name, Ty); 158 F->setName(Name); 159 return NewF; 160 } 161 162 // If the function exists but has the wrong type, return a bitcast to the 163 // right type. 164 if (F->getType() != PointerType::getUnqual(Ty)) 165 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty)); 166 167 // Otherwise, we just found the existing function or a prototype. 168 return F; 169 } 170 171 Constant *Module::getOrInsertFunction(StringRef Name, 172 FunctionType *Ty) { 173 return getOrInsertFunction(Name, Ty, AttributeSet()); 174 } 175 176 // getOrInsertFunction - Look up the specified function in the module symbol 177 // table. If it does not exist, add a prototype for the function and return it. 178 // This version of the method takes a null terminated list of function 179 // arguments, which makes it easier for clients to use. 180 // 181 Constant *Module::getOrInsertFunction(StringRef Name, 182 AttributeSet AttributeList, 183 Type *RetTy, ...) { 184 va_list Args; 185 va_start(Args, RetTy); 186 187 // Build the list of argument types... 188 std::vector<Type*> ArgTys; 189 while (Type *ArgTy = va_arg(Args, Type*)) 190 ArgTys.push_back(ArgTy); 191 192 va_end(Args); 193 194 // Build the function type and chain to the other getOrInsertFunction... 195 return getOrInsertFunction(Name, 196 FunctionType::get(RetTy, ArgTys, false), 197 AttributeList); 198 } 199 200 Constant *Module::getOrInsertFunction(StringRef Name, 201 Type *RetTy, ...) { 202 va_list Args; 203 va_start(Args, RetTy); 204 205 // Build the list of argument types... 206 std::vector<Type*> ArgTys; 207 while (Type *ArgTy = va_arg(Args, Type*)) 208 ArgTys.push_back(ArgTy); 209 210 va_end(Args); 211 212 // Build the function type and chain to the other getOrInsertFunction... 213 return getOrInsertFunction(Name, 214 FunctionType::get(RetTy, ArgTys, false), 215 AttributeSet()); 216 } 217 218 // getFunction - Look up the specified function in the module symbol table. 219 // If it does not exist, return null. 220 // 221 Function *Module::getFunction(StringRef Name) const { 222 return dyn_cast_or_null<Function>(getNamedValue(Name)); 223 } 224 225 //===----------------------------------------------------------------------===// 226 // Methods for easy access to the global variables in the module. 227 // 228 229 /// getGlobalVariable - Look up the specified global variable in the module 230 /// symbol table. If it does not exist, return null. The type argument 231 /// should be the underlying type of the global, i.e., it should not have 232 /// the top-level PointerType, which represents the address of the global. 233 /// If AllowLocal is set to true, this function will return types that 234 /// have an local. By default, these types are not returned. 235 /// 236 GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) { 237 if (GlobalVariable *Result = 238 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name))) 239 if (AllowLocal || !Result->hasLocalLinkage()) 240 return Result; 241 return 0; 242 } 243 244 /// getOrInsertGlobal - Look up the specified global in the module symbol table. 245 /// 1. If it does not exist, add a declaration of the global and return it. 246 /// 2. Else, the global exists but has the wrong type: return the function 247 /// with a constantexpr cast to the right type. 248 /// 3. Finally, if the existing global is the correct delclaration, return the 249 /// existing global. 250 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) { 251 // See if we have a definition for the specified global already. 252 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)); 253 if (GV == 0) { 254 // Nope, add it 255 GlobalVariable *New = 256 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage, 257 0, Name); 258 return New; // Return the new declaration. 259 } 260 261 // If the variable exists but has the wrong type, return a bitcast to the 262 // right type. 263 if (GV->getType() != PointerType::getUnqual(Ty)) 264 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty)); 265 266 // Otherwise, we just found the existing function or a prototype. 267 return GV; 268 } 269 270 //===----------------------------------------------------------------------===// 271 // Methods for easy access to the global variables in the module. 272 // 273 274 // getNamedAlias - Look up the specified global in the module symbol table. 275 // If it does not exist, return null. 276 // 277 GlobalAlias *Module::getNamedAlias(StringRef Name) const { 278 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name)); 279 } 280 281 /// getNamedMetadata - Return the first NamedMDNode in the module with the 282 /// specified name. This method returns null if a NamedMDNode with the 283 /// specified name is not found. 284 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const { 285 SmallString<256> NameData; 286 StringRef NameRef = Name.toStringRef(NameData); 287 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef); 288 } 289 290 /// getOrInsertNamedMetadata - Return the first named MDNode in the module 291 /// with the specified name. This method returns a new NamedMDNode if a 292 /// NamedMDNode with the specified name is not found. 293 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) { 294 NamedMDNode *&NMD = 295 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name]; 296 if (!NMD) { 297 NMD = new NamedMDNode(Name); 298 NMD->setParent(this); 299 NamedMDList.push_back(NMD); 300 } 301 return NMD; 302 } 303 304 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and 305 /// delete it. 306 void Module::eraseNamedMetadata(NamedMDNode *NMD) { 307 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName()); 308 NamedMDList.erase(NMD); 309 } 310 311 /// getModuleFlagsMetadata - Returns the module flags in the provided vector. 312 void Module:: 313 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const { 314 const NamedMDNode *ModFlags = getModuleFlagsMetadata(); 315 if (!ModFlags) return; 316 317 for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) { 318 MDNode *Flag = ModFlags->getOperand(i); 319 ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0)); 320 MDString *Key = cast<MDString>(Flag->getOperand(1)); 321 Value *Val = Flag->getOperand(2); 322 Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()), 323 Key, Val)); 324 } 325 } 326 327 /// Return the corresponding value if Key appears in module flags, otherwise 328 /// return null. 329 Value *Module::getModuleFlag(StringRef Key) const { 330 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 331 getModuleFlagsMetadata(ModuleFlags); 332 for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) { 333 const ModuleFlagEntry &MFE = ModuleFlags[I]; 334 if (Key == MFE.Key->getString()) 335 return MFE.Val; 336 } 337 return 0; 338 } 339 340 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that 341 /// represents module-level flags. This method returns null if there are no 342 /// module-level flags. 343 NamedMDNode *Module::getModuleFlagsMetadata() const { 344 return getNamedMetadata("llvm.module.flags"); 345 } 346 347 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that 348 /// represents module-level flags. If module-level flags aren't found, it 349 /// creates the named metadata that contains them. 350 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() { 351 return getOrInsertNamedMetadata("llvm.module.flags"); 352 } 353 354 /// addModuleFlag - Add a module-level flag to the module-level flags 355 /// metadata. It will create the module-level flags named metadata if it doesn't 356 /// already exist. 357 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 358 Value *Val) { 359 Type *Int32Ty = Type::getInt32Ty(Context); 360 Value *Ops[3] = { 361 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val 362 }; 363 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops)); 364 } 365 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key, 366 uint32_t Val) { 367 Type *Int32Ty = Type::getInt32Ty(Context); 368 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val)); 369 } 370 void Module::addModuleFlag(MDNode *Node) { 371 assert(Node->getNumOperands() == 3 && 372 "Invalid number of operands for module flag!"); 373 assert(isa<ConstantInt>(Node->getOperand(0)) && 374 isa<MDString>(Node->getOperand(1)) && 375 "Invalid operand types for module flag!"); 376 getOrInsertModuleFlagsMetadata()->addOperand(Node); 377 } 378 379 //===----------------------------------------------------------------------===// 380 // Methods to control the materialization of GlobalValues in the Module. 381 // 382 void Module::setMaterializer(GVMaterializer *GVM) { 383 assert(!Materializer && 384 "Module already has a GVMaterializer. Call MaterializeAllPermanently" 385 " to clear it out before setting another one."); 386 Materializer.reset(GVM); 387 } 388 389 bool Module::isMaterializable(const GlobalValue *GV) const { 390 if (Materializer) 391 return Materializer->isMaterializable(GV); 392 return false; 393 } 394 395 bool Module::isDematerializable(const GlobalValue *GV) const { 396 if (Materializer) 397 return Materializer->isDematerializable(GV); 398 return false; 399 } 400 401 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) { 402 if (Materializer) 403 return Materializer->Materialize(GV, ErrInfo); 404 return false; 405 } 406 407 void Module::Dematerialize(GlobalValue *GV) { 408 if (Materializer) 409 return Materializer->Dematerialize(GV); 410 } 411 412 bool Module::MaterializeAll(std::string *ErrInfo) { 413 if (!Materializer) 414 return false; 415 return Materializer->MaterializeModule(this, ErrInfo); 416 } 417 418 bool Module::MaterializeAllPermanently(std::string *ErrInfo) { 419 if (MaterializeAll(ErrInfo)) 420 return true; 421 Materializer.reset(); 422 return false; 423 } 424 425 //===----------------------------------------------------------------------===// 426 // Other module related stuff. 427 // 428 429 430 // dropAllReferences() - This function causes all the subelements to "let go" 431 // of all references that they are maintaining. This allows one to 'delete' a 432 // whole module at a time, even though there may be circular references... first 433 // all references are dropped, and all use counts go to zero. Then everything 434 // is deleted for real. Note that no operations are valid on an object that 435 // has "dropped all references", except operator delete. 436 // 437 void Module::dropAllReferences() { 438 for(Module::iterator I = begin(), E = end(); I != E; ++I) 439 I->dropAllReferences(); 440 441 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I) 442 I->dropAllReferences(); 443 444 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I) 445 I->dropAllReferences(); 446 } 447