1 //===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Module.h This file contains the declarations for the Module class.
13 //===----------------------------------------------------------------------===//
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"
32 template<typename T> struct DenseMapInfo;
33 template<typename KeyT, typename ValueT,
34 typename KeyInfoT, typename ValueInfoT> class DenseMap;
36 template<> struct ilist_traits<Function>
37 : public SymbolTableListTraits<Function, Module> {
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);
44 static void destroySentinel(Function*) {}
46 Function *provideInitialHead() const { return createSentinel(); }
47 Function *ensureHead(Function*) const { return createSentinel(); }
48 static void noteHead(Function*, Function*) {}
51 mutable ilist_node<Function> Sentinel;
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);
60 static void destroySentinel(GlobalVariable*) {}
62 GlobalVariable *provideInitialHead() const { return createSentinel(); }
63 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
64 static void noteHead(GlobalVariable*, GlobalVariable*) {}
66 mutable ilist_node<GlobalVariable> Sentinel;
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);
75 static void destroySentinel(GlobalAlias*) {}
77 GlobalAlias *provideInitialHead() const { return createSentinel(); }
78 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
79 static void noteHead(GlobalAlias*, GlobalAlias*) {}
81 mutable ilist_node<GlobalAlias> Sentinel;
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
88 NamedMDNode *createSentinel() const {
89 return static_cast<NamedMDNode*>(&Sentinel);
91 static void destroySentinel(NamedMDNode*) {}
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 *) {}
99 mutable ilist_node<NamedMDNode> Sentinel;
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.
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.
114 /// @name Types And Enumerations
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;
126 /// The type for the list of dependent libraries.
127 typedef std::vector<std::string> LibraryListType;
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;
134 /// The Function iterators.
135 typedef FunctionListType::iterator iterator;
136 /// The Function constant iterator
137 typedef FunctionListType::const_iterator const_iterator;
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;
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;
151 /// An enumeration for describing the endianess of the target machine.
152 enum Endianness { AnyEndianness, LittleEndian, BigEndian };
154 /// An enumeration for describing the size of a pointer on the target machine.
155 enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
157 /// An enumeration for the supported behaviors of module flags. The following
158 /// module flags behavior values are supported:
163 /// Emits an error if two values disagree.
166 /// Emits a warning if two values disagree.
169 /// Emits an error when the specified value is not present
170 /// or doesn't have the specified value. It is an error for
171 /// two (or more) llvm.module.flags with the same ID to have
172 /// the Require behavior but different values. There may be
173 /// multiple Require flags per ID.
176 /// Uses the specified value if the two values disagree. It
177 /// is an error for two (or more) llvm.module.flags with the
178 /// same ID to have the Override behavior but different
180 enum ModAttrBehavior { Error = 1, Warning = 2, Require = 3, Override = 4 };
183 /// @name Member Variables
186 LLVMContext &Context; ///< The LLVMContext from which types and
187 ///< constants are allocated.
188 GlobalListType GlobalList; ///< The Global Variables in the module
189 FunctionListType FunctionList; ///< The Functions in the module
190 AliasListType AliasList; ///< The Aliases in the module
191 LibraryListType LibraryList; ///< The Libraries needed by the module
192 NamedMDListType NamedMDList; ///< The named metadata in the module
193 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
194 ValueSymbolTable *ValSymTab; ///< Symbol table for values
195 OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
196 std::string ModuleID; ///< Human readable identifier for the module
197 std::string TargetTriple; ///< Platform target triple Module compiled on
198 std::string DataLayout; ///< Target data description
199 void *NamedMDSymTab; ///< NamedMDNode names.
201 friend class Constant;
204 /// @name Constructors
207 /// The Module constructor. Note that there is no default constructor. You
208 /// must provide a name for the module upon construction.
209 explicit Module(StringRef ModuleID, LLVMContext& C);
210 /// The module destructor. This will dropAllReferences.
214 /// @name Module Level Accessors
217 /// Get the module identifier which is, essentially, the name of the module.
218 /// @returns the module identifier as a string
219 const std::string &getModuleIdentifier() const { return ModuleID; }
221 /// Get the data layout string for the module's target platform. This encodes
222 /// the type sizes and alignments expected by this module.
223 /// @returns the data layout as a string
224 const std::string &getDataLayout() const { return DataLayout; }
226 /// Get the target triple which is a string describing the target host.
227 /// @returns a string containing the target triple.
228 const std::string &getTargetTriple() const { return TargetTriple; }
230 /// Get the target endian information.
231 /// @returns Endianess - an enumeration for the endianess of the target
232 Endianness getEndianness() const;
234 /// Get the target pointer size.
235 /// @returns PointerSize - an enumeration for the size of the target's pointer
236 PointerSize getPointerSize() const;
238 /// Get the global data context.
239 /// @returns LLVMContext - a container for LLVM's global information
240 LLVMContext &getContext() const { return Context; }
242 /// Get any module-scope inline assembly blocks.
243 /// @returns a string containing the module-scope inline assembly blocks.
244 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
247 /// @name Module Level Mutators
250 /// Set the module identifier.
251 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
253 /// Set the data layout
254 void setDataLayout(StringRef DL) { DataLayout = DL; }
256 /// Set the target triple.
257 void setTargetTriple(StringRef T) { TargetTriple = T; }
259 /// Set the module-scope inline assembly blocks.
260 void setModuleInlineAsm(StringRef Asm) {
261 GlobalScopeAsm = Asm;
262 if (!GlobalScopeAsm.empty() &&
263 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
264 GlobalScopeAsm += '\n';
267 /// Append to the module-scope inline assembly blocks, automatically inserting
268 /// a separating newline if necessary.
269 void appendModuleInlineAsm(StringRef Asm) {
270 GlobalScopeAsm += Asm;
271 if (!GlobalScopeAsm.empty() &&
272 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
273 GlobalScopeAsm += '\n';
277 /// @name Generic Value Accessors
280 /// getNamedValue - Return the global value in the module with
281 /// the specified name, of arbitrary type. This method returns null
282 /// if a global with the specified name is not found.
283 GlobalValue *getNamedValue(StringRef Name) const;
285 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
286 /// This ID is uniqued across modules in the current LLVMContext.
287 unsigned getMDKindID(StringRef Name) const;
289 /// getMDKindNames - Populate client supplied SmallVector with the name for
290 /// custom metadata IDs registered in this LLVMContext.
291 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
294 typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*>,
295 DenseMapInfo<unsigned> > NumeredTypesMapTy;
297 /// findUsedStructTypes - Walk the entire module and find all of the
298 /// struct types that are in use, returning them in a vector.
299 void findUsedStructTypes(std::vector<StructType*> &StructTypes) const;
301 /// getTypeByName - Return the type with the specified name, or null if there
302 /// is none by that name.
303 StructType *getTypeByName(StringRef Name) const;
306 /// @name Function Accessors
309 /// getOrInsertFunction - Look up the specified function in the module symbol
310 /// table. Four possibilities:
311 /// 1. If it does not exist, add a prototype for the function and return it.
312 /// 2. If it exists, and has a local linkage, the existing function is
313 /// renamed and a new one is inserted.
314 /// 3. Otherwise, if the existing function has the correct prototype, return
315 /// the existing function.
316 /// 4. Finally, the function exists but has the wrong prototype: return the
317 /// function with a constantexpr cast to the right prototype.
318 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
319 AttrListPtr AttributeList);
321 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
323 /// getOrInsertFunction - Look up the specified function in the module symbol
324 /// table. If it does not exist, add a prototype for the function and return
325 /// it. This function guarantees to return a constant of pointer to the
326 /// specified function type or a ConstantExpr BitCast of that type if the
327 /// named function has a different type. This version of the method takes a
328 /// null terminated list of function arguments, which makes it easier for
330 Constant *getOrInsertFunction(StringRef Name,
331 AttrListPtr AttributeList,
332 Type *RetTy, ...) END_WITH_NULL;
334 /// getOrInsertFunction - Same as above, but without the attributes.
335 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
338 Constant *getOrInsertTargetIntrinsic(StringRef Name,
340 AttrListPtr AttributeList);
342 /// getFunction - Look up the specified function in the module symbol table.
343 /// If it does not exist, return null.
344 Function *getFunction(StringRef Name) const;
347 /// @name Global Variable Accessors
350 /// getGlobalVariable - Look up the specified global variable in the module
351 /// symbol table. If it does not exist, return null. If AllowInternal is set
352 /// to true, this function will return types that have InternalLinkage. By
353 /// default, these types are not returned.
354 GlobalVariable *getGlobalVariable(StringRef Name,
355 bool AllowInternal = false) const;
357 /// getNamedGlobal - Return the global variable in the module with the
358 /// specified name, of arbitrary type. This method returns null if a global
359 /// with the specified name is not found.
360 GlobalVariable *getNamedGlobal(StringRef Name) const {
361 return getGlobalVariable(Name, true);
364 /// getOrInsertGlobal - Look up the specified global in the module symbol
366 /// 1. If it does not exist, add a declaration of the global and return it.
367 /// 2. Else, the global exists but has the wrong type: return the function
368 /// with a constantexpr cast to the right type.
369 /// 3. Finally, if the existing global is the correct declaration, return
370 /// the existing global.
371 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
374 /// @name Global Alias Accessors
377 /// getNamedAlias - Return the global alias in the module with the
378 /// specified name, of arbitrary type. This method returns null if a global
379 /// with the specified name is not found.
380 GlobalAlias *getNamedAlias(StringRef Name) const;
383 /// @name Named Metadata Accessors
386 /// getNamedMetadata - Return the NamedMDNode in the module with the
387 /// specified name. This method returns null if a NamedMDNode with the
388 /// specified name is not found.
389 NamedMDNode *getNamedMetadata(const Twine &Name) const;
391 /// getOrInsertNamedMetadata - Return the named MDNode in the module
392 /// with the specified name. This method returns a new NamedMDNode if a
393 /// NamedMDNode with the specified name is not found.
394 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
396 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
398 void eraseNamedMetadata(NamedMDNode *NMD);
401 /// @name Module Flags Accessors
404 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
405 /// represents module-level flags. This method returns null if there are no
406 /// module-level flags.
407 NamedMDNode *getModuleFlagsMetadata() const;
409 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
410 /// that represents module-level flags. If module-level flags aren't found,
411 /// it creates the named metadata that contains them.
412 NamedMDNode *getOrInsertModuleFlagsMetadata();
414 /// addModuleFlag - Add a module-level flag to the module-level flags
415 /// metadata. It will create the module-level flags named metadata if it
416 /// doesn't already exist.
417 void addModuleFlag(ModAttrBehavior Behavior, StringRef Key, Value *Val);
418 void addModuleFlag(ModAttrBehavior Behavior, StringRef Key, uint32_t Val);
419 void addModuleFlag(MDNode *Node);
422 /// @name Materialization
425 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
426 /// yet have a Materializer. To reset the materializer for a module that
427 /// already has one, call MaterializeAllPermanently first. Destroying this
428 /// module will destroy its materializer without materializing any more
429 /// GlobalValues. Without destroying the Module, there is no way to detach or
430 /// destroy a materializer without materializing all the GVs it controls, to
431 /// avoid leaving orphan unmaterialized GVs.
432 void setMaterializer(GVMaterializer *GVM);
433 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
434 GVMaterializer *getMaterializer() const { return Materializer.get(); }
436 /// isMaterializable - True if the definition of GV has yet to be materialized
437 /// from the GVMaterializer.
438 bool isMaterializable(const GlobalValue *GV) const;
439 /// isDematerializable - Returns true if this GV was loaded from this Module's
440 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
441 bool isDematerializable(const GlobalValue *GV) const;
443 /// Materialize - Make sure the GlobalValue is fully read. If the module is
444 /// corrupt, this returns true and fills in the optional string with
445 /// information about the problem. If successful, this returns false.
446 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
447 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
448 /// supports it, release the memory for the function, and set it up to be
449 /// materialized lazily. If !isDematerializable(), this method is a noop.
450 void Dematerialize(GlobalValue *GV);
452 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
453 /// If the module is corrupt, this returns true and fills in the optional
454 /// string with information about the problem. If successful, this returns
456 bool MaterializeAll(std::string *ErrInfo = 0);
458 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
459 /// fully read and clear the Materializer. If the module is corrupt, this
460 /// returns true, fills in the optional string with information about the
461 /// problem, and DOES NOT clear the old Materializer. If successful, this
463 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
466 /// @name Direct access to the globals list, functions list, and symbol table
469 /// Get the Module's list of global variables (constant).
470 const GlobalListType &getGlobalList() const { return GlobalList; }
471 /// Get the Module's list of global variables.
472 GlobalListType &getGlobalList() { return GlobalList; }
473 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
474 return &Module::GlobalList;
476 /// Get the Module's list of functions (constant).
477 const FunctionListType &getFunctionList() const { return FunctionList; }
478 /// Get the Module's list of functions.
479 FunctionListType &getFunctionList() { return FunctionList; }
480 static iplist<Function> Module::*getSublistAccess(Function*) {
481 return &Module::FunctionList;
483 /// Get the Module's list of aliases (constant).
484 const AliasListType &getAliasList() const { return AliasList; }
485 /// Get the Module's list of aliases.
486 AliasListType &getAliasList() { return AliasList; }
487 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
488 return &Module::AliasList;
490 /// Get the symbol table of global variable and function identifiers
491 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
492 /// Get the Module's symbol table of global variable and function identifiers.
493 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
496 /// @name Global Variable Iteration
499 global_iterator global_begin() { return GlobalList.begin(); }
500 const_global_iterator global_begin() const { return GlobalList.begin(); }
501 global_iterator global_end () { return GlobalList.end(); }
502 const_global_iterator global_end () const { return GlobalList.end(); }
503 bool global_empty() const { return GlobalList.empty(); }
506 /// @name Function Iteration
509 iterator begin() { return FunctionList.begin(); }
510 const_iterator begin() const { return FunctionList.begin(); }
511 iterator end () { return FunctionList.end(); }
512 const_iterator end () const { return FunctionList.end(); }
513 size_t size() const { return FunctionList.size(); }
514 bool empty() const { return FunctionList.empty(); }
517 /// @name Dependent Library Iteration
520 /// @brief Get a constant iterator to beginning of dependent library list.
521 inline lib_iterator lib_begin() const { return LibraryList.begin(); }
522 /// @brief Get a constant iterator to end of dependent library list.
523 inline lib_iterator lib_end() const { return LibraryList.end(); }
524 /// @brief Returns the number of items in the list of libraries.
525 inline size_t lib_size() const { return LibraryList.size(); }
526 /// @brief Add a library to the list of dependent libraries
527 void addLibrary(StringRef Lib);
528 /// @brief Remove a library from the list of dependent libraries
529 void removeLibrary(StringRef Lib);
530 /// @brief Get all the libraries
531 inline const LibraryListType& getLibraries() const { return LibraryList; }
534 /// @name Alias Iteration
537 alias_iterator alias_begin() { return AliasList.begin(); }
538 const_alias_iterator alias_begin() const { return AliasList.begin(); }
539 alias_iterator alias_end () { return AliasList.end(); }
540 const_alias_iterator alias_end () const { return AliasList.end(); }
541 size_t alias_size () const { return AliasList.size(); }
542 bool alias_empty() const { return AliasList.empty(); }
546 /// @name Named Metadata Iteration
549 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
550 const_named_metadata_iterator named_metadata_begin() const {
551 return NamedMDList.begin();
554 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
555 const_named_metadata_iterator named_metadata_end() const {
556 return NamedMDList.end();
559 size_t named_metadata_size() const { return NamedMDList.size(); }
560 bool named_metadata_empty() const { return NamedMDList.empty(); }
564 /// @name Utility functions for printing and dumping Module objects
567 /// Print the module to an output stream with an optional
568 /// AssemblyAnnotationWriter.
569 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
571 /// Dump the module to stderr (for debugging).
574 /// This function causes all the subinstructions to "let go" of all references
575 /// that they are maintaining. This allows one to 'delete' a whole class at
576 /// a time, even though there may be circular references... first all
577 /// references are dropped, and all use counts go to zero. Then everything
578 /// is delete'd for real. Note that no operations are valid on an object
579 /// that has "dropped all references", except operator delete.
580 void dropAllReferences();
584 /// An raw_ostream inserter for modules.
585 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
590 } // End llvm namespace