LLVM API Documentation

Module.cpp

Go to the documentation of this file.
00001 //===-- Module.cpp - Implement the Module class ---------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Module class for the VMCore library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Module.h"
00015 #include "llvm/InstrTypes.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/Support/LeakDetector.h"
00021 #include "SymbolTableListTraitsImpl.h"
00022 #include <algorithm>
00023 #include <cstdarg>
00024 #include <cstdlib>
00025 #include <iostream>
00026 #include <map>
00027 using namespace llvm;
00028 
00029 //===----------------------------------------------------------------------===//
00030 // Methods to implement the globals and functions lists.
00031 //
00032 
00033 Function *ilist_traits<Function>::createSentinel() {
00034   FunctionType *FTy =
00035     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
00036   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
00037   // This should not be garbage monitored.
00038   LeakDetector::removeGarbageObject(Ret);
00039   return Ret;
00040 }
00041 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
00042   GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
00043                                            GlobalValue::ExternalLinkage);
00044   // This should not be garbage monitored.
00045   LeakDetector::removeGarbageObject(Ret);
00046   return Ret;
00047 }
00048 
00049 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
00050   return M->getFunctionList();
00051 }
00052 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
00053   return M->getGlobalList();
00054 }
00055 
00056 // Explicit instantiations of SymbolTableListTraits since some of the methods
00057 // are not in the public header file.
00058 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
00059 template class SymbolTableListTraits<Function, Module, Module>;
00060 
00061 //===----------------------------------------------------------------------===//
00062 // Primitive Module methods.
00063 //
00064 
00065 Module::Module(const std::string &MID)
00066   : ModuleID(MID), DataLayout("") {
00067   FunctionList.setItemParent(this);
00068   FunctionList.setParent(this);
00069   GlobalList.setItemParent(this);
00070   GlobalList.setParent(this);
00071   SymTab = new SymbolTable();
00072 }
00073 
00074 Module::~Module() {
00075   dropAllReferences();
00076   GlobalList.clear();
00077   GlobalList.setParent(0);
00078   FunctionList.clear();
00079   FunctionList.setParent(0);
00080   LibraryList.clear();
00081   delete SymTab;
00082 }
00083 
00084 // Module::dump() - Allow printing from debugger
00085 void Module::dump() const {
00086   print(std::cerr);
00087 }
00088 
00089 /// Target endian information...
00090 Module::Endianness Module::getEndianness() const {
00091   std::string temp = DataLayout;
00092   Module::Endianness ret = AnyEndianness;
00093   
00094   while (!temp.empty()) {
00095     std::string token = getToken(temp, "-");
00096     
00097     if (token[0] == 'e') {
00098       ret = LittleEndian;
00099     } else if (token[0] == 'E') {
00100       ret = BigEndian;
00101     }
00102   }
00103   
00104   return ret;
00105 }
00106 
00107 void Module::setEndianness(Endianness E) {
00108   if (!DataLayout.empty() && E != AnyEndianness)
00109     DataLayout += "-";
00110   
00111   if (E == LittleEndian)
00112     DataLayout += "e";
00113   else if (E == BigEndian)
00114     DataLayout += "E";
00115 }
00116 
00117 /// Target Pointer Size information...
00118 Module::PointerSize Module::getPointerSize() const {
00119   std::string temp = DataLayout;
00120   Module::PointerSize ret = AnyPointerSize;
00121   
00122   while (!temp.empty()) {
00123     std::string token = getToken(temp, "-");
00124     char signal = getToken(token, ":")[0];
00125     
00126     if (signal == 'p') {
00127       int size = atoi(getToken(token, ":").c_str());
00128       if (size == 32)
00129         ret = Pointer32;
00130       else if (size == 64)
00131         ret = Pointer64;
00132     }
00133   }
00134   
00135   return ret;
00136 }
00137 
00138 void Module::setPointerSize(PointerSize PS) {
00139   if (!DataLayout.empty() && PS != AnyPointerSize)
00140     DataLayout += "-";
00141   
00142   if (PS == Pointer32)
00143     DataLayout += "p:32:32";
00144   else if (PS == Pointer64)
00145     DataLayout += "p:64:64";
00146 }
00147 
00148 //===----------------------------------------------------------------------===//
00149 // Methods for easy access to the functions in the module.
00150 //
00151 
00152 // getOrInsertFunction - Look up the specified function in the module symbol
00153 // table.  If it does not exist, add a prototype for the function and return
00154 // it.  This is nice because it allows most passes to get away with not handling
00155 // the symbol table directly for this common task.
00156 //
00157 Function *Module::getOrInsertFunction(const std::string &Name,
00158                                       const FunctionType *Ty) {
00159   SymbolTable &SymTab = getSymbolTable();
00160 
00161   // See if we have a definitions for the specified function already...
00162   if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
00163     return cast<Function>(V);      // Yup, got it
00164   } else {                         // Nope, add one
00165     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
00166     FunctionList.push_back(New);
00167     return New;                    // Return the new prototype...
00168   }
00169 }
00170 
00171 // getOrInsertFunction - Look up the specified function in the module symbol
00172 // table.  If it does not exist, add a prototype for the function and return it.
00173 // This version of the method takes a null terminated list of function
00174 // arguments, which makes it easier for clients to use.
00175 //
00176 Function *Module::getOrInsertFunction(const std::string &Name,
00177                                       const Type *RetTy, ...) {
00178   va_list Args;
00179   va_start(Args, RetTy);
00180 
00181   // Build the list of argument types...
00182   std::vector<const Type*> ArgTys;
00183   while (const Type *ArgTy = va_arg(Args, const Type*))
00184     ArgTys.push_back(ArgTy);
00185 
00186   va_end(Args);
00187 
00188   // Build the function type and chain to the other getOrInsertFunction...
00189   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
00190 }
00191 
00192 
00193 // getFunction - Look up the specified function in the module symbol table.
00194 // If it does not exist, return null.
00195 //
00196 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
00197   SymbolTable &SymTab = getSymbolTable();
00198   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
00199 }
00200 
00201 
00202 /// getMainFunction - This function looks up main efficiently.  This is such a
00203 /// common case, that it is a method in Module.  If main cannot be found, a
00204 /// null pointer is returned.
00205 ///
00206 Function *Module::getMainFunction() {
00207   std::vector<const Type*> Params;
00208 
00209   // int main(void)...
00210   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
00211                                                           Params, false)))
00212     return F;
00213 
00214   // void main(void)...
00215   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
00216                                                           Params, false)))
00217     return F;
00218 
00219   Params.push_back(Type::IntTy);
00220 
00221   // int main(int argc)...
00222   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
00223                                                           Params, false)))
00224     return F;
00225 
00226   // void main(int argc)...
00227   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
00228                                                           Params, false)))
00229     return F;
00230 
00231   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
00232     Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
00233 
00234     // int main(int argc, char **argv)...
00235     if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
00236                                                             Params, false)))
00237       return F;
00238 
00239     // void main(int argc, char **argv)...
00240     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
00241                                                             Params, false)))
00242       return F;
00243   }
00244 
00245   // Ok, try to find main the hard way...
00246   return getNamedFunction("main");
00247 }
00248 
00249 /// getNamedFunction - Return the first function in the module with the
00250 /// specified name, of arbitrary type.  This method returns null if a function
00251 /// with the specified name is not found.
00252 ///
00253 Function *Module::getNamedFunction(const std::string &Name) const {
00254   // Loop over all of the functions, looking for the function desired
00255   const Function *Found = 0;
00256   for (const_iterator I = begin(), E = end(); I != E; ++I)
00257     if (I->getName() == Name)
00258       if (I->isExternal())
00259         Found = I;
00260       else
00261         return const_cast<Function*>(&(*I));
00262   return const_cast<Function*>(Found); // Non-external function not found...
00263 }
00264 
00265 //===----------------------------------------------------------------------===//
00266 // Methods for easy access to the global variables in the module.
00267 //
00268 
00269 /// getGlobalVariable - Look up the specified global variable in the module
00270 /// symbol table.  If it does not exist, return null.  The type argument
00271 /// should be the underlying type of the global, i.e., it should not have
00272 /// the top-level PointerType, which represents the address of the global.
00273 /// If AllowInternal is set to true, this function will return types that
00274 /// have InternalLinkage. By default, these types are not returned.
00275 ///
00276 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
00277                                           const Type *Ty, bool AllowInternal) {
00278   if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
00279     GlobalVariable *Result = cast<GlobalVariable>(V);
00280     if (AllowInternal || !Result->hasInternalLinkage())
00281       return Result;
00282   }
00283   return 0;
00284 }
00285 
00286 /// getNamedGlobal - Return the first global variable in the module with the
00287 /// specified name, of arbitrary type.  This method returns null if a global
00288 /// with the specified name is not found.
00289 ///
00290 GlobalVariable *Module::getNamedGlobal(const std::string &Name) const {
00291   // FIXME: This would be much faster with a symbol table that doesn't
00292   // discriminate based on type!
00293   for (const_global_iterator I = global_begin(), E = global_end();
00294        I != E; ++I)
00295     if (I->getName() == Name) 
00296       return const_cast<GlobalVariable*>(&(*I));
00297   return 0;
00298 }
00299 
00300 
00301 
00302 //===----------------------------------------------------------------------===//
00303 // Methods for easy access to the types in the module.
00304 //
00305 
00306 
00307 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
00308 // there is already an entry for this name, true is returned and the symbol
00309 // table is not modified.
00310 //
00311 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
00312   SymbolTable &ST = getSymbolTable();
00313 
00314   if (ST.lookupType(Name)) return true;  // Already in symtab...
00315 
00316   // Not in symbol table?  Set the name with the Symtab as an argument so the
00317   // type knows what to update...
00318   ST.insert(Name, Ty);
00319 
00320   return false;
00321 }
00322 
00323 /// getTypeByName - Return the type with the specified name in this module, or
00324 /// null if there is none by that name.
00325 const Type *Module::getTypeByName(const std::string &Name) const {
00326   const SymbolTable &ST = getSymbolTable();
00327   return cast_or_null<Type>(ST.lookupType(Name));
00328 }
00329 
00330 // getTypeName - If there is at least one entry in the symbol table for the
00331 // specified type, return it.
00332 //
00333 std::string Module::getTypeName(const Type *Ty) const {
00334   const SymbolTable &ST = getSymbolTable();
00335 
00336   SymbolTable::type_const_iterator TI = ST.type_begin();
00337   SymbolTable::type_const_iterator TE = ST.type_end();
00338   if ( TI == TE ) return ""; // No names for types
00339 
00340   while (TI != TE && TI->second != Ty)
00341     ++TI;
00342 
00343   if (TI != TE)  // Must have found an entry!
00344     return TI->first;
00345   return "";     // Must not have found anything...
00346 }
00347 
00348 //===----------------------------------------------------------------------===//
00349 // Other module related stuff.
00350 //
00351 
00352 
00353 // dropAllReferences() - This function causes all the subelementss to "let go"
00354 // of all references that they are maintaining.  This allows one to 'delete' a
00355 // whole module at a time, even though there may be circular references... first
00356 // all references are dropped, and all use counts go to zero.  Then everything
00357 // is deleted for real.  Note that no operations are valid on an object that
00358 // has "dropped all references", except operator delete.
00359 //
00360 void Module::dropAllReferences() {
00361   for(Module::iterator I = begin(), E = end(); I != E; ++I)
00362     I->dropAllReferences();
00363 
00364   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
00365     I->dropAllReferences();
00366 }
00367