1 //===-- Module.cpp - Implement the Module class ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "Support/STLExtras.h"
19 #include "Support/LeakDetector.h"
20 #include "SymbolTableListTraitsImpl.h"
26 //===----------------------------------------------------------------------===//
27 // Stuff to implement the globals and functions lists.
30 Function *ilist_traits<Function>::createNode() {
32 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
33 Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
34 // This should not be garbage monitored.
35 LeakDetector::removeGarbageObject(Ret);
38 GlobalVariable *ilist_traits<GlobalVariable>::createNode() {
39 GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
40 GlobalValue::ExternalLinkage);
41 // This should not be garbage monitored.
42 LeakDetector::removeGarbageObject(Ret);
46 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
47 return M->getFunctionList();
49 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
50 return M->getGlobalList();
53 // Explicit instantiations of SymbolTableListTraits since some of the methods
54 // are not in the public header file...
55 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
56 template class SymbolTableListTraits<Function, Module, Module>;
58 // Define the GlobalValueRefMap as a struct that wraps a map so that we don't
59 // have Module.h depend on <map>
62 struct GlobalValueRefMap {
63 typedef std::map<GlobalValue*, ConstantPointerRef*> MapTy;
64 typedef MapTy::iterator iterator;
65 std::map<GlobalValue*, ConstantPointerRef*> Map;
69 //===----------------------------------------------------------------------===//
70 // Primitive Module methods.
73 Module::Module(const std::string &MID)
74 : ModuleID(MID), Endian(AnyEndianness), PtrSize(AnyPointerSize) {
75 FunctionList.setItemParent(this);
76 FunctionList.setParent(this);
77 GlobalList.setItemParent(this);
78 GlobalList.setParent(this);
80 SymTab = new SymbolTable();
86 GlobalList.setParent(0);
88 FunctionList.setParent(0);
92 // Module::dump() - Allow printing from debugger
93 void Module::dump() const {
97 //===----------------------------------------------------------------------===//
98 // Methods for easy access to the functions in the module.
101 // getOrInsertFunction - Look up the specified function in the module symbol
102 // table. If it does not exist, add a prototype for the function and return
103 // it. This is nice because it allows most passes to get away with not handling
104 // the symbol table directly for this common task.
106 Function *Module::getOrInsertFunction(const std::string &Name,
107 const FunctionType *Ty) {
108 SymbolTable &SymTab = getSymbolTable();
110 // See if we have a definitions for the specified function already...
111 if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
112 return cast<Function>(V); // Yup, got it
113 } else { // Nope, add one
114 Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
115 FunctionList.push_back(New);
116 return New; // Return the new prototype...
120 // getOrInsertFunction - Look up the specified function in the module symbol
121 // table. If it does not exist, add a prototype for the function and return it.
122 // This version of the method takes a null terminated list of function
123 // arguments, which makes it easier for clients to use.
125 Function *Module::getOrInsertFunction(const std::string &Name,
126 const Type *RetTy, ...) {
128 va_start(Args, RetTy);
130 // Build the list of argument types...
131 std::vector<const Type*> ArgTys;
132 while (const Type *ArgTy = va_arg(Args, const Type*))
133 ArgTys.push_back(ArgTy);
137 // Build the function type and chain to the other getOrInsertFunction...
138 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
142 // getFunction - Look up the specified function in the module symbol table.
143 // If it does not exist, return null.
145 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
146 SymbolTable &SymTab = getSymbolTable();
147 return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
151 /// getMainFunction - This function looks up main efficiently. This is such a
152 /// common case, that it is a method in Module. If main cannot be found, a
153 /// null pointer is returned.
155 Function *Module::getMainFunction() {
156 std::vector<const Type*> Params;
159 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
163 // void main(void)...
164 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
168 Params.push_back(Type::IntTy);
170 // int main(int argc)...
171 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
175 // void main(int argc)...
176 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
180 for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
181 Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
183 // int main(int argc, char **argv)...
184 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
188 // void main(int argc, char **argv)...
189 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
194 // Ok, try to find main the hard way...
195 return getNamedFunction("main");
198 /// getNamedFunction - Return the first function in the module with the
199 /// specified name, of arbitrary type. This method returns null if a function
200 /// with the specified name is not found.
202 Function *Module::getNamedFunction(const std::string &Name) {
203 // Loop over all of the functions, looking for the function desired
205 for (iterator I = begin(), E = end(); I != E; ++I)
206 if (I->getName() == Name)
211 return Found; // Non-external function not found...
214 //===----------------------------------------------------------------------===//
215 // Methods for easy access to the global variables in the module.
218 /// getGlobalVariable - Look up the specified global variable in the module
219 /// symbol table. If it does not exist, return null. Note that this only
220 /// returns a global variable if it does not have internal linkage. The type
221 /// argument should be the underlying type of the global, ie, it should not
222 /// have the top-level PointerType, which represents the address of the
225 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
227 if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
228 GlobalVariable *Result = cast<GlobalVariable>(V);
229 if (!Result->hasInternalLinkage())
237 //===----------------------------------------------------------------------===//
238 // Methods for easy access to the types in the module.
242 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
243 // there is already an entry for this name, true is returned and the symbol
244 // table is not modified.
246 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
247 SymbolTable &ST = getSymbolTable();
249 if (ST.lookup(Type::TypeTy, Name)) return true; // Already in symtab...
251 // Not in symbol table? Set the name with the Symtab as an argument so the
252 // type knows what to update...
253 ((Value*)Ty)->setName(Name, &ST);
258 /// getTypeByName - Return the type with the specified name in this module, or
259 /// null if there is none by that name.
260 const Type *Module::getTypeByName(const std::string &Name) const {
261 const SymbolTable &ST = getSymbolTable();
262 return cast_or_null<Type>(ST.lookup(Type::TypeTy, Name));
265 // getTypeName - If there is at least one entry in the symbol table for the
266 // specified type, return it.
268 std::string Module::getTypeName(const Type *Ty) const {
269 const SymbolTable &ST = getSymbolTable();
270 if (ST.find(Type::TypeTy) == ST.end())
271 return ""; // No names for types...
273 SymbolTable::type_const_iterator TI = ST.type_begin(Type::TypeTy);
274 SymbolTable::type_const_iterator TE = ST.type_end(Type::TypeTy);
276 while (TI != TE && TI->second != (const Value*)Ty)
279 if (TI != TE) // Must have found an entry!
281 return ""; // Must not have found anything...
285 //===----------------------------------------------------------------------===//
286 // Other module related stuff.
290 // dropAllReferences() - This function causes all the subelementss to "let go"
291 // of all references that they are maintaining. This allows one to 'delete' a
292 // whole module at a time, even though there may be circular references... first
293 // all references are dropped, and all use counts go to zero. Then everything
294 // is deleted for real. Note that no operations are valid on an object that
295 // has "dropped all references", except operator delete.
297 void Module::dropAllReferences() {
298 for(Module::iterator I = begin(), E = end(); I != E; ++I)
299 I->dropAllReferences();
301 for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
302 I->dropAllReferences();
304 // If there are any GlobalVariable references still out there, nuke them now.
305 // Since all references are hereby dropped, nothing could possibly reference
306 // them still. Note that destroying all of the constant pointer refs will
307 // eventually cause the GVRefMap field to be set to null (by
308 // destroyConstantPointerRef, below).
311 // Delete the ConstantPointerRef node...
312 GVRefMap->Map.begin()->second->destroyConstant();
315 // Accessor for the underlying GlobalValRefMap...
316 ConstantPointerRef *Module::getConstantPointerRef(GlobalValue *V){
317 // Create ref map lazily on demand...
318 if (GVRefMap == 0) GVRefMap = new GlobalValueRefMap();
320 GlobalValueRefMap::iterator I = GVRefMap->Map.find(V);
321 if (I != GVRefMap->Map.end()) return I->second;
323 ConstantPointerRef *Ref = new ConstantPointerRef(V);
324 GVRefMap->Map[V] = Ref;
328 void Module::destroyConstantPointerRef(ConstantPointerRef *CPR) {
329 assert(GVRefMap && "No map allocated, but we have a CPR?");
330 if (!GVRefMap->Map.erase(CPR->getValue())) // Remove it from the map...
331 assert(0 && "ConstantPointerRef not found in module CPR map!");
333 if (GVRefMap->Map.empty()) { // If the map is empty, delete it.
339 void Module::mutateConstantPointerRef(GlobalValue *OldGV, GlobalValue *NewGV) {
340 assert(OldGV != NewGV && "Cannot mutate to the same global!");
341 GlobalValueRefMap::iterator I = GVRefMap->Map.find(OldGV);
342 assert(I != GVRefMap->Map.end() &&
343 "mutateConstantPointerRef; OldGV not in table!");
344 ConstantPointerRef *Ref = I->second;
346 // Remove the old entry...
347 GVRefMap->Map.erase(I);
349 // Check to see if a CPR already exists for NewGV
350 I = GVRefMap->Map.lower_bound(NewGV);
352 if (I == GVRefMap->Map.end() || I->first != NewGV) {
353 // Insert the new entry...
354 GVRefMap->Map.insert(I, std::make_pair(NewGV, Ref));
356 // Otherwise, an entry already exists for the current global value.
357 // Completely replace the old CPR with the existing one...
358 Ref->replaceAllUsesWith(I->second);