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