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 "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/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GVMaterializer.h"
23 #include "llvm/InstrTypes.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/Support/LeakDetector.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);
60 delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
63 /// Target endian information.
64 Module::Endianness Module::getEndianness() const {
65 StringRef temp = DataLayout;
66 Module::Endianness ret = AnyEndianness;
68 while (!temp.empty()) {
69 std::pair<StringRef, StringRef> P = getToken(temp, "-");
71 StringRef token = P.first;
74 if (token[0] == 'e') {
76 } else if (token[0] == 'E') {
84 /// Target Pointer Size information.
85 Module::PointerSize Module::getPointerSize() const {
86 StringRef temp = DataLayout;
87 Module::PointerSize ret = AnyPointerSize;
89 while (!temp.empty()) {
90 std::pair<StringRef, StringRef> TmpP = getToken(temp, "-");
92 TmpP = getToken(TmpP.first, ":");
93 StringRef token = TmpP.second, signalToken = TmpP.first;
95 if (signalToken[0] == 'p') {
97 getToken(token, ":").first.getAsInteger(10, size);
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));
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);
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);
129 //===----------------------------------------------------------------------===//
130 // Methods for easy access to the functions in the module.
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.
138 Constant *Module::getOrInsertFunction(StringRef Name,
140 AttributeSet AttributeList) {
141 // See if we have a definition for the specified function already.
142 GlobalValue *F = getNamedValue(Name);
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.
152 // Okay, the function exists. Does it have externally visible linkage?
153 if (F->hasLocalLinkage()) {
154 // Clear the function's name.
156 // Retry, now there won't be a conflict.
157 Constant *NewF = getOrInsertFunction(Name, Ty);
162 // If the function exists but has the wrong type, return a bitcast to the
164 if (F->getType() != PointerType::getUnqual(Ty))
165 return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
167 // Otherwise, we just found the existing function or a prototype.
171 Constant *Module::getOrInsertTargetIntrinsic(StringRef Name,
173 AttributeSet AttributeList) {
174 // See if we have a definition for the specified function already.
175 GlobalValue *F = getNamedValue(Name);
178 Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
179 New->setAttributes(AttributeList);
180 FunctionList.push_back(New);
181 return New; // Return the new prototype.
184 // Otherwise, we just found the existing function or a prototype.
188 Constant *Module::getOrInsertFunction(StringRef Name,
190 return getOrInsertFunction(Name, Ty, AttributeSet());
193 // getOrInsertFunction - Look up the specified function in the module symbol
194 // table. If it does not exist, add a prototype for the function and return it.
195 // This version of the method takes a null terminated list of function
196 // arguments, which makes it easier for clients to use.
198 Constant *Module::getOrInsertFunction(StringRef Name,
199 AttributeSet AttributeList,
202 va_start(Args, RetTy);
204 // Build the list of argument types...
205 std::vector<Type*> ArgTys;
206 while (Type *ArgTy = va_arg(Args, Type*))
207 ArgTys.push_back(ArgTy);
211 // Build the function type and chain to the other getOrInsertFunction...
212 return getOrInsertFunction(Name,
213 FunctionType::get(RetTy, ArgTys, false),
217 Constant *Module::getOrInsertFunction(StringRef Name,
220 va_start(Args, RetTy);
222 // Build the list of argument types...
223 std::vector<Type*> ArgTys;
224 while (Type *ArgTy = va_arg(Args, Type*))
225 ArgTys.push_back(ArgTy);
229 // Build the function type and chain to the other getOrInsertFunction...
230 return getOrInsertFunction(Name,
231 FunctionType::get(RetTy, ArgTys, false),
235 // getFunction - Look up the specified function in the module symbol table.
236 // If it does not exist, return null.
238 Function *Module::getFunction(StringRef Name) const {
239 return dyn_cast_or_null<Function>(getNamedValue(Name));
242 //===----------------------------------------------------------------------===//
243 // Methods for easy access to the global variables in the module.
246 /// getGlobalVariable - Look up the specified global variable in the module
247 /// symbol table. If it does not exist, return null. The type argument
248 /// should be the underlying type of the global, i.e., it should not have
249 /// the top-level PointerType, which represents the address of the global.
250 /// If AllowLocal is set to true, this function will return types that
251 /// have an local. By default, these types are not returned.
253 GlobalVariable *Module::getGlobalVariable(StringRef Name,
254 bool AllowLocal) const {
255 if (GlobalVariable *Result =
256 dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
257 if (AllowLocal || !Result->hasLocalLinkage())
262 /// getOrInsertGlobal - Look up the specified global in the module symbol table.
263 /// 1. If it does not exist, add a declaration of the global and return it.
264 /// 2. Else, the global exists but has the wrong type: return the function
265 /// with a constantexpr cast to the right type.
266 /// 3. Finally, if the existing global is the correct delclaration, return the
268 Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
269 // See if we have a definition for the specified global already.
270 GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
273 GlobalVariable *New =
274 new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
276 return New; // Return the new declaration.
279 // If the variable exists but has the wrong type, return a bitcast to the
281 if (GV->getType() != PointerType::getUnqual(Ty))
282 return ConstantExpr::getBitCast(GV, PointerType::getUnqual(Ty));
284 // Otherwise, we just found the existing function or a prototype.
288 //===----------------------------------------------------------------------===//
289 // Methods for easy access to the global variables in the module.
292 // getNamedAlias - Look up the specified global in the module symbol table.
293 // If it does not exist, return null.
295 GlobalAlias *Module::getNamedAlias(StringRef Name) const {
296 return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
299 /// getNamedMetadata - Return the first NamedMDNode in the module with the
300 /// specified name. This method returns null if a NamedMDNode with the
301 /// specified name is not found.
302 NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
303 SmallString<256> NameData;
304 StringRef NameRef = Name.toStringRef(NameData);
305 return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
308 /// getOrInsertNamedMetadata - Return the first named MDNode in the module
309 /// with the specified name. This method returns a new NamedMDNode if a
310 /// NamedMDNode with the specified name is not found.
311 NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
313 (*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
315 NMD = new NamedMDNode(Name);
316 NMD->setParent(this);
317 NamedMDList.push_back(NMD);
322 /// eraseNamedMetadata - Remove the given NamedMDNode from this module and
324 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
325 static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
326 NamedMDList.erase(NMD);
329 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
331 getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
332 const NamedMDNode *ModFlags = getModuleFlagsMetadata();
333 if (!ModFlags) return;
335 for (unsigned i = 0, e = ModFlags->getNumOperands(); i != e; ++i) {
336 MDNode *Flag = ModFlags->getOperand(i);
337 ConstantInt *Behavior = cast<ConstantInt>(Flag->getOperand(0));
338 MDString *Key = cast<MDString>(Flag->getOperand(1));
339 Value *Val = Flag->getOperand(2);
340 Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue()),
345 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
346 /// represents module-level flags. This method returns null if there are no
347 /// module-level flags.
348 NamedMDNode *Module::getModuleFlagsMetadata() const {
349 return getNamedMetadata("llvm.module.flags");
352 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
353 /// represents module-level flags. If module-level flags aren't found, it
354 /// creates the named metadata that contains them.
355 NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
356 return getOrInsertNamedMetadata("llvm.module.flags");
359 /// addModuleFlag - Add a module-level flag to the module-level flags
360 /// metadata. It will create the module-level flags named metadata if it doesn't
362 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
364 Type *Int32Ty = Type::getInt32Ty(Context);
366 ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
368 getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
370 void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
372 Type *Int32Ty = Type::getInt32Ty(Context);
373 addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
375 void Module::addModuleFlag(MDNode *Node) {
376 assert(Node->getNumOperands() == 3 &&
377 "Invalid number of operands for module flag!");
378 assert(isa<ConstantInt>(Node->getOperand(0)) &&
379 isa<MDString>(Node->getOperand(1)) &&
380 "Invalid operand types for module flag!");
381 getOrInsertModuleFlagsMetadata()->addOperand(Node);
384 //===----------------------------------------------------------------------===//
385 // Methods to control the materialization of GlobalValues in the Module.
387 void Module::setMaterializer(GVMaterializer *GVM) {
388 assert(!Materializer &&
389 "Module already has a GVMaterializer. Call MaterializeAllPermanently"
390 " to clear it out before setting another one.");
391 Materializer.reset(GVM);
394 bool Module::isMaterializable(const GlobalValue *GV) const {
396 return Materializer->isMaterializable(GV);
400 bool Module::isDematerializable(const GlobalValue *GV) const {
402 return Materializer->isDematerializable(GV);
406 bool Module::Materialize(GlobalValue *GV, std::string *ErrInfo) {
408 return Materializer->Materialize(GV, ErrInfo);
412 void Module::Dematerialize(GlobalValue *GV) {
414 return Materializer->Dematerialize(GV);
417 bool Module::MaterializeAll(std::string *ErrInfo) {
420 return Materializer->MaterializeModule(this, ErrInfo);
423 bool Module::MaterializeAllPermanently(std::string *ErrInfo) {
424 if (MaterializeAll(ErrInfo))
426 Materializer.reset();
430 //===----------------------------------------------------------------------===//
431 // Other module related stuff.
435 // dropAllReferences() - This function causes all the subelements to "let go"
436 // of all references that they are maintaining. This allows one to 'delete' a
437 // whole module at a time, even though there may be circular references... first
438 // all references are dropped, and all use counts go to zero. Then everything
439 // is deleted for real. Note that no operations are valid on an object that
440 // has "dropped all references", except operator delete.
442 void Module::dropAllReferences() {
443 for(Module::iterator I = begin(), E = end(); I != E; ++I)
444 I->dropAllReferences();
446 for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
447 I->dropAllReferences();
449 for(Module::alias_iterator I = alias_begin(), E = alias_end(); I != E; ++I)
450 I->dropAllReferences();