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