Change Module to use TargetData-compatible strings internally.
[oota-llvm.git] / lib / VMCore / Module.cpp
1 //===-- Module.cpp - Implement the Module class ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Module class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Module.h"
15 #include "llvm/InstrTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include <algorithm>
23 #include <cstdarg>
24 #include <cstdlib>
25 #include <iostream>
26 #include <map>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Methods to implement the globals and functions lists.
31 //
32
33 Function *ilist_traits<Function>::createSentinel() {
34   FunctionType *FTy =
35     FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
36   Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
37   // This should not be garbage monitored.
38   LeakDetector::removeGarbageObject(Ret);
39   return Ret;
40 }
41 GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
42   GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
43                                            GlobalValue::ExternalLinkage);
44   // This should not be garbage monitored.
45   LeakDetector::removeGarbageObject(Ret);
46   return Ret;
47 }
48
49 iplist<Function> &ilist_traits<Function>::getList(Module *M) {
50   return M->getFunctionList();
51 }
52 iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
53   return M->getGlobalList();
54 }
55
56 // Explicit instantiations of SymbolTableListTraits since some of the methods
57 // are not in the public header file.
58 template class SymbolTableListTraits<GlobalVariable, Module, Module>;
59 template class SymbolTableListTraits<Function, Module, Module>;
60
61 //===----------------------------------------------------------------------===//
62 // Primitive Module methods.
63 //
64
65 Module::Module(const std::string &MID)
66   : ModuleID(MID), DataLayout("") {
67   FunctionList.setItemParent(this);
68   FunctionList.setParent(this);
69   GlobalList.setItemParent(this);
70   GlobalList.setParent(this);
71   SymTab = new SymbolTable();
72 }
73
74 Module::~Module() {
75   dropAllReferences();
76   GlobalList.clear();
77   GlobalList.setParent(0);
78   FunctionList.clear();
79   FunctionList.setParent(0);
80   LibraryList.clear();
81   delete SymTab;
82 }
83
84 // Module::dump() - Allow printing from debugger
85 void Module::dump() const {
86   print(std::cerr);
87 }
88
89 /// Target endian information...
90 Module::Endianness Module::getEndianness() const {
91   std::string temp = DataLayout;
92   
93   while (temp.length() > 0) {
94     std::string token = getToken(temp, "-");
95     
96     if (token[0] == 'e') {
97       return LittleEndian;
98     } else if (token[0] == 'E') {
99       return BigEndian;
100     }
101   }
102   
103   return AnyEndianness;
104 }
105
106 void Module::setEndianness(Endianness E) {
107   if (DataLayout.compare("") != 0 && E != AnyEndianness)
108     DataLayout.insert(0, "-");
109   
110   if (E == LittleEndian)
111     DataLayout.insert(0, "e");
112   else if (E == BigEndian)
113     DataLayout.insert(0, "E");
114 }
115
116 /// Target Pointer Size information...
117 Module::PointerSize Module::getPointerSize() const {
118   std::string temp = DataLayout;
119   
120   while (temp.length() > 0) {
121     std::string token = getToken(temp, "-");
122     char signal = getToken(token, ":")[0];
123     
124     if (signal == 'p') {
125       int size = atoi(getToken(token, ":").c_str());
126       if (size == 32)
127         return Pointer32;
128       else if (size == 64)
129         return Pointer64;
130     }
131   }
132   
133   return AnyPointerSize;
134 }
135
136 void Module::setPointerSize(PointerSize PS) {
137   if (DataLayout.compare("") != 0 && PS != AnyPointerSize)
138     DataLayout.insert(0, "-");
139   
140   if (PS == Pointer32)
141     DataLayout.insert(0, "p:32:32");
142   else if (PS == Pointer64)
143     DataLayout.insert(0, "p:64:64");
144 }
145
146 //===----------------------------------------------------------------------===//
147 // Methods for easy access to the functions in the module.
148 //
149
150 // getOrInsertFunction - Look up the specified function in the module symbol
151 // table.  If it does not exist, add a prototype for the function and return
152 // it.  This is nice because it allows most passes to get away with not handling
153 // the symbol table directly for this common task.
154 //
155 Function *Module::getOrInsertFunction(const std::string &Name,
156                                       const FunctionType *Ty) {
157   SymbolTable &SymTab = getSymbolTable();
158
159   // See if we have a definitions for the specified function already...
160   if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
161     return cast<Function>(V);      // Yup, got it
162   } else {                         // Nope, add one
163     Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
164     FunctionList.push_back(New);
165     return New;                    // Return the new prototype...
166   }
167 }
168
169 // getOrInsertFunction - Look up the specified function in the module symbol
170 // table.  If it does not exist, add a prototype for the function and return it.
171 // This version of the method takes a null terminated list of function
172 // arguments, which makes it easier for clients to use.
173 //
174 Function *Module::getOrInsertFunction(const std::string &Name,
175                                       const Type *RetTy, ...) {
176   va_list Args;
177   va_start(Args, RetTy);
178
179   // Build the list of argument types...
180   std::vector<const Type*> ArgTys;
181   while (const Type *ArgTy = va_arg(Args, const Type*))
182     ArgTys.push_back(ArgTy);
183
184   va_end(Args);
185
186   // Build the function type and chain to the other getOrInsertFunction...
187   return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
188 }
189
190
191 // getFunction - Look up the specified function in the module symbol table.
192 // If it does not exist, return null.
193 //
194 Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
195   SymbolTable &SymTab = getSymbolTable();
196   return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
197 }
198
199
200 /// getMainFunction - This function looks up main efficiently.  This is such a
201 /// common case, that it is a method in Module.  If main cannot be found, a
202 /// null pointer is returned.
203 ///
204 Function *Module::getMainFunction() {
205   std::vector<const Type*> Params;
206
207   // int main(void)...
208   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
209                                                           Params, false)))
210     return F;
211
212   // void main(void)...
213   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
214                                                           Params, false)))
215     return F;
216
217   Params.push_back(Type::IntTy);
218
219   // int main(int argc)...
220   if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
221                                                           Params, false)))
222     return F;
223
224   // void main(int argc)...
225   if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
226                                                           Params, false)))
227     return F;
228
229   for (unsigned i = 0; i != 2; ++i) {  // Check argv and envp
230     Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
231
232     // int main(int argc, char **argv)...
233     if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
234                                                             Params, false)))
235       return F;
236
237     // void main(int argc, char **argv)...
238     if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
239                                                             Params, false)))
240       return F;
241   }
242
243   // Ok, try to find main the hard way...
244   return getNamedFunction("main");
245 }
246
247 /// getNamedFunction - Return the first function in the module with the
248 /// specified name, of arbitrary type.  This method returns null if a function
249 /// with the specified name is not found.
250 ///
251 Function *Module::getNamedFunction(const std::string &Name) {
252   // Loop over all of the functions, looking for the function desired
253   Function *Found = 0;
254   for (iterator I = begin(), E = end(); I != E; ++I)
255     if (I->getName() == Name)
256       if (I->isExternal())
257         Found = I;
258       else
259         return I;
260   return Found; // Non-external function not found...
261 }
262
263 //===----------------------------------------------------------------------===//
264 // Methods for easy access to the global variables in the module.
265 //
266
267 /// getGlobalVariable - Look up the specified global variable in the module
268 /// symbol table.  If it does not exist, return null.  The type argument
269 /// should be the underlying type of the global, i.e., it should not have
270 /// the top-level PointerType, which represents the address of the global.
271 /// If AllowInternal is set to true, this function will return types that
272 /// have InternalLinkage. By default, these types are not returned.
273 ///
274 GlobalVariable *Module::getGlobalVariable(const std::string &Name,
275                                           const Type *Ty, bool AllowInternal) {
276   if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
277     GlobalVariable *Result = cast<GlobalVariable>(V);
278     if (AllowInternal || !Result->hasInternalLinkage())
279       return Result;
280   }
281   return 0;
282 }
283
284 /// getNamedGlobal - Return the first global variable in the module with the
285 /// specified name, of arbitrary type.  This method returns null if a global
286 /// with the specified name is not found.
287 ///
288 GlobalVariable *Module::getNamedGlobal(const std::string &Name) {
289   // FIXME: This would be much faster with a symbol table that doesn't
290   // discriminate based on type!
291   for (global_iterator I = global_begin(), E = global_end();
292        I != E; ++I)
293     if (I->getName() == Name) 
294       return I;
295   return 0;
296 }
297
298
299
300 //===----------------------------------------------------------------------===//
301 // Methods for easy access to the types in the module.
302 //
303
304
305 // addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
306 // there is already an entry for this name, true is returned and the symbol
307 // table is not modified.
308 //
309 bool Module::addTypeName(const std::string &Name, const Type *Ty) {
310   SymbolTable &ST = getSymbolTable();
311
312   if (ST.lookupType(Name)) return true;  // Already in symtab...
313
314   // Not in symbol table?  Set the name with the Symtab as an argument so the
315   // type knows what to update...
316   ST.insert(Name, Ty);
317
318   return false;
319 }
320
321 /// getTypeByName - Return the type with the specified name in this module, or
322 /// null if there is none by that name.
323 const Type *Module::getTypeByName(const std::string &Name) const {
324   const SymbolTable &ST = getSymbolTable();
325   return cast_or_null<Type>(ST.lookupType(Name));
326 }
327
328 // getTypeName - If there is at least one entry in the symbol table for the
329 // specified type, return it.
330 //
331 std::string Module::getTypeName(const Type *Ty) const {
332   const SymbolTable &ST = getSymbolTable();
333
334   SymbolTable::type_const_iterator TI = ST.type_begin();
335   SymbolTable::type_const_iterator TE = ST.type_end();
336   if ( TI == TE ) return ""; // No names for types
337
338   while (TI != TE && TI->second != Ty)
339     ++TI;
340
341   if (TI != TE)  // Must have found an entry!
342     return TI->first;
343   return "";     // Must not have found anything...
344 }
345
346 //===----------------------------------------------------------------------===//
347 // Other module related stuff.
348 //
349
350
351 // dropAllReferences() - This function causes all the subelementss to "let go"
352 // of all references that they are maintaining.  This allows one to 'delete' a
353 // whole module at a time, even though there may be circular references... first
354 // all references are dropped, and all use counts go to zero.  Then everything
355 // is deleted for real.  Note that no operations are valid on an object that
356 // has "dropped all references", except operator delete.
357 //
358 void Module::dropAllReferences() {
359   for(Module::iterator I = begin(), E = end(); I != E; ++I)
360     I->dropAllReferences();
361
362   for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
363     I->dropAllReferences();
364 }
365