501625df7a3dcb3e127f6c16f7ff5c391de29346
[oota-llvm.git] / include / llvm / Module.h
1 //===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// Module.h This file contains the declarations for the Module class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_MODULE_H
16 #define LLVM_MODULE_H
17
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/Metadata.h"
22 #include "llvm/Support/DataTypes.h"
23 #include <vector>
24
25 namespace llvm {
26
27 class GlobalValueRefMap;   // Used by ConstantVals.cpp
28 class FunctionType;
29 class LLVMContext;
30
31 template<> struct ilist_traits<Function>
32   : public SymbolTableListTraits<Function, Module> {
33
34   // createSentinel is used to get hold of the node that marks the end of the
35   // list... (same trick used here as in ilist_traits<Instruction>)
36   Function *createSentinel() const {
37     return static_cast<Function*>(&Sentinel);
38   }
39   static void destroySentinel(Function*) {}
40
41   Function *provideInitialHead() const { return createSentinel(); }
42   Function *ensureHead(Function*) const { return createSentinel(); }
43   static void noteHead(Function*, Function*) {}
44
45 private:
46   mutable ilist_node<Function> Sentinel;
47 };
48 template<> struct ilist_traits<GlobalVariable>
49   : public SymbolTableListTraits<GlobalVariable, Module> {
50   // createSentinel is used to create a node that marks the end of the list.
51   static GlobalVariable *createSentinel();
52   static void destroySentinel(GlobalVariable *GV) { delete GV; }
53 };
54 template<> struct ilist_traits<GlobalAlias>
55   : public SymbolTableListTraits<GlobalAlias, Module> {
56   // createSentinel is used to create a node that marks the end of the list.
57   static GlobalAlias *createSentinel();
58   static void destroySentinel(GlobalAlias *GA) { delete GA; }
59 };
60 template<> struct ilist_traits<NamedMDNode>
61   : public SymbolTableListTraits<NamedMDNode, Module> {
62   // createSentinel is used to get hold of a node that marks the end of
63   // the list...
64   NamedMDNode *createSentinel() const {
65     return static_cast<NamedMDNode*>(&Sentinel);
66   }
67   static void destroySentinel(NamedMDNode*) {}
68
69   NamedMDNode *provideInitialHead() const { return createSentinel(); }
70   NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
71   static void noteHead(NamedMDNode*, NamedMDNode*) {}
72 private:
73   mutable ilist_node<NamedMDNode> Sentinel;
74 };
75
76 /// A Module instance is used to store all the information related to an
77 /// LLVM module. Modules are the top level container of all other LLVM
78 /// Intermediate Representation (IR) objects. Each module directly contains a
79 /// list of globals variables, a list of functions, a list of libraries (or
80 /// other modules) this module depends on, a symbol table, and various data
81 /// about the target's characteristics.
82 ///
83 /// A module maintains a GlobalValRefMap object that is used to hold all
84 /// constant references to global variables in the module.  When a global
85 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
86 /// @brief The main container class for the LLVM Intermediate Representation.
87 class Module {
88 /// @name Types And Enumerations
89 /// @{
90 public:
91   /// The type for the list of global variables.
92   typedef iplist<GlobalVariable> GlobalListType;
93   /// The type for the list of functions.
94   typedef iplist<Function> FunctionListType;
95   /// The type for the list of aliases.
96   typedef iplist<GlobalAlias> AliasListType;
97   /// The type for the list of named metadata.
98   typedef iplist<NamedMDNode> NamedMDListType;
99
100   /// The type for the list of dependent libraries.
101   typedef std::vector<std::string> LibraryListType;
102
103   /// The Global Variable iterator.
104   typedef GlobalListType::iterator                      global_iterator;
105   /// The Global Variable constant iterator.
106   typedef GlobalListType::const_iterator          const_global_iterator;
107
108   /// The Function iterators.
109   typedef FunctionListType::iterator                           iterator;
110   /// The Function constant iterator
111   typedef FunctionListType::const_iterator               const_iterator;
112
113   /// The Global Alias iterators.
114   typedef AliasListType::iterator                        alias_iterator;
115   /// The Global Alias constant iterator
116   typedef AliasListType::const_iterator            const_alias_iterator;
117
118   /// The named metadata iterators.
119   typedef NamedMDListType::iterator             named_metadata_iterator;
120   /// The named metadata constant interators.
121   typedef NamedMDListType::const_iterator const_named_metadata_iterator;
122   /// The Library list iterator.
123   typedef LibraryListType::const_iterator lib_iterator;
124
125   /// An enumeration for describing the endianess of the target machine.
126   enum Endianness  { AnyEndianness, LittleEndian, BigEndian };
127
128   /// An enumeration for describing the size of a pointer on the target machine.
129   enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
130
131 /// @}
132 /// @name Member Variables
133 /// @{
134 private:
135   LLVMContext& Context;          ///< The LLVMContext from which types and
136                                  ///< constants are allocated.
137   GlobalListType GlobalList;     ///< The Global Variables in the module
138   FunctionListType FunctionList; ///< The Functions in the module
139   AliasListType AliasList;       ///< The Aliases in the module
140   LibraryListType LibraryList;   ///< The Libraries needed by the module
141   NamedMDListType NamedMDList;   ///< The named metadata in the module
142   std::string GlobalScopeAsm;    ///< Inline Asm at global scope.
143   ValueSymbolTable *ValSymTab;   ///< Symbol table for values
144   TypeSymbolTable *TypeSymTab;   ///< Symbol table for types
145   std::string ModuleID;          ///< Human readable identifier for the module
146   std::string TargetTriple;      ///< Platform target triple Module compiled on
147   std::string DataLayout;        ///< Target data description
148
149   friend class Constant;
150
151 /// @}
152 /// @name Constructors
153 /// @{
154 public:
155   /// The Module constructor. Note that there is no default constructor. You
156   /// must provide a name for the module upon construction.
157   explicit Module(const StringRef &ModuleID, LLVMContext& C);
158   /// The module destructor. This will dropAllReferences.
159   ~Module();
160
161 /// @}
162 /// @name Module Level Accessors
163 /// @{
164 public:
165   /// Get the module identifier which is, essentially, the name of the module.
166   /// @returns the module identifier as a string
167   const std::string &getModuleIdentifier() const { return ModuleID; }
168
169   /// Get the data layout string for the module's target platform.  This encodes
170   /// the type sizes and alignments expected by this module.
171   /// @returns the data layout as a string
172   const std::string &getDataLayout() const { return DataLayout; }
173
174   /// Get the target triple which is a string describing the target host.
175   /// @returns a string containing the target triple.
176   const std::string &getTargetTriple() const { return TargetTriple; }
177
178   /// Get the target endian information.
179   /// @returns Endianess - an enumeration for the endianess of the target
180   Endianness getEndianness() const;
181
182   /// Get the target pointer size.
183   /// @returns PointerSize - an enumeration for the size of the target's pointer
184   PointerSize getPointerSize() const;
185
186   /// Get the global data context.
187   /// @returns LLVMContext - a container for LLVM's global information
188   LLVMContext& getContext() const { return Context; }
189
190   /// Get any module-scope inline assembly blocks.
191   /// @returns a string containing the module-scope inline assembly blocks.
192   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
193 /// @}
194 /// @name Module Level Mutators
195 /// @{
196 public:
197
198   /// Set the module identifier.
199   void setModuleIdentifier(const StringRef &ID) { ModuleID = ID; }
200
201   /// Set the data layout
202   void setDataLayout(const StringRef &DL) { DataLayout = DL; }
203
204   /// Set the target triple.
205   void setTargetTriple(const StringRef &T) { TargetTriple = T; }
206
207   /// Set the module-scope inline assembly blocks.
208   void setModuleInlineAsm(const StringRef &Asm) { GlobalScopeAsm = Asm; }
209
210   /// Append to the module-scope inline assembly blocks, automatically
211   /// appending a newline to the end.
212   void appendModuleInlineAsm(const StringRef &Asm) {
213     GlobalScopeAsm += Asm;
214     GlobalScopeAsm += '\n';
215   }
216
217 /// @}
218 /// @name Generic Value Accessors
219 /// @{
220
221   /// getNamedValue - Return the first global value in the module with
222   /// the specified name, of arbitrary type.  This method returns null
223   /// if a global with the specified name is not found.
224   GlobalValue *getNamedValue(const StringRef &Name) const;
225
226 /// @}
227 /// @name Function Accessors
228 /// @{
229 public:
230   /// getOrInsertFunction - Look up the specified function in the module symbol
231   /// table.  Four possibilities:
232   ///   1. If it does not exist, add a prototype for the function and return it.
233   ///   2. If it exists, and has a local linkage, the existing function is
234   ///      renamed and a new one is inserted.
235   ///   3. Otherwise, if the existing function has the correct prototype, return
236   ///      the existing function.
237   ///   4. Finally, the function exists but has the wrong prototype: return the
238   ///      function with a constantexpr cast to the right prototype.
239   Constant *getOrInsertFunction(const StringRef &Name, const FunctionType *T,
240                                 AttrListPtr AttributeList);
241
242   Constant *getOrInsertFunction(const StringRef &Name, const FunctionType *T);
243
244   /// getOrInsertFunction - Look up the specified function in the module symbol
245   /// table.  If it does not exist, add a prototype for the function and return
246   /// it.  This function guarantees to return a constant of pointer to the
247   /// specified function type or a ConstantExpr BitCast of that type if the
248   /// named function has a different type.  This version of the method takes a
249   /// null terminated list of function arguments, which makes it easier for
250   /// clients to use.
251   Constant *getOrInsertFunction(const StringRef &Name,
252                                 AttrListPtr AttributeList,
253                                 const Type *RetTy, ...)  END_WITH_NULL;
254
255   Constant *getOrInsertFunction(const StringRef &Name, const Type *RetTy, ...)
256     END_WITH_NULL;
257
258   Constant *getOrInsertTargetIntrinsic(const StringRef &Name,
259                                        const FunctionType *Ty,
260                                        AttrListPtr AttributeList);
261   
262   /// getFunction - Look up the specified function in the module symbol table.
263   /// If it does not exist, return null.
264   Function *getFunction(const StringRef &Name) const;
265
266 /// @}
267 /// @name Global Variable Accessors
268 /// @{
269 public:
270   /// getGlobalVariable - Look up the specified global variable in the module
271   /// symbol table.  If it does not exist, return null. If AllowInternal is set
272   /// to true, this function will return types that have InternalLinkage. By
273   /// default, these types are not returned.
274   GlobalVariable *getGlobalVariable(const StringRef &Name,
275                                     bool AllowInternal = false) const;
276
277   /// getNamedGlobal - Return the first global variable in the module with the
278   /// specified name, of arbitrary type.  This method returns null if a global
279   /// with the specified name is not found.
280   GlobalVariable *getNamedGlobal(const StringRef &Name) const {
281     return getGlobalVariable(Name, true);
282   }
283
284   /// getOrInsertGlobal - Look up the specified global in the module symbol
285   /// table.
286   ///   1. If it does not exist, add a declaration of the global and return it.
287   ///   2. Else, the global exists but has the wrong type: return the function
288   ///      with a constantexpr cast to the right type.
289   ///   3. Finally, if the existing global is the correct delclaration, return
290   ///      the existing global.
291   Constant *getOrInsertGlobal(const StringRef &Name, const Type *Ty);
292
293 /// @}
294 /// @name Global Alias Accessors
295 /// @{
296 public:
297   /// getNamedAlias - Return the first global alias in the module with the
298   /// specified name, of arbitrary type.  This method returns null if a global
299   /// with the specified name is not found.
300   GlobalAlias *getNamedAlias(const StringRef &Name) const;
301
302 /// @}
303 /// @name Named Metadata Accessors
304 /// @{
305 public:
306   /// getNamedMetadata - Return the first NamedMDNode in the module with the
307   /// specified name. This method returns null if a NamedMDNode with the 
308   /// specified name is not found.
309   NamedMDNode *getNamedMetadata(const StringRef &Name) const;
310
311   /// getOrInsertNamedMetadata - Return the first named MDNode in the module 
312   /// with the specified name. This method returns a new NamedMDNode if a 
313   /// NamedMDNode with the specified name is not found.
314   NamedMDNode *getOrInsertNamedMetadata(const StringRef &Name);
315
316 /// @}
317 /// @name Type Accessors
318 /// @{
319 public:
320   /// addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
321   /// there is already an entry for this name, true is returned and the symbol
322   /// table is not modified.
323   bool addTypeName(const StringRef &Name, const Type *Ty);
324
325   /// getTypeName - If there is at least one entry in the symbol table for the
326   /// specified type, return it.
327   std::string getTypeName(const Type *Ty) const;
328
329   /// getTypeByName - Return the type with the specified name in this module, or
330   /// null if there is none by that name.
331   const Type *getTypeByName(const StringRef &Name) const;
332
333 /// @}
334 /// @name Direct access to the globals list, functions list, and symbol table
335 /// @{
336 public:
337   /// Get the Module's list of global variables (constant).
338   const GlobalListType   &getGlobalList() const       { return GlobalList; }
339   /// Get the Module's list of global variables.
340   GlobalListType         &getGlobalList()             { return GlobalList; }
341   static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
342     return &Module::GlobalList;
343   }
344   /// Get the Module's list of functions (constant).
345   const FunctionListType &getFunctionList() const     { return FunctionList; }
346   /// Get the Module's list of functions.
347   FunctionListType       &getFunctionList()           { return FunctionList; }
348   static iplist<Function> Module::*getSublistAccess(Function*) {
349     return &Module::FunctionList;
350   }
351   /// Get the Module's list of aliases (constant).
352   const AliasListType    &getAliasList() const        { return AliasList; }
353   /// Get the Module's list of aliases.
354   AliasListType          &getAliasList()              { return AliasList; }
355   static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
356     return &Module::AliasList;
357   }
358   /// Get the Module's list of named metadata (constant).
359   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
360   /// Get the Module's list of named metadata.
361   NamedMDListType  &getNamedMDList()                  { return NamedMDList; }
362   static iplist<NamedMDNode> Module::*getSublistAccess(NamedMDNode *) {
363     return &Module::NamedMDList;
364   }
365   /// Get the symbol table of global variable and function identifiers
366   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
367   /// Get the Module's symbol table of global variable and function identifiers.
368   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
369   /// Get the symbol table of types
370   const TypeSymbolTable  &getTypeSymbolTable() const  { return *TypeSymTab; }
371   /// Get the Module's symbol table of types
372   TypeSymbolTable        &getTypeSymbolTable()        { return *TypeSymTab; }
373
374 /// @}
375 /// @name Global Variable Iteration
376 /// @{
377 public:
378   /// Get an iterator to the first global variable
379   global_iterator       global_begin()       { return GlobalList.begin(); }
380   /// Get a constant iterator to the first global variable
381   const_global_iterator global_begin() const { return GlobalList.begin(); }
382   /// Get an iterator to the last global variable
383   global_iterator       global_end  ()       { return GlobalList.end(); }
384   /// Get a constant iterator to the last global variable
385   const_global_iterator global_end  () const { return GlobalList.end(); }
386   /// Determine if the list of globals is empty.
387   bool                  global_empty() const { return GlobalList.empty(); }
388
389 /// @}
390 /// @name Function Iteration
391 /// @{
392 public:
393   /// Get an iterator to the first function.
394   iterator                begin()       { return FunctionList.begin(); }
395   /// Get a constant iterator to the first function.
396   const_iterator          begin() const { return FunctionList.begin(); }
397   /// Get an iterator to the last function.
398   iterator                end  ()       { return FunctionList.end();   }
399   /// Get a constant iterator to the last function.
400   const_iterator          end  () const { return FunctionList.end();   }
401   /// Determine how many functions are in the Module's list of functions.
402   size_t                  size() const  { return FunctionList.size(); }
403   /// Determine if the list of functions is empty.
404   bool                    empty() const { return FunctionList.empty(); }
405
406 /// @}
407 /// @name Dependent Library Iteration
408 /// @{
409 public:
410   /// @brief Get a constant iterator to beginning of dependent library list.
411   inline lib_iterator lib_begin() const { return LibraryList.begin(); }
412   /// @brief Get a constant iterator to end of dependent library list.
413   inline lib_iterator lib_end()   const { return LibraryList.end();   }
414   /// @brief Returns the number of items in the list of libraries.
415   inline size_t       lib_size()  const { return LibraryList.size();  }
416   /// @brief Add a library to the list of dependent libraries
417   void addLibrary(const StringRef &Lib);
418   /// @brief Remove a library from the list of dependent libraries
419   void removeLibrary(const StringRef &Lib);
420   /// @brief Get all the libraries
421   inline const LibraryListType& getLibraries() const { return LibraryList; }
422
423 /// @}
424 /// @name Alias Iteration
425 /// @{
426 public:
427   /// Get an iterator to the first alias.
428   alias_iterator       alias_begin()            { return AliasList.begin(); }
429   /// Get a constant iterator to the first alias.
430   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
431   /// Get an iterator to the last alias.
432   alias_iterator       alias_end  ()            { return AliasList.end();   }
433   /// Get a constant iterator to the last alias.
434   const_alias_iterator alias_end  () const      { return AliasList.end();   }
435   /// Determine how many aliases are in the Module's list of aliases.
436   size_t               alias_size () const      { return AliasList.size();  }
437   /// Determine if the list of aliases is empty.
438   bool                 alias_empty() const      { return AliasList.empty(); }
439
440
441 /// @}
442 /// @name Named Metadata Iteration
443 /// @{
444 public:
445   /// Get an iterator to the first named metadata.
446   named_metadata_iterator       named_metadata_begin()            
447                                                 { return NamedMDList.begin(); }
448   /// Get a constant iterator to the first named metadata.
449   const_named_metadata_iterator named_metadata_begin() const      
450                                                 { return NamedMDList.begin(); }
451   /// Get an iterator to the last named metadata.
452   named_metadata_iterator       named_metadata_end  ()            
453                                                 { return NamedMDList.end();   }
454   /// Get a constant iterator to the last named metadata.
455   const_named_metadata_iterator named_metadata_end  () const      
456                                                 { return NamedMDList.end();   }
457   /// Determine how many NamedMDNodes are in the Module's list of named metadata.
458   size_t                        named_metadata_size () const      
459                                                 { return NamedMDList.size();  }
460   /// Determine if the list of named metadata is empty.
461   bool                          named_metadata_empty() const      
462                                                 { return NamedMDList.empty(); }
463
464
465 /// @}
466 /// @name Utility functions for printing and dumping Module objects
467 /// @{
468 public:
469   /// Print the module to an output stream with AssemblyAnnotationWriter.
470   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
471   
472   /// Dump the module to stderr (for debugging).
473   void dump() const;
474   /// This function causes all the subinstructions to "let go" of all references
475   /// that they are maintaining.  This allows one to 'delete' a whole class at
476   /// a time, even though there may be circular references... first all
477   /// references are dropped, and all use counts go to zero.  Then everything
478   /// is delete'd for real.  Note that no operations are valid on an object
479   /// that has "dropped all references", except operator delete.
480   void dropAllReferences();
481 /// @}
482 };
483
484 /// An raw_ostream inserter for modules.
485 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
486   M.print(O, 0);
487   return O;
488 }
489
490 } // End llvm namespace
491
492 #endif