Keep track of named mdnodes in a Module using an ilist.
[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 named MDNode in the module with the
307   /// specified name. This method returns null if a MDNode with the specified
308   /// name is not found.
309   NamedMDNode *getNamedMetadata(const StringRef &Name) const;
310
311 /// @}
312 /// @name Type Accessors
313 /// @{
314 public:
315   /// addTypeName - Insert an entry in the symbol table mapping Str to Type.  If
316   /// there is already an entry for this name, true is returned and the symbol
317   /// table is not modified.
318   bool addTypeName(const StringRef &Name, const Type *Ty);
319
320   /// getTypeName - If there is at least one entry in the symbol table for the
321   /// specified type, return it.
322   std::string getTypeName(const Type *Ty) const;
323
324   /// getTypeByName - Return the type with the specified name in this module, or
325   /// null if there is none by that name.
326   const Type *getTypeByName(const StringRef &Name) const;
327
328 /// @}
329 /// @name Direct access to the globals list, functions list, and symbol table
330 /// @{
331 public:
332   /// Get the Module's list of global variables (constant).
333   const GlobalListType   &getGlobalList() const       { return GlobalList; }
334   /// Get the Module's list of global variables.
335   GlobalListType         &getGlobalList()             { return GlobalList; }
336   static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
337     return &Module::GlobalList;
338   }
339   /// Get the Module's list of functions (constant).
340   const FunctionListType &getFunctionList() const     { return FunctionList; }
341   /// Get the Module's list of functions.
342   FunctionListType       &getFunctionList()           { return FunctionList; }
343   static iplist<Function> Module::*getSublistAccess(Function*) {
344     return &Module::FunctionList;
345   }
346   /// Get the Module's list of aliases (constant).
347   const AliasListType    &getAliasList() const        { return AliasList; }
348   /// Get the Module's list of aliases.
349   AliasListType          &getAliasList()              { return AliasList; }
350   static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
351     return &Module::AliasList;
352   }
353   /// Get the Module's list of named metadata (constant).
354   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
355   /// Get the Module's list of named metadata.
356   NamedMDListType  &getNamedMDList()                  { return NamedMDList; }
357   static iplist<NamedMDNode> Module::*getSublistAccess(NamedMDNode *) {
358     return &Module::NamedMDList;
359   }
360   /// Get the symbol table of global variable and function identifiers
361   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
362   /// Get the Module's symbol table of global variable and function identifiers.
363   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
364   /// Get the symbol table of types
365   const TypeSymbolTable  &getTypeSymbolTable() const  { return *TypeSymTab; }
366   /// Get the Module's symbol table of types
367   TypeSymbolTable        &getTypeSymbolTable()        { return *TypeSymTab; }
368
369 /// @}
370 /// @name Global Variable Iteration
371 /// @{
372 public:
373   /// Get an iterator to the first global variable
374   global_iterator       global_begin()       { return GlobalList.begin(); }
375   /// Get a constant iterator to the first global variable
376   const_global_iterator global_begin() const { return GlobalList.begin(); }
377   /// Get an iterator to the last global variable
378   global_iterator       global_end  ()       { return GlobalList.end(); }
379   /// Get a constant iterator to the last global variable
380   const_global_iterator global_end  () const { return GlobalList.end(); }
381   /// Determine if the list of globals is empty.
382   bool                  global_empty() const { return GlobalList.empty(); }
383
384 /// @}
385 /// @name Function Iteration
386 /// @{
387 public:
388   /// Get an iterator to the first function.
389   iterator                begin()       { return FunctionList.begin(); }
390   /// Get a constant iterator to the first function.
391   const_iterator          begin() const { return FunctionList.begin(); }
392   /// Get an iterator to the last function.
393   iterator                end  ()       { return FunctionList.end();   }
394   /// Get a constant iterator to the last function.
395   const_iterator          end  () const { return FunctionList.end();   }
396   /// Determine how many functions are in the Module's list of functions.
397   size_t                  size() const  { return FunctionList.size(); }
398   /// Determine if the list of functions is empty.
399   bool                    empty() const { return FunctionList.empty(); }
400
401 /// @}
402 /// @name Dependent Library Iteration
403 /// @{
404 public:
405   /// @brief Get a constant iterator to beginning of dependent library list.
406   inline lib_iterator lib_begin() const { return LibraryList.begin(); }
407   /// @brief Get a constant iterator to end of dependent library list.
408   inline lib_iterator lib_end()   const { return LibraryList.end();   }
409   /// @brief Returns the number of items in the list of libraries.
410   inline size_t       lib_size()  const { return LibraryList.size();  }
411   /// @brief Add a library to the list of dependent libraries
412   void addLibrary(const StringRef &Lib);
413   /// @brief Remove a library from the list of dependent libraries
414   void removeLibrary(const StringRef &Lib);
415   /// @brief Get all the libraries
416   inline const LibraryListType& getLibraries() const { return LibraryList; }
417
418 /// @}
419 /// @name Alias Iteration
420 /// @{
421 public:
422   /// Get an iterator to the first alias.
423   alias_iterator       alias_begin()            { return AliasList.begin(); }
424   /// Get a constant iterator to the first alias.
425   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
426   /// Get an iterator to the last alias.
427   alias_iterator       alias_end  ()            { return AliasList.end();   }
428   /// Get a constant iterator to the last alias.
429   const_alias_iterator alias_end  () const      { return AliasList.end();   }
430   /// Determine how many aliases are in the Module's list of aliases.
431   size_t               alias_size () const      { return AliasList.size();  }
432   /// Determine if the list of aliases is empty.
433   bool                 alias_empty() const      { return AliasList.empty(); }
434
435
436 /// @}
437 /// @name Named Metadata Iteration
438 /// @{
439 public:
440   /// Get an iterator to the first named metadata.
441   named_metadata_iterator       named_metadata_begin()            
442                                                 { return NamedMDList.begin(); }
443   /// Get a constant iterator to the first named metadata.
444   const_named_metadata_iterator named_metadata_begin() const      
445                                                 { return NamedMDList.begin(); }
446   /// Get an iterator to the last named metadata.
447   named_metadata_iterator       named_metadata_end  ()            
448                                                 { return NamedMDList.end();   }
449   /// Get a constant iterator to the last named metadata.
450   const_named_metadata_iterator named_metadata_end  () const      
451                                                 { return NamedMDList.end();   }
452   /// Determine how many NamedMDNodes are in the Module's list of named metadata.
453   size_t                        named_metadata_size () const      
454                                                 { return NamedMDList.size();  }
455   /// Determine if the list of named metadata is empty.
456   bool                          named_metadata_empty() const      
457                                                 { return NamedMDList.empty(); }
458
459
460 /// @}
461 /// @name Utility functions for printing and dumping Module objects
462 /// @{
463 public:
464   /// Print the module to an output stream with AssemblyAnnotationWriter.
465   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
466   void print(std::ostream &OS, AssemblyAnnotationWriter *AAW) const;
467   
468   /// Dump the module to stderr (for debugging).
469   void dump() const;
470   /// This function causes all the subinstructions to "let go" of all references
471   /// that they are maintaining.  This allows one to 'delete' a whole class at
472   /// a time, even though there may be circular references... first all
473   /// references are dropped, and all use counts go to zero.  Then everything
474   /// is delete'd for real.  Note that no operations are valid on an object
475   /// that has "dropped all references", except operator delete.
476   void dropAllReferences();
477 /// @}
478 };
479
480 /// An iostream inserter for modules.
481 inline std::ostream &operator<<(std::ostream &O, const Module &M) {
482   M.print(O, 0);
483   return O;
484 }
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