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, typename KeyInfoT> class DenseMap;
35 template<> struct ilist_traits<Function>
36 : public SymbolTableListTraits<Function, Module> {
38 // createSentinel is used to get hold of the node that marks the end of the
39 // list... (same trick used here as in ilist_traits<Instruction>)
40 Function *createSentinel() const {
41 return static_cast<Function*>(&Sentinel);
43 static void destroySentinel(Function*) {}
45 Function *provideInitialHead() const { return createSentinel(); }
46 Function *ensureHead(Function*) const { return createSentinel(); }
47 static void noteHead(Function*, Function*) {}
50 mutable ilist_node<Function> Sentinel;
53 template<> struct ilist_traits<GlobalVariable>
54 : public SymbolTableListTraits<GlobalVariable, Module> {
55 // createSentinel is used to create a node that marks the end of the list.
56 GlobalVariable *createSentinel() const {
57 return static_cast<GlobalVariable*>(&Sentinel);
59 static void destroySentinel(GlobalVariable*) {}
61 GlobalVariable *provideInitialHead() const { return createSentinel(); }
62 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
63 static void noteHead(GlobalVariable*, GlobalVariable*) {}
65 mutable ilist_node<GlobalVariable> Sentinel;
68 template<> struct ilist_traits<GlobalAlias>
69 : public SymbolTableListTraits<GlobalAlias, Module> {
70 // createSentinel is used to create a node that marks the end of the list.
71 GlobalAlias *createSentinel() const {
72 return static_cast<GlobalAlias*>(&Sentinel);
74 static void destroySentinel(GlobalAlias*) {}
76 GlobalAlias *provideInitialHead() const { return createSentinel(); }
77 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
78 static void noteHead(GlobalAlias*, GlobalAlias*) {}
80 mutable ilist_node<GlobalAlias> Sentinel;
83 template<> struct ilist_traits<NamedMDNode>
84 : public ilist_default_traits<NamedMDNode> {
85 // createSentinel is used to get hold of a node that marks the end of
87 NamedMDNode *createSentinel() const {
88 return static_cast<NamedMDNode*>(&Sentinel);
90 static void destroySentinel(NamedMDNode*) {}
92 NamedMDNode *provideInitialHead() const { return createSentinel(); }
93 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
94 static void noteHead(NamedMDNode*, NamedMDNode*) {}
95 void addNodeToList(NamedMDNode *) {}
96 void removeNodeFromList(NamedMDNode *) {}
98 mutable ilist_node<NamedMDNode> Sentinel;
101 /// A Module instance is used to store all the information related to an
102 /// LLVM module. Modules are the top level container of all other LLVM
103 /// Intermediate Representation (IR) objects. Each module directly contains a
104 /// list of globals variables, a list of functions, a list of libraries (or
105 /// other modules) this module depends on, a symbol table, and various data
106 /// about the target's characteristics.
108 /// A module maintains a GlobalValRefMap object that is used to hold all
109 /// constant references to global variables in the module. When a global
110 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
111 /// @brief The main container class for the LLVM Intermediate Representation.
113 /// @name Types And Enumerations
116 /// The type for the list of global variables.
117 typedef iplist<GlobalVariable> GlobalListType;
118 /// The type for the list of functions.
119 typedef iplist<Function> FunctionListType;
120 /// The type for the list of aliases.
121 typedef iplist<GlobalAlias> AliasListType;
122 /// The type for the list of named metadata.
123 typedef ilist<NamedMDNode> NamedMDListType;
125 /// The type for the list of dependent libraries.
126 typedef std::vector<std::string> LibraryListType;
128 /// The Global Variable iterator.
129 typedef GlobalListType::iterator global_iterator;
130 /// The Global Variable constant iterator.
131 typedef GlobalListType::const_iterator const_global_iterator;
133 /// The Function iterators.
134 typedef FunctionListType::iterator iterator;
135 /// The Function constant iterator
136 typedef FunctionListType::const_iterator const_iterator;
138 /// The Global Alias iterators.
139 typedef AliasListType::iterator alias_iterator;
140 /// The Global Alias constant iterator
141 typedef AliasListType::const_iterator const_alias_iterator;
143 /// The named metadata iterators.
144 typedef NamedMDListType::iterator named_metadata_iterator;
145 /// The named metadata constant interators.
146 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
147 /// The Library list iterator.
148 typedef LibraryListType::const_iterator lib_iterator;
150 /// An enumeration for describing the endianess of the target machine.
151 enum Endianness { AnyEndianness, LittleEndian, BigEndian };
153 /// An enumeration for describing the size of a pointer on the target machine.
154 enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
156 /// An enumeration for the supported behaviors of module flags. The following
157 /// module flags behavior values are supported:
162 /// Emits an error if two values disagree.
165 /// Emits a warning if two values disagree.
168 /// Emits an error when the specified value is not present
169 /// or doesn't have the specified value. It is an error for
170 /// two (or more) llvm.module.flags with the same ID to have
171 /// the Require behavior but different values. There may be
172 /// multiple Require flags per ID.
175 /// Uses the specified value if the two values disagree. It
176 /// is an error for two (or more) llvm.module.flags with the
177 /// same ID to have the Override behavior but different
179 enum ModFlagBehavior { Error = 1, Warning = 2, Require = 3, Override = 4 };
181 struct ModuleFlagEntry {
182 ModFlagBehavior Behavior;
185 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
186 : Behavior(B), Key(K), Val(V) {}
190 /// @name Member Variables
193 LLVMContext &Context; ///< The LLVMContext from which types and
194 ///< constants are allocated.
195 GlobalListType GlobalList; ///< The Global Variables in the module
196 FunctionListType FunctionList; ///< The Functions in the module
197 AliasListType AliasList; ///< The Aliases in the module
198 LibraryListType LibraryList; ///< The Libraries needed by the module
199 NamedMDListType NamedMDList; ///< The named metadata in the module
200 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
201 ValueSymbolTable *ValSymTab; ///< Symbol table for values
202 OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
203 std::string ModuleID; ///< Human readable identifier for the module
204 std::string TargetTriple; ///< Platform target triple Module compiled on
205 std::string DataLayout; ///< Target data description
206 void *NamedMDSymTab; ///< NamedMDNode names.
208 friend class Constant;
211 /// @name Constructors
214 /// The Module constructor. Note that there is no default constructor. You
215 /// must provide a name for the module upon construction.
216 explicit Module(StringRef ModuleID, LLVMContext& C);
217 /// The module destructor. This will dropAllReferences.
221 /// @name Module Level Accessors
224 /// Get the module identifier which is, essentially, the name of the module.
225 /// @returns the module identifier as a string
226 const std::string &getModuleIdentifier() const { return ModuleID; }
228 /// Get the data layout string for the module's target platform. This encodes
229 /// the type sizes and alignments expected by this module.
230 /// @returns the data layout as a string
231 const std::string &getDataLayout() const { return DataLayout; }
233 /// Get the target triple which is a string describing the target host.
234 /// @returns a string containing the target triple.
235 const std::string &getTargetTriple() const { return TargetTriple; }
237 /// Get the target endian information.
238 /// @returns Endianess - an enumeration for the endianess of the target
239 Endianness getEndianness() const;
241 /// Get the target pointer size.
242 /// @returns PointerSize - an enumeration for the size of the target's pointer
243 PointerSize getPointerSize() const;
245 /// Get the global data context.
246 /// @returns LLVMContext - a container for LLVM's global information
247 LLVMContext &getContext() const { return Context; }
249 /// Get any module-scope inline assembly blocks.
250 /// @returns a string containing the module-scope inline assembly blocks.
251 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
254 /// @name Module Level Mutators
257 /// Set the module identifier.
258 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
260 /// Set the data layout
261 void setDataLayout(StringRef DL) { DataLayout = DL; }
263 /// Set the target triple.
264 void setTargetTriple(StringRef T) { TargetTriple = T; }
266 /// Set the module-scope inline assembly blocks.
267 void setModuleInlineAsm(StringRef Asm) {
268 GlobalScopeAsm = Asm;
269 if (!GlobalScopeAsm.empty() &&
270 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
271 GlobalScopeAsm += '\n';
274 /// Append to the module-scope inline assembly blocks, automatically inserting
275 /// a separating newline if necessary.
276 void appendModuleInlineAsm(StringRef Asm) {
277 GlobalScopeAsm += Asm;
278 if (!GlobalScopeAsm.empty() &&
279 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
280 GlobalScopeAsm += '\n';
284 /// @name Generic Value Accessors
287 /// getNamedValue - Return the global value in the module with
288 /// the specified name, of arbitrary type. This method returns null
289 /// if a global with the specified name is not found.
290 GlobalValue *getNamedValue(StringRef Name) const;
292 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
293 /// This ID is uniqued across modules in the current LLVMContext.
294 unsigned getMDKindID(StringRef Name) const;
296 /// getMDKindNames - Populate client supplied SmallVector with the name for
297 /// custom metadata IDs registered in this LLVMContext.
298 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
301 typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
304 /// getTypeByName - Return the type with the specified name, or null if there
305 /// is none by that name.
306 StructType *getTypeByName(StringRef Name) const;
309 /// @name Function Accessors
312 /// getOrInsertFunction - Look up the specified function in the module symbol
313 /// table. Four possibilities:
314 /// 1. If it does not exist, add a prototype for the function and return it.
315 /// 2. If it exists, and has a local linkage, the existing function is
316 /// renamed and a new one is inserted.
317 /// 3. Otherwise, if the existing function has the correct prototype, return
318 /// the existing function.
319 /// 4. Finally, the function exists but has the wrong prototype: return the
320 /// function with a constantexpr cast to the right prototype.
321 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
322 AttrListPtr AttributeList);
324 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
326 /// getOrInsertFunction - Look up the specified function in the module symbol
327 /// table. If it does not exist, add a prototype for the function and return
328 /// it. This function guarantees to return a constant of pointer to the
329 /// specified function type or a ConstantExpr BitCast of that type if the
330 /// named function has a different type. This version of the method takes a
331 /// null terminated list of function arguments, which makes it easier for
333 Constant *getOrInsertFunction(StringRef Name,
334 AttrListPtr AttributeList,
335 Type *RetTy, ...) END_WITH_NULL;
337 /// getOrInsertFunction - Same as above, but without the attributes.
338 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
341 Constant *getOrInsertTargetIntrinsic(StringRef Name,
343 AttrListPtr AttributeList);
345 /// getFunction - Look up the specified function in the module symbol table.
346 /// If it does not exist, return null.
347 Function *getFunction(StringRef Name) const;
350 /// @name Global Variable Accessors
353 /// getGlobalVariable - Look up the specified global variable in the module
354 /// symbol table. If it does not exist, return null. If AllowInternal is set
355 /// to true, this function will return types that have InternalLinkage. By
356 /// default, these types are not returned.
357 GlobalVariable *getGlobalVariable(StringRef Name,
358 bool AllowInternal = false) const;
360 /// getNamedGlobal - Return the global variable in the module with the
361 /// specified name, of arbitrary type. This method returns null if a global
362 /// with the specified name is not found.
363 GlobalVariable *getNamedGlobal(StringRef Name) const {
364 return getGlobalVariable(Name, true);
367 /// getOrInsertGlobal - Look up the specified global in the module symbol
369 /// 1. If it does not exist, add a declaration of the global and return it.
370 /// 2. Else, the global exists but has the wrong type: return the function
371 /// with a constantexpr cast to the right type.
372 /// 3. Finally, if the existing global is the correct declaration, return
373 /// the existing global.
374 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
377 /// @name Global Alias Accessors
380 /// getNamedAlias - Return the global alias in the module with the
381 /// specified name, of arbitrary type. This method returns null if a global
382 /// with the specified name is not found.
383 GlobalAlias *getNamedAlias(StringRef Name) const;
386 /// @name Named Metadata Accessors
389 /// getNamedMetadata - Return the NamedMDNode in the module with the
390 /// specified name. This method returns null if a NamedMDNode with the
391 /// specified name is not found.
392 NamedMDNode *getNamedMetadata(const Twine &Name) const;
394 /// getOrInsertNamedMetadata - Return the named MDNode in the module
395 /// with the specified name. This method returns a new NamedMDNode if a
396 /// NamedMDNode with the specified name is not found.
397 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
399 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
401 void eraseNamedMetadata(NamedMDNode *NMD);
404 /// @name Module Flags Accessors
407 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
408 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
410 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
411 /// represents module-level flags. This method returns null if there are no
412 /// module-level flags.
413 NamedMDNode *getModuleFlagsMetadata() const;
415 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
416 /// that represents module-level flags. If module-level flags aren't found,
417 /// it creates the named metadata that contains them.
418 NamedMDNode *getOrInsertModuleFlagsMetadata();
420 /// addModuleFlag - Add a module-level flag to the module-level flags
421 /// metadata. It will create the module-level flags named metadata if it
422 /// doesn't already exist.
423 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
424 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
425 void addModuleFlag(MDNode *Node);
428 /// @name Materialization
431 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
432 /// yet have a Materializer. To reset the materializer for a module that
433 /// already has one, call MaterializeAllPermanently first. Destroying this
434 /// module will destroy its materializer without materializing any more
435 /// GlobalValues. Without destroying the Module, there is no way to detach or
436 /// destroy a materializer without materializing all the GVs it controls, to
437 /// avoid leaving orphan unmaterialized GVs.
438 void setMaterializer(GVMaterializer *GVM);
439 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
440 GVMaterializer *getMaterializer() const { return Materializer.get(); }
442 /// isMaterializable - True if the definition of GV has yet to be materialized
443 /// from the GVMaterializer.
444 bool isMaterializable(const GlobalValue *GV) const;
445 /// isDematerializable - Returns true if this GV was loaded from this Module's
446 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
447 bool isDematerializable(const GlobalValue *GV) const;
449 /// Materialize - Make sure the GlobalValue is fully read. If the module is
450 /// corrupt, this returns true and fills in the optional string with
451 /// information about the problem. If successful, this returns false.
452 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
453 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
454 /// supports it, release the memory for the function, and set it up to be
455 /// materialized lazily. If !isDematerializable(), this method is a noop.
456 void Dematerialize(GlobalValue *GV);
458 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
459 /// If the module is corrupt, this returns true and fills in the optional
460 /// string with information about the problem. If successful, this returns
462 bool MaterializeAll(std::string *ErrInfo = 0);
464 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
465 /// fully read and clear the Materializer. If the module is corrupt, this
466 /// returns true, fills in the optional string with information about the
467 /// problem, and DOES NOT clear the old Materializer. If successful, this
469 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
472 /// @name Direct access to the globals list, functions list, and symbol table
475 /// Get the Module's list of global variables (constant).
476 const GlobalListType &getGlobalList() const { return GlobalList; }
477 /// Get the Module's list of global variables.
478 GlobalListType &getGlobalList() { return GlobalList; }
479 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
480 return &Module::GlobalList;
482 /// Get the Module's list of functions (constant).
483 const FunctionListType &getFunctionList() const { return FunctionList; }
484 /// Get the Module's list of functions.
485 FunctionListType &getFunctionList() { return FunctionList; }
486 static iplist<Function> Module::*getSublistAccess(Function*) {
487 return &Module::FunctionList;
489 /// Get the Module's list of aliases (constant).
490 const AliasListType &getAliasList() const { return AliasList; }
491 /// Get the Module's list of aliases.
492 AliasListType &getAliasList() { return AliasList; }
493 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
494 return &Module::AliasList;
496 /// Get the Module's list of named metadata (constant).
497 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
498 /// Get the Module's list of named metadata.
499 NamedMDListType &getNamedMDList() { return NamedMDList; }
500 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
501 return &Module::NamedMDList;
503 /// Get the symbol table of global variable and function identifiers
504 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
505 /// Get the Module's symbol table of global variable and function identifiers.
506 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
509 /// @name Global Variable Iteration
512 global_iterator global_begin() { return GlobalList.begin(); }
513 const_global_iterator global_begin() const { return GlobalList.begin(); }
514 global_iterator global_end () { return GlobalList.end(); }
515 const_global_iterator global_end () const { return GlobalList.end(); }
516 bool global_empty() const { return GlobalList.empty(); }
519 /// @name Function Iteration
522 iterator begin() { return FunctionList.begin(); }
523 const_iterator begin() const { return FunctionList.begin(); }
524 iterator end () { return FunctionList.end(); }
525 const_iterator end () const { return FunctionList.end(); }
526 size_t size() const { return FunctionList.size(); }
527 bool empty() const { return FunctionList.empty(); }
530 /// @name Dependent Library Iteration
533 /// @brief Get a constant iterator to beginning of dependent library list.
534 inline lib_iterator lib_begin() const { return LibraryList.begin(); }
535 /// @brief Get a constant iterator to end of dependent library list.
536 inline lib_iterator lib_end() const { return LibraryList.end(); }
537 /// @brief Returns the number of items in the list of libraries.
538 inline size_t lib_size() const { return LibraryList.size(); }
539 /// @brief Add a library to the list of dependent libraries
540 void addLibrary(StringRef Lib);
541 /// @brief Remove a library from the list of dependent libraries
542 void removeLibrary(StringRef Lib);
543 /// @brief Get all the libraries
544 inline const LibraryListType& getLibraries() const { return LibraryList; }
547 /// @name Alias Iteration
550 alias_iterator alias_begin() { return AliasList.begin(); }
551 const_alias_iterator alias_begin() const { return AliasList.begin(); }
552 alias_iterator alias_end () { return AliasList.end(); }
553 const_alias_iterator alias_end () const { return AliasList.end(); }
554 size_t alias_size () const { return AliasList.size(); }
555 bool alias_empty() const { return AliasList.empty(); }
559 /// @name Named Metadata Iteration
562 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
563 const_named_metadata_iterator named_metadata_begin() const {
564 return NamedMDList.begin();
567 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
568 const_named_metadata_iterator named_metadata_end() const {
569 return NamedMDList.end();
572 size_t named_metadata_size() const { return NamedMDList.size(); }
573 bool named_metadata_empty() const { return NamedMDList.empty(); }
577 /// @name Utility functions for printing and dumping Module objects
580 /// Print the module to an output stream with an optional
581 /// AssemblyAnnotationWriter.
582 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
584 /// Dump the module to stderr (for debugging).
587 /// This function causes all the subinstructions to "let go" of all references
588 /// that they are maintaining. This allows one to 'delete' a whole class at
589 /// a time, even though there may be circular references... first all
590 /// references are dropped, and all use counts go to zero. Then everything
591 /// is delete'd for real. Note that no operations are valid on an object
592 /// that has "dropped all references", except operator delete.
593 void dropAllReferences();
597 /// An raw_ostream inserter for modules.
598 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
603 } // End llvm namespace