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