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