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 Function *ilist_traits<Function>::createNode() {
28 FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
29 Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
30 // This should not be garbage monitored.
31 LeakDetector::removeGarbageObject(Ret);
34 GlobalVariable *ilist_traits<GlobalVariable>::createNode() {
35 GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
36 GlobalValue::ExternalLinkage);
37 // This should not be garbage monitored.
38 LeakDetector::removeGarbageObject(Ret);
42 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
43 return M->getFunctionList();
45 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
46 return M->getGlobalList();
49 // Explicit instantiations of SymbolTableListTraits since some of the methods
50 // are not in the public header file...
51 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
52 template class SymbolTableListTraits<Function, Module, Module>;
54 // Define the GlobalValueRefMap as a struct that wraps a map so that we don't
55 // have Module.h depend on <map>
58 struct GlobalValueRefMap {
59 typedef std::map<GlobalValue*, ConstantPointerRef*> MapTy;
60 typedef MapTy::iterator iterator;
61 std::map<GlobalValue*, ConstantPointerRef*> Map;
66 Module::Module(const std::string &MID)
67 : ModuleID(MID), Endian(AnyEndianness), PtrSize(AnyPointerSize) {
68 FunctionList.setItemParent(this);
69 FunctionList.setParent(this);
70 GlobalList.setItemParent(this);
71 GlobalList.setParent(this);
73 SymTab = new SymbolTable();
79 GlobalList.setParent(0);
81 FunctionList.setParent(0);
85 // Module::dump() - Allow printing from debugger
86 void Module::dump() const {
90 // getOrInsertFunction - Look up the specified function in the module symbol
91 // table. If it does not exist, add a prototype for the function and return
92 // it. This is nice because it allows most passes to get away with not handling
93 // the symbol table directly for this common task.
95 Function *Module::getOrInsertFunction(const std::string &Name,
96 const FunctionType *Ty) {
97 SymbolTable &SymTab = getSymbolTable();
99 // See if we have a definitions for the specified function already...
100 if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
101 return cast<Function>(V); // Yup, got it
102 } else { // Nope, add one
103 Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
104 FunctionList.push_back(New);
105 return New; // Return the new prototype...
109 // getOrInsertFunction - Look up the specified function in the module symbol
110 // table. If it does not exist, add a prototype for the function and return it.
111 // This version of the method takes a null terminated list of function
112 // arguments, which makes it easier for clients to use.
114 Function *Module::getOrInsertFunction(const std::string &Name,
115 const Type *RetTy, ...) {
117 va_start(Args, RetTy);
119 // Build the list of argument types...
120 std::vector<const Type*> ArgTys;
121 while (const Type *ArgTy = va_arg(Args, const Type*))
122 ArgTys.push_back(ArgTy);
126 // Build the function type and chain to the other getOrInsertFunction...
127 return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
132 // getFunction - Look up the specified function in the module symbol table.
133 // If it does not exist, return null.
135 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
136 SymbolTable &SymTab = getSymbolTable();
137 return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
141 /// getMainFunction - This function looks up main efficiently. This is such a
142 /// common case, that it is a method in Module. If main cannot be found, a
143 /// null pointer is returned.
145 Function *Module::getMainFunction() {
146 std::vector<const Type*> Params;
149 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
153 // void main(void)...
154 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
158 Params.push_back(Type::IntTy);
160 // int main(int argc)...
161 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
165 // void main(int argc)...
166 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
170 for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
171 Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
173 // int main(int argc, char **argv)...
174 if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
178 // void main(int argc, char **argv)...
179 if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
184 // Ok, try to find main the hard way...
185 return getNamedFunction("main");
188 /// getNamedFunction - Return the first function in the module with the
189 /// specified name, of arbitrary type. This method returns null if a function
190 /// with the specified name is not found.
192 Function *Module::getNamedFunction(const std::string &Name) {
193 // Loop over all of the functions, looking for the function desired
195 for (iterator I = begin(), E = end(); I != E; ++I)
196 if (I->getName() == Name)
201 return Found; // Non-external function not found...
205 // addTypeName - Insert an entry in the symbol table mapping Str to Type. If
206 // there is already an entry for this name, true is returned and the symbol
207 // table is not modified.
209 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
210 SymbolTable &ST = getSymbolTable();
212 if (ST.lookup(Type::TypeTy, Name)) return true; // Already in symtab...
214 // Not in symbol table? Set the name with the Symtab as an argument so the
215 // type knows what to update...
216 ((Value*)Ty)->setName(Name, &ST);
221 /// getTypeByName - Return the type with the specified name in this module, or
222 /// null if there is none by that name.
223 const Type *Module::getTypeByName(const std::string &Name) const {
224 const SymbolTable &ST = getSymbolTable();
225 return cast_or_null<Type>(ST.lookup(Type::TypeTy, Name));
228 // getTypeName - If there is at least one entry in the symbol table for the
229 // specified type, return it.
231 std::string Module::getTypeName(const Type *Ty) const {
232 const SymbolTable &ST = getSymbolTable();
233 if (ST.find(Type::TypeTy) == ST.end())
234 return ""; // No names for types...
236 SymbolTable::type_const_iterator TI = ST.type_begin(Type::TypeTy);
237 SymbolTable::type_const_iterator TE = ST.type_end(Type::TypeTy);
239 while (TI != TE && TI->second != (const Value*)Ty)
242 if (TI != TE) // Must have found an entry!
244 return ""; // Must not have found anything...
248 // dropAllReferences() - This function causes all the subelementss to "let go"
249 // of all references that they are maintaining. This allows one to 'delete' a
250 // whole module at a time, even though there may be circular references... first
251 // all references are dropped, and all use counts go to zero. Then everything
252 // is deleted for real. Note that no operations are valid on an object that
253 // has "dropped all references", except operator delete.
255 void Module::dropAllReferences() {
256 for(Module::iterator I = begin(), E = end(); I != E; ++I)
257 I->dropAllReferences();
259 for(Module::giterator I = gbegin(), E = gend(); I != E; ++I)
260 I->dropAllReferences();
262 // If there are any GlobalVariable references still out there, nuke them now.
263 // Since all references are hereby dropped, nothing could possibly reference
264 // them still. Note that destroying all of the constant pointer refs will
265 // eventually cause the GVRefMap field to be set to null (by
266 // destroyConstantPointerRef, below).
269 // Delete the ConstantPointerRef node...
270 GVRefMap->Map.begin()->second->destroyConstant();
273 // Accessor for the underlying GlobalValRefMap...
274 ConstantPointerRef *Module::getConstantPointerRef(GlobalValue *V){
275 // Create ref map lazily on demand...
276 if (GVRefMap == 0) GVRefMap = new GlobalValueRefMap();
278 GlobalValueRefMap::iterator I = GVRefMap->Map.find(V);
279 if (I != GVRefMap->Map.end()) return I->second;
281 ConstantPointerRef *Ref = new ConstantPointerRef(V);
282 GVRefMap->Map[V] = Ref;
286 void Module::destroyConstantPointerRef(ConstantPointerRef *CPR) {
287 assert(GVRefMap && "No map allocated, but we have a CPR?");
288 if (!GVRefMap->Map.erase(CPR->getValue())) // Remove it from the map...
289 assert(0 && "ConstantPointerRef not found in module CPR map!");
291 if (GVRefMap->Map.empty()) { // If the map is empty, delete it.
297 void Module::mutateConstantPointerRef(GlobalValue *OldGV, GlobalValue *NewGV) {
298 assert(OldGV != NewGV && "Cannot mutate to the same global!");
299 GlobalValueRefMap::iterator I = GVRefMap->Map.find(OldGV);
300 assert(I != GVRefMap->Map.end() &&
301 "mutateConstantPointerRef; OldGV not in table!");
302 ConstantPointerRef *Ref = I->second;
304 // Remove the old entry...
305 GVRefMap->Map.erase(I);
307 // Check to see if a CPR already exists for NewGV
308 I = GVRefMap->Map.lower_bound(NewGV);
310 if (I == GVRefMap->Map.end() || I->first != NewGV) {
311 // Insert the new entry...
312 GVRefMap->Map.insert(I, std::make_pair(NewGV, Ref));
314 // Otherwise, an entry already exists for the current global value.
315 // Completely replace the old CPR with the existing one...
316 Ref->replaceAllUsesWith(I->second);