1 //===-- Module.cpp - Implement the Module class ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Module class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Module.h"
15 #include "llvm/InstrTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GVMaterializer.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Support/LeakDetector.h"
25 #include "SymbolTableListTraitsImpl.h"
31 //===----------------------------------------------------------------------===//
32 // Methods to implement the globals and functions lists.
35 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
36 GlobalVariable *Ret = new GlobalVariable(Type::getInt32Ty(getGlobalContext()),
37 false, GlobalValue::ExternalLinkage);
38 // This should not be garbage monitored.
39 LeakDetector::removeGarbageObject(Ret);
42 GlobalAlias *ilist_traits<GlobalAlias>::createSentinel() {
43 GlobalAlias *Ret = new GlobalAlias(Type::getInt32Ty(getGlobalContext()),
44 GlobalValue::ExternalLinkage);
45 // This should not be garbage monitored.
46 LeakDetector::removeGarbageObject(Ret);
50 // Explicit instantiations of SymbolTableListTraits since some of the methods
51 // are not in the public header file.
52 template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
53 template class llvm::SymbolTableListTraits<Function, Module>;
54 template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
56 //===----------------------------------------------------------------------===//
57 // Primitive Module methods.
60 Module::Module(StringRef MID, LLVMContext& C)
61 : Context(C), Materializer(NULL), ModuleID(MID) {
62 ValSymTab = new ValueSymbolTable();
63 NamedMDSymTab = new StringMap<NamedMDNode *>();
64 Context.addModule(this);
68 Context.removeModule(this);
76 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
79 /// Target endian information.
80 Module::Endianness Module::getEndianness() const {
81 StringRef temp = DataLayout;
82 Module::Endianness ret = AnyEndianness;
84 while (!temp.empty()) {
85 std::pair<StringRef, StringRef> P = getToken(temp, "-");
87 StringRef token = P.first;
90 if (token[0] == 'e') {
92 } else if (token[0] == 'E') {
100 /// Target Pointer Size information.
101 Module::PointerSize Module::getPointerSize() const {
102 StringRef temp = DataLayout;
103 Module::PointerSize ret = AnyPointerSize;
105 while (!temp.empty()) {
106 std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
108 TmpP = getToken(TmpP.first, ":");
109 StringRef token = TmpP.second, signalToken = TmpP.first;
111 if (signalToken[0] == 'p') {
113 getToken(token, ":").first.getAsInteger(10, size);
124 /// getNamedValue - Return the first global value in the module with
125 /// the specified name, of arbitrary type. This method returns null
126 /// if a global with the specified name is not found.
127 GlobalValue *Module::getNamedValue(StringRef Name) const {
128 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
131 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
132 /// This ID is uniqued across modules in the current LLVMContext.
133 unsigned Module::getMDKindID(StringRef Name) const {
134 return Context.getMDKindID(Name);
137 /// getMDKindNames - Populate client supplied SmallVector with the name for
138 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
139 /// so it is filled in as an empty string.
140 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
141 return Context.getMDKindNames(Result);
145 //===----------------------------------------------------------------------===//
146 // Methods for easy access to the functions in the module.
149 // getOrInsertFunction - Look up the specified function in the module symbol
150 // table. If it does not exist, add a prototype for the function and return
151 // it. This is nice because it allows most passes to get away with not handling
152 // the symbol table directly for this common task.
154 Constant *Module::getOrInsertFunction(StringRef Name,
156 AttrListPtr AttributeList) {
157 // See if we have a definition for the specified function already.
158 GlobalValue *F = getNamedValue(Name);
161 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
162 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
163 New->setAttributes(AttributeList);
164 FunctionList.push_back(New);
165 return New; // Return the new prototype.
168 // Okay, the function exists. Does it have externally visible linkage?
169 if (F->hasLocalLinkage()) {
170 // Clear the function's name.
172 // Retry, now there won't be a conflict.
173 Constant *NewF = getOrInsertFunction(Name, Ty);
178 // If the function exists but has the wrong type, return a bitcast to the
180 if (F->getType() != PointerType::getUnqual(Ty))
181 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
183 // Otherwise, we just found the existing function or a prototype.
187 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
189 AttrListPtr AttributeList) {
190 // See if we have a definition for the specified function already.
191 GlobalValue *F = getNamedValue(Name);
194 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
195 New->setAttributes(AttributeList);
196 FunctionList.push_back(New);
197 return New; // Return the new prototype.
200 // Otherwise, we just found the existing function or a prototype.
204 Constant *Module::getOrInsertFunction(StringRef Name,
206 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
207 return getOrInsertFunction(Name, Ty, AttributeList);
210 // getOrInsertFunction - Look up the specified function in the module symbol
211 // table. If it does not exist, add a prototype for the function and return it.
212 // This version of the method takes a null terminated list of function
213 // arguments, which makes it easier for clients to use.
215 Constant *Module::getOrInsertFunction(StringRef Name,
216 AttrListPtr AttributeList,
219 va_start(Args, RetTy);
221 // Build the list of argument types...
222 std::vector<Type*> ArgTys;
223 while (Type *ArgTy = va_arg(Args, Type*))
224 ArgTys.push_back(ArgTy);
228 // Build the function type and chain to the other getOrInsertFunction...
229 return getOrInsertFunction(Name,
230 FunctionType::get(RetTy, ArgTys, false),
234 Constant *Module::getOrInsertFunction(StringRef Name,
237 va_start(Args, RetTy);
239 // Build the list of argument types...
240 std::vector<Type*> ArgTys;
241 while (Type *ArgTy = va_arg(Args, Type*))
242 ArgTys.push_back(ArgTy);
246 // Build the function type and chain to the other getOrInsertFunction...
247 return getOrInsertFunction(Name,
248 FunctionType::get(RetTy, ArgTys, false),
249 AttrListPtr::get((AttributeWithIndex *)0, 0));
252 // getFunction - Look up the specified function in the module symbol table.
253 // If it does not exist, return null.
255 Function *Module::getFunction(StringRef Name) const {
256 return dyn_cast_or_null<Function>(getNamedValue(Name));
259 //===----------------------------------------------------------------------===//
260 // Methods for easy access to the global variables in the module.
263 /// getGlobalVariable - Look up the specified global variable in the module
264 /// symbol table. If it does not exist, return null. The type argument
265 /// should be the underlying type of the global, i.e., it should not have
266 /// the top-level PointerType, which represents the address of the global.
267 /// If AllowLocal is set to true, this function will return types that
268 /// have an local. By default, these types are not returned.
270 GlobalVariable *Module::getGlobalVariable(StringRef Name,
271 bool AllowLocal) const {
272 if (GlobalVariable *Result =
273 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
274 if (AllowLocal || !Result->hasLocalLinkage())
279 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
280 /// 1. If it does not exist, add a declaration of the global and return it.
281 /// 2. Else, the global exists but has the wrong type: return the function
282 /// with a constantexpr cast to the right type.
283 /// 3. Finally, if the existing global is the correct delclaration, return the
285 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
286 // See if we have a definition for the specified global already.
287 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
290 GlobalVariable *New =
291 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
293 return New; // Return the new declaration.
296 // If the variable exists but has the wrong type, return a bitcast to the
298 if (GV->getType() != PointerType::getUnqual(Ty))
299 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
301 // Otherwise, we just found the existing function or a prototype.
305 //===----------------------------------------------------------------------===//
306 // Methods for easy access to the global variables in the module.
309 // getNamedAlias - Look up the specified global in the module symbol table.
310 // If it does not exist, return null.
312 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
313 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
316 /// getNamedMetadata - Return the first NamedMDNode in the module with the
317 /// specified name. This method returns null if a NamedMDNode with the
318 /// specified name is not found.
319 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
320 SmallString<256> NameData;
321 StringRef NameRef = Name.toStringRef(NameData);
322 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
325 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
326 /// with the specified name. This method returns a new NamedMDNode if a
327 /// NamedMDNode with the specified name is not found.
328 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
330 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
332 NMD = new NamedMDNode(Name);
333 NMD->setParent(this);
334 NamedMDList.push_back(NMD);
339 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
340 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
341 NamedMDList.erase(NMD);
345 //===----------------------------------------------------------------------===//
346 // Methods to control the materialization of GlobalValues in the Module.
348 void Module::setMaterializer(GVMaterializer *GVM) {
349 assert(!Materializer &&
350 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
351 " to clear it out before setting another one.");
352 Materializer.reset(GVM);
355 bool Module::isMaterializable(const GlobalValue *GV) const {
357 return Materializer->isMaterializable(GV);
361 bool Module::isDematerializable(const GlobalValue *GV) const {
363 return Materializer->isDematerializable(GV);
367 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
369 return Materializer->Materialize(GV, ErrInfo);
373 void Module::Dematerialize(GlobalValue *GV) {
375 return Materializer->Dematerialize(GV);
378 bool Module::MaterializeAll(std::string *ErrInfo) {
381 return Materializer->MaterializeModule(this, ErrInfo);
384 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
385 if (MaterializeAll(ErrInfo))
387 Materializer.reset();
391 //===----------------------------------------------------------------------===//
392 // Other module related stuff.
396 // dropAllReferences() - This function causes all the subelementss to "let go"
397 // of all references that they are maintaining. This allows one to 'delete' a
398 // whole module at a time, even though there may be circular references... first
399 // all references are dropped, and all use counts go to zero. Then everything
400 // is deleted for real. Note that no operations are valid on an object that
401 // has "dropped all references", except operator delete.
403 void Module::dropAllReferences() {
404 for(Module::iterator I = begin(), E = end(); I != E; ++I)
405 I->dropAllReferences();
407 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
408 I->dropAllReferences();
410 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
411 I->dropAllReferences();
414 void Module::addLibrary(StringRef Lib) {
415 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
418 LibraryList.push_back(Lib);
421 void Module::removeLibrary(StringRef Lib) {
422 LibraryListType::iterator I = LibraryList.begin();
423 LibraryListType::iterator E = LibraryList.end();
426 LibraryList.erase(I);
431 //===----------------------------------------------------------------------===//
432 // Type finding functionality.
433 //===----------------------------------------------------------------------===//
436 /// TypeFinder - Walk over a module, identifying all of the types that are
437 /// used by the module.
439 // To avoid walking constant expressions multiple times and other IR
440 // objects, we keep several helper maps.
441 DenseSet<const Value*> VisitedConstants;
442 DenseSet<Type*> VisitedTypes;
444 std::vector<StructType*> &StructTypes;
446 TypeFinder(std::vector<StructType*> &structTypes)
447 : StructTypes(structTypes) {}
449 void run(const Module &M) {
450 // Get types from global variables.
451 for (Module::const_global_iterator I = M.global_begin(),
452 E = M.global_end(); I != E; ++I) {
453 incorporateType(I->getType());
454 if (I->hasInitializer())
455 incorporateValue(I->getInitializer());
458 // Get types from aliases.
459 for (Module::const_alias_iterator I = M.alias_begin(),
460 E = M.alias_end(); I != E; ++I) {
461 incorporateType(I->getType());
462 if (const Value *Aliasee = I->getAliasee())
463 incorporateValue(Aliasee);
466 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
468 // Get types from functions.
469 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
470 incorporateType(FI->getType());
472 for (Function::const_iterator BB = FI->begin(), E = FI->end();
474 for (BasicBlock::const_iterator II = BB->begin(),
475 E = BB->end(); II != E; ++II) {
476 const Instruction &I = *II;
477 // Incorporate the type of the instruction and all its operands.
478 incorporateType(I.getType());
479 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
481 incorporateValue(*OI);
483 // Incorporate types hiding in metadata.
484 I.getAllMetadataOtherThanDebugLoc(MDForInst);
485 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
486 incorporateMDNode(MDForInst[i].second);
491 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
492 E = M.named_metadata_end(); I != E; ++I) {
493 const NamedMDNode *NMD = I;
494 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
495 incorporateMDNode(NMD->getOperand(i));
500 void incorporateType(Type *Ty) {
501 // Check to see if we're already visited this type.
502 if (!VisitedTypes.insert(Ty).second)
505 // If this is a structure or opaque type, add a name for the type.
506 if (StructType *STy = dyn_cast<StructType>(Ty))
507 StructTypes.push_back(STy);
509 // Recursively walk all contained types.
510 for (Type::subtype_iterator I = Ty->subtype_begin(),
511 E = Ty->subtype_end(); I != E; ++I)
515 /// incorporateValue - This method is used to walk operand lists finding
516 /// types hiding in constant expressions and other operands that won't be
517 /// walked in other ways. GlobalValues, basic blocks, instructions, and
518 /// inst operands are all explicitly enumerated.
519 void incorporateValue(const Value *V) {
520 if (const MDNode *M = dyn_cast<MDNode>(V))
521 return incorporateMDNode(M);
522 if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
525 if (!VisitedConstants.insert(V).second)
529 incorporateType(V->getType());
531 // Look in operands for types.
532 const User *U = cast<User>(V);
533 for (Constant::const_op_iterator I = U->op_begin(),
534 E = U->op_end(); I != E;++I)
535 incorporateValue(*I);
538 void incorporateMDNode(const MDNode *V) {
541 if (!VisitedConstants.insert(V).second)
544 // Look in operands for types.
545 for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i)
546 if (Value *Op = V->getOperand(i))
547 incorporateValue(Op);
550 } // end anonymous namespace
552 void Module::findUsedStructTypes(std::vector<StructType*> &StructTypes) const {
553 TypeFinder(StructTypes).run(*this);