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 // 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>;
41 //===----------------------------------------------------------------------===//
42 // Primitive Module methods.
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);
53 Context.removeModule(this);
61 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
64 /// Target endian information.
65 Module::Endianness Module::getEndianness() const {
66 StringRef temp = DataLayout;
67 Module::Endianness ret = AnyEndianness;
69 while (!temp.empty()) {
70 std::pair<StringRef, StringRef> P = getToken(temp, "-");
72 StringRef token = P.first;
75 if (token[0] == 'e') {
77 } else if (token[0] == 'E') {
85 /// Target Pointer Size information.
86 Module::PointerSize Module::getPointerSize() const {
87 StringRef temp = DataLayout;
88 Module::PointerSize ret = AnyPointerSize;
90 while (!temp.empty()) {
91 std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
93 TmpP = getToken(TmpP.first, ":");
94 StringRef token = TmpP.second, signalToken = TmpP.first;
96 if (signalToken[0] == 'p') {
98 getToken(token, ":").first.getAsInteger(10, size);
109 /// getNamedValue - Return the first global value in the module with
110 /// the specified name, of arbitrary type. This method returns null
111 /// if a global with the specified name is not found.
112 GlobalValue *Module::getNamedValue(StringRef Name) const {
113 return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
116 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
117 /// This ID is uniqued across modules in the current LLVMContext.
118 unsigned Module::getMDKindID(StringRef Name) const {
119 return Context.getMDKindID(Name);
122 /// getMDKindNames - Populate client supplied SmallVector with the name for
123 /// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
124 /// so it is filled in as an empty string.
125 void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
126 return Context.getMDKindNames(Result);
130 //===----------------------------------------------------------------------===//
131 // Methods for easy access to the functions in the module.
134 // getOrInsertFunction - Look up the specified function in the module symbol
135 // table. If it does not exist, add a prototype for the function and return
136 // it. This is nice because it allows most passes to get away with not handling
137 // the symbol table directly for this common task.
139 Constant *Module::getOrInsertFunction(StringRef Name,
141 AttrListPtr AttributeList) {
142 // See if we have a definition for the specified function already.
143 GlobalValue *F = getNamedValue(Name);
146 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
147 if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
148 New->setAttributes(AttributeList);
149 FunctionList.push_back(New);
150 return New; // Return the new prototype.
153 // Okay, the function exists. Does it have externally visible linkage?
154 if (F->hasLocalLinkage()) {
155 // Clear the function's name.
157 // Retry, now there won't be a conflict.
158 Constant *NewF = getOrInsertFunction(Name, Ty);
163 // If the function exists but has the wrong type, return a bitcast to the
165 if (F->getType() != PointerType::getUnqual(Ty))
166 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
168 // Otherwise, we just found the existing function or a prototype.
172 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
174 AttrListPtr AttributeList) {
175 // See if we have a definition for the specified function already.
176 GlobalValue *F = getNamedValue(Name);
179 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
180 New->setAttributes(AttributeList);
181 FunctionList.push_back(New);
182 return New; // Return the new prototype.
185 // Otherwise, we just found the existing function or a prototype.
189 Constant *Module::getOrInsertFunction(StringRef Name,
191 AttrListPtr AttributeList = AttrListPtr::get((AttributeWithIndex *)0, 0);
192 return getOrInsertFunction(Name, Ty, AttributeList);
195 // getOrInsertFunction - Look up the specified function in the module symbol
196 // table. If it does not exist, add a prototype for the function and return it.
197 // This version of the method takes a null terminated list of function
198 // arguments, which makes it easier for clients to use.
200 Constant *Module::getOrInsertFunction(StringRef Name,
201 AttrListPtr AttributeList,
204 va_start(Args, RetTy);
206 // Build the list of argument types...
207 std::vector<Type*> ArgTys;
208 while (Type *ArgTy = va_arg(Args, Type*))
209 ArgTys.push_back(ArgTy);
213 // Build the function type and chain to the other getOrInsertFunction...
214 return getOrInsertFunction(Name,
215 FunctionType::get(RetTy, ArgTys, false),
219 Constant *Module::getOrInsertFunction(StringRef Name,
222 va_start(Args, RetTy);
224 // Build the list of argument types...
225 std::vector<Type*> ArgTys;
226 while (Type *ArgTy = va_arg(Args, Type*))
227 ArgTys.push_back(ArgTy);
231 // Build the function type and chain to the other getOrInsertFunction...
232 return getOrInsertFunction(Name,
233 FunctionType::get(RetTy, ArgTys, false),
234 AttrListPtr::get((AttributeWithIndex *)0, 0));
237 // getFunction - Look up the specified function in the module symbol table.
238 // If it does not exist, return null.
240 Function *Module::getFunction(StringRef Name) const {
241 return dyn_cast_or_null<Function>(getNamedValue(Name));
244 //===----------------------------------------------------------------------===//
245 // Methods for easy access to the global variables in the module.
248 /// getGlobalVariable - Look up the specified global variable in the module
249 /// symbol table. If it does not exist, return null. The type argument
250 /// should be the underlying type of the global, i.e., it should not have
251 /// the top-level PointerType, which represents the address of the global.
252 /// If AllowLocal is set to true, this function will return types that
253 /// have an local. By default, these types are not returned.
255 GlobalVariable *Module::getGlobalVariable(StringRef Name,
256 bool AllowLocal) const {
257 if (GlobalVariable *Result =
258 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
259 if (AllowLocal || !Result->hasLocalLinkage())
264 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
265 /// 1. If it does not exist, add a declaration of the global and return it.
266 /// 2. Else, the global exists but has the wrong type: return the function
267 /// with a constantexpr cast to the right type.
268 /// 3. Finally, if the existing global is the correct delclaration, return the
270 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
271 // See if we have a definition for the specified global already.
272 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
275 GlobalVariable *New =
276 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
278 return New; // Return the new declaration.
281 // If the variable exists but has the wrong type, return a bitcast to the
283 if (GV->getType() != PointerType::getUnqual(Ty))
284 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
286 // Otherwise, we just found the existing function or a prototype.
290 //===----------------------------------------------------------------------===//
291 // Methods for easy access to the global variables in the module.
294 // getNamedAlias - Look up the specified global in the module symbol table.
295 // If it does not exist, return null.
297 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
298 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
301 /// getNamedMetadata - Return the first NamedMDNode in the module with the
302 /// specified name. This method returns null if a NamedMDNode with the
303 /// specified name is not found.
304 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
305 SmallString<256> NameData;
306 StringRef NameRef = Name.toStringRef(NameData);
307 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
310 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
311 /// with the specified name. This method returns a new NamedMDNode if a
312 /// NamedMDNode with the specified name is not found.
313 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
315 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
317 NMD = new NamedMDNode(Name);
318 NMD->setParent(this);
319 NamedMDList.push_back(NMD);
324 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
325 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
326 NamedMDList.erase(NMD);
330 //===----------------------------------------------------------------------===//
331 // Methods to control the materialization of GlobalValues in the Module.
333 void Module::setMaterializer(GVMaterializer *GVM) {
334 assert(!Materializer &&
335 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
336 " to clear it out before setting another one.");
337 Materializer.reset(GVM);
340 bool Module::isMaterializable(const GlobalValue *GV) const {
342 return Materializer->isMaterializable(GV);
346 bool Module::isDematerializable(const GlobalValue *GV) const {
348 return Materializer->isDematerializable(GV);
352 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
354 return Materializer->Materialize(GV, ErrInfo);
358 void Module::Dematerialize(GlobalValue *GV) {
360 return Materializer->Dematerialize(GV);
363 bool Module::MaterializeAll(std::string *ErrInfo) {
366 return Materializer->MaterializeModule(this, ErrInfo);
369 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
370 if (MaterializeAll(ErrInfo))
372 Materializer.reset();
376 //===----------------------------------------------------------------------===//
377 // Other module related stuff.
381 // dropAllReferences() - This function causes all the subelementss to "let go"
382 // of all references that they are maintaining. This allows one to 'delete' a
383 // whole module at a time, even though there may be circular references... first
384 // all references are dropped, and all use counts go to zero. Then everything
385 // is deleted for real. Note that no operations are valid on an object that
386 // has "dropped all references", except operator delete.
388 void Module::dropAllReferences() {
389 for(Module::iterator I = begin(), E = end(); I != E; ++I)
390 I->dropAllReferences();
392 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
393 I->dropAllReferences();
395 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
396 I->dropAllReferences();
399 void Module::addLibrary(StringRef Lib) {
400 for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I)
403 LibraryList.push_back(Lib);
406 void Module::removeLibrary(StringRef Lib) {
407 LibraryListType::iterator I = LibraryList.begin();
408 LibraryListType::iterator E = LibraryList.end();
411 LibraryList.erase(I);
416 //===----------------------------------------------------------------------===//
417 // Type finding functionality.
418 //===----------------------------------------------------------------------===//
421 /// TypeFinder - Walk over a module, identifying all of the types that are
422 /// used by the module.
424 // To avoid walking constant expressions multiple times and other IR
425 // objects, we keep several helper maps.
426 DenseSet<const Value*> VisitedConstants;
427 DenseSet<Type*> VisitedTypes;
429 std::vector<StructType*> &StructTypes;
431 TypeFinder(std::vector<StructType*> &structTypes)
432 : StructTypes(structTypes) {}
434 void run(const Module &M) {
435 // Get types from global variables.
436 for (Module::const_global_iterator I = M.global_begin(),
437 E = M.global_end(); I != E; ++I) {
438 incorporateType(I->getType());
439 if (I->hasInitializer())
440 incorporateValue(I->getInitializer());
443 // Get types from aliases.
444 for (Module::const_alias_iterator I = M.alias_begin(),
445 E = M.alias_end(); I != E; ++I) {
446 incorporateType(I->getType());
447 if (const Value *Aliasee = I->getAliasee())
448 incorporateValue(Aliasee);
451 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
453 // Get types from functions.
454 for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
455 incorporateType(FI->getType());
457 for (Function::const_iterator BB = FI->begin(), E = FI->end();
459 for (BasicBlock::const_iterator II = BB->begin(),
460 E = BB->end(); II != E; ++II) {
461 const Instruction &I = *II;
462 // Incorporate the type of the instruction and all its operands.
463 incorporateType(I.getType());
464 for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
466 incorporateValue(*OI);
468 // Incorporate types hiding in metadata.
469 I.getAllMetadataOtherThanDebugLoc(MDForInst);
470 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
471 incorporateMDNode(MDForInst[i].second);
476 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
477 E = M.named_metadata_end(); I != E; ++I) {
478 const NamedMDNode *NMD = I;
479 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
480 incorporateMDNode(NMD->getOperand(i));
485 void incorporateType(Type *Ty) {
486 // Check to see if we're already visited this type.
487 if (!VisitedTypes.insert(Ty).second)
490 // If this is a structure or opaque type, add a name for the type.
491 if (StructType *STy = dyn_cast<StructType>(Ty))
492 StructTypes.push_back(STy);
494 // Recursively walk all contained types.
495 for (Type::subtype_iterator I = Ty->subtype_begin(),
496 E = Ty->subtype_end(); I != E; ++I)
500 /// incorporateValue - This method is used to walk operand lists finding
501 /// types hiding in constant expressions and other operands that won't be
502 /// walked in other ways. GlobalValues, basic blocks, instructions, and
503 /// inst operands are all explicitly enumerated.
504 void incorporateValue(const Value *V) {
505 if (const MDNode *M = dyn_cast<MDNode>(V))
506 return incorporateMDNode(M);
507 if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
510 if (!VisitedConstants.insert(V).second)
514 incorporateType(V->getType());
516 // Look in operands for types.
517 const User *U = cast<User>(V);
518 for (Constant::const_op_iterator I = U->op_begin(),
519 E = U->op_end(); I != E;++I)
520 incorporateValue(*I);
523 void incorporateMDNode(const MDNode *V) {
526 if (!VisitedConstants.insert(V).second)
529 // Look in operands for types.
530 for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i)
531 if (Value *Op = V->getOperand(i))
532 incorporateValue(Op);
535 } // end anonymous namespace
537 void Module::findUsedStructTypes(std::vector<StructType*> &StructTypes) const {
538 TypeFinder(StructTypes).run(*this);