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/ADT/OwningPtr.h"
19 #include "llvm/Function.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Support/DataTypes.h"
31 template<typename T> struct DenseMapInfo;
32 template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
34 template<> struct ilist_traits<Function>
35 : public SymbolTableListTraits<Function, Module> {
37 // createSentinel is used to get hold of the node that marks the end of the
38 // list... (same trick used here as in ilist_traits<Instruction>)
39 Function *createSentinel() const {
40 return static_cast<Function*>(&Sentinel);
42 static void destroySentinel(Function*) {}
44 Function *provideInitialHead() const { return createSentinel(); }
45 Function *ensureHead(Function*) const { return createSentinel(); }
46 static void noteHead(Function*, Function*) {}
49 mutable ilist_node<Function> Sentinel;
52 template<> struct ilist_traits<GlobalVariable>
53 : public SymbolTableListTraits<GlobalVariable, Module> {
54 // createSentinel is used to create a node that marks the end of the list.
55 GlobalVariable *createSentinel() const {
56 return static_cast<GlobalVariable*>(&Sentinel);
58 static void destroySentinel(GlobalVariable*) {}
60 GlobalVariable *provideInitialHead() const { return createSentinel(); }
61 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
62 static void noteHead(GlobalVariable*, GlobalVariable*) {}
64 mutable ilist_node<GlobalVariable> Sentinel;
67 template<> struct ilist_traits<GlobalAlias>
68 : public SymbolTableListTraits<GlobalAlias, Module> {
69 // createSentinel is used to create a node that marks the end of the list.
70 GlobalAlias *createSentinel() const {
71 return static_cast<GlobalAlias*>(&Sentinel);
73 static void destroySentinel(GlobalAlias*) {}
75 GlobalAlias *provideInitialHead() const { return createSentinel(); }
76 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
77 static void noteHead(GlobalAlias*, GlobalAlias*) {}
79 mutable ilist_node<GlobalAlias> Sentinel;
82 template<> struct ilist_traits<NamedMDNode>
83 : public ilist_default_traits<NamedMDNode> {
84 // createSentinel is used to get hold of a node that marks the end of
86 NamedMDNode *createSentinel() const {
87 return static_cast<NamedMDNode*>(&Sentinel);
89 static void destroySentinel(NamedMDNode*) {}
91 NamedMDNode *provideInitialHead() const { return createSentinel(); }
92 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
93 static void noteHead(NamedMDNode*, NamedMDNode*) {}
94 void addNodeToList(NamedMDNode *) {}
95 void removeNodeFromList(NamedMDNode *) {}
97 mutable ilist_node<NamedMDNode> Sentinel;
100 /// A Module instance is used to store all the information related to an
101 /// LLVM module. Modules are the top level container of all other LLVM
102 /// Intermediate Representation (IR) objects. Each module directly contains a
103 /// list of globals variables, a list of functions, a list of libraries (or
104 /// other modules) this module depends on, a symbol table, and various data
105 /// about the target's characteristics.
107 /// A module maintains a GlobalValRefMap object that is used to hold all
108 /// constant references to global variables in the module. When a global
109 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
110 /// @brief The main container class for the LLVM Intermediate Representation.
112 /// @name Types And Enumerations
115 /// The type for the list of global variables.
116 typedef iplist<GlobalVariable> GlobalListType;
117 /// The type for the list of functions.
118 typedef iplist<Function> FunctionListType;
119 /// The type for the list of aliases.
120 typedef iplist<GlobalAlias> AliasListType;
121 /// The type for the list of named metadata.
122 typedef ilist<NamedMDNode> NamedMDListType;
124 /// The Global Variable iterator.
125 typedef GlobalListType::iterator global_iterator;
126 /// The Global Variable constant iterator.
127 typedef GlobalListType::const_iterator const_global_iterator;
129 /// The Function iterators.
130 typedef FunctionListType::iterator iterator;
131 /// The Function constant iterator
132 typedef FunctionListType::const_iterator const_iterator;
134 /// The Global Alias iterators.
135 typedef AliasListType::iterator alias_iterator;
136 /// The Global Alias constant iterator
137 typedef AliasListType::const_iterator const_alias_iterator;
139 /// The named metadata iterators.
140 typedef NamedMDListType::iterator named_metadata_iterator;
141 /// The named metadata constant interators.
142 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
144 /// An enumeration for describing the endianess of the target machine.
145 enum Endianness { AnyEndianness, LittleEndian, BigEndian };
147 /// An enumeration for describing the size of a pointer on the target machine.
148 enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
150 /// An enumeration for the supported behaviors of module flags. The following
151 /// module flags behavior values are supported:
156 /// Emits an error if two values disagree.
159 /// Emits a warning if two values disagree.
162 /// Emits an error when the specified value is not present
163 /// or doesn't have the specified value. It is an error for
164 /// two (or more) llvm.module.flags with the same ID to have
165 /// the Require behavior but different values. There may be
166 /// multiple Require flags per ID.
169 /// Uses the specified value if the two values disagree. It
170 /// is an error for two (or more) llvm.module.flags with the
171 /// same ID to have the Override behavior but different
173 enum ModFlagBehavior { Error = 1, Warning = 2, Require = 3, Override = 4 };
175 struct ModuleFlagEntry {
176 ModFlagBehavior Behavior;
179 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
180 : Behavior(B), Key(K), Val(V) {}
184 /// @name Member Variables
187 LLVMContext &Context; ///< The LLVMContext from which types and
188 ///< constants are allocated.
189 GlobalListType GlobalList; ///< The Global Variables in the module
190 FunctionListType FunctionList; ///< The Functions in the module
191 AliasListType AliasList; ///< The Aliases in 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*> >
297 /// getTypeByName - Return the type with the specified name, or null if there
298 /// is none by that name.
299 StructType *getTypeByName(StringRef Name) const;
302 /// @name Function Accessors
305 /// getOrInsertFunction - Look up the specified function in the module symbol
306 /// table. Four possibilities:
307 /// 1. If it does not exist, add a prototype for the function and return it.
308 /// 2. If it exists, and has a local linkage, the existing function is
309 /// renamed and a new one is inserted.
310 /// 3. Otherwise, if the existing function has the correct prototype, return
311 /// the existing function.
312 /// 4. Finally, the function exists but has the wrong prototype: return the
313 /// function with a constantexpr cast to the right prototype.
314 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
315 AttributeSet AttributeList);
317 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
319 /// getOrInsertFunction - Look up the specified function in the module symbol
320 /// table. If it does not exist, add a prototype for the function and return
321 /// it. This function guarantees to return a constant of pointer to the
322 /// specified function type or a ConstantExpr BitCast of that type if the
323 /// named function has a different type. This version of the method takes a
324 /// null terminated list of function arguments, which makes it easier for
326 Constant *getOrInsertFunction(StringRef Name,
327 AttributeSet AttributeList,
328 Type *RetTy, ...) END_WITH_NULL;
330 /// getOrInsertFunction - Same as above, but without the attributes.
331 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
334 Constant *getOrInsertTargetIntrinsic(StringRef Name,
336 AttributeSet AttributeList);
338 /// getFunction - Look up the specified function in the module symbol table.
339 /// If it does not exist, return null.
340 Function *getFunction(StringRef Name) const;
343 /// @name Global Variable Accessors
346 /// getGlobalVariable - Look up the specified global variable in the module
347 /// symbol table. If it does not exist, return null. If AllowInternal is set
348 /// to true, this function will return types that have InternalLinkage. By
349 /// default, these types are not returned.
350 GlobalVariable *getGlobalVariable(StringRef Name,
351 bool AllowInternal = false) const;
353 /// getNamedGlobal - Return the global variable in the module with the
354 /// specified name, of arbitrary type. This method returns null if a global
355 /// with the specified name is not found.
356 GlobalVariable *getNamedGlobal(StringRef Name) const {
357 return getGlobalVariable(Name, true);
360 /// getOrInsertGlobal - Look up the specified global in the module symbol
362 /// 1. If it does not exist, add a declaration of the global and return it.
363 /// 2. Else, the global exists but has the wrong type: return the function
364 /// with a constantexpr cast to the right type.
365 /// 3. Finally, if the existing global is the correct declaration, return
366 /// the existing global.
367 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
370 /// @name Global Alias Accessors
373 /// getNamedAlias - Return the global alias in the module with the
374 /// specified name, of arbitrary type. This method returns null if a global
375 /// with the specified name is not found.
376 GlobalAlias *getNamedAlias(StringRef Name) const;
379 /// @name Named Metadata Accessors
382 /// getNamedMetadata - Return the NamedMDNode in the module with the
383 /// specified name. This method returns null if a NamedMDNode with the
384 /// specified name is not found.
385 NamedMDNode *getNamedMetadata(const Twine &Name) const;
387 /// getOrInsertNamedMetadata - Return the named MDNode in the module
388 /// with the specified name. This method returns a new NamedMDNode if a
389 /// NamedMDNode with the specified name is not found.
390 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
392 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
394 void eraseNamedMetadata(NamedMDNode *NMD);
397 /// @name Module Flags Accessors
400 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
401 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
403 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
404 /// represents module-level flags. This method returns null if there are no
405 /// module-level flags.
406 NamedMDNode *getModuleFlagsMetadata() const;
408 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
409 /// that represents module-level flags. If module-level flags aren't found,
410 /// it creates the named metadata that contains them.
411 NamedMDNode *getOrInsertModuleFlagsMetadata();
413 /// addModuleFlag - Add a module-level flag to the module-level flags
414 /// metadata. It will create the module-level flags named metadata if it
415 /// doesn't already exist.
416 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
417 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
418 void addModuleFlag(MDNode *Node);
421 /// @name Materialization
424 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
425 /// yet have a Materializer. To reset the materializer for a module that
426 /// already has one, call MaterializeAllPermanently first. Destroying this
427 /// module will destroy its materializer without materializing any more
428 /// GlobalValues. Without destroying the Module, there is no way to detach or
429 /// destroy a materializer without materializing all the GVs it controls, to
430 /// avoid leaving orphan unmaterialized GVs.
431 void setMaterializer(GVMaterializer *GVM);
432 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
433 GVMaterializer *getMaterializer() const { return Materializer.get(); }
435 /// isMaterializable - True if the definition of GV has yet to be materialized
436 /// from the GVMaterializer.
437 bool isMaterializable(const GlobalValue *GV) const;
438 /// isDematerializable - Returns true if this GV was loaded from this Module's
439 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
440 bool isDematerializable(const GlobalValue *GV) const;
442 /// Materialize - Make sure the GlobalValue is fully read. If the module is
443 /// corrupt, this returns true and fills in the optional string with
444 /// information about the problem. If successful, this returns false.
445 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
446 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
447 /// supports it, release the memory for the function, and set it up to be
448 /// materialized lazily. If !isDematerializable(), this method is a noop.
449 void Dematerialize(GlobalValue *GV);
451 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
452 /// If the module is corrupt, this returns true and fills in the optional
453 /// string with information about the problem. If successful, this returns
455 bool MaterializeAll(std::string *ErrInfo = 0);
457 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
458 /// fully read and clear the Materializer. If the module is corrupt, this
459 /// returns true, fills in the optional string with information about the
460 /// problem, and DOES NOT clear the old Materializer. If successful, this
462 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
465 /// @name Direct access to the globals list, functions list, and symbol table
468 /// Get the Module's list of global variables (constant).
469 const GlobalListType &getGlobalList() const { return GlobalList; }
470 /// Get the Module's list of global variables.
471 GlobalListType &getGlobalList() { return GlobalList; }
472 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
473 return &Module::GlobalList;
475 /// Get the Module's list of functions (constant).
476 const FunctionListType &getFunctionList() const { return FunctionList; }
477 /// Get the Module's list of functions.
478 FunctionListType &getFunctionList() { return FunctionList; }
479 static iplist<Function> Module::*getSublistAccess(Function*) {
480 return &Module::FunctionList;
482 /// Get the Module's list of aliases (constant).
483 const AliasListType &getAliasList() const { return AliasList; }
484 /// Get the Module's list of aliases.
485 AliasListType &getAliasList() { return AliasList; }
486 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
487 return &Module::AliasList;
489 /// Get the Module's list of named metadata (constant).
490 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
491 /// Get the Module's list of named metadata.
492 NamedMDListType &getNamedMDList() { return NamedMDList; }
493 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
494 return &Module::NamedMDList;
496 /// Get the symbol table of global variable and function identifiers
497 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
498 /// Get the Module's symbol table of global variable and function identifiers.
499 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
502 /// @name Global Variable Iteration
505 global_iterator global_begin() { return GlobalList.begin(); }
506 const_global_iterator global_begin() const { return GlobalList.begin(); }
507 global_iterator global_end () { return GlobalList.end(); }
508 const_global_iterator global_end () const { return GlobalList.end(); }
509 bool global_empty() const { return GlobalList.empty(); }
512 /// @name Function Iteration
515 iterator begin() { return FunctionList.begin(); }
516 const_iterator begin() const { return FunctionList.begin(); }
517 iterator end () { return FunctionList.end(); }
518 const_iterator end () const { return FunctionList.end(); }
519 size_t size() const { return FunctionList.size(); }
520 bool empty() const { return FunctionList.empty(); }
523 /// @name Alias Iteration
526 alias_iterator alias_begin() { return AliasList.begin(); }
527 const_alias_iterator alias_begin() const { return AliasList.begin(); }
528 alias_iterator alias_end () { return AliasList.end(); }
529 const_alias_iterator alias_end () const { return AliasList.end(); }
530 size_t alias_size () const { return AliasList.size(); }
531 bool alias_empty() const { return AliasList.empty(); }
535 /// @name Named Metadata Iteration
538 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
539 const_named_metadata_iterator named_metadata_begin() const {
540 return NamedMDList.begin();
543 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
544 const_named_metadata_iterator named_metadata_end() const {
545 return NamedMDList.end();
548 size_t named_metadata_size() const { return NamedMDList.size(); }
549 bool named_metadata_empty() const { return NamedMDList.empty(); }
553 /// @name Utility functions for printing and dumping Module objects
556 /// Print the module to an output stream with an optional
557 /// AssemblyAnnotationWriter.
558 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
560 /// Dump the module to stderr (for debugging).
563 /// This function causes all the subinstructions to "let go" of all references
564 /// that they are maintaining. This allows one to 'delete' a whole class at
565 /// a time, even though there may be circular references... first all
566 /// references are dropped, and all use counts go to zero. Then everything
567 /// is delete'd for real. Note that no operations are valid on an object
568 /// that has "dropped all references", except operator delete.
569 void dropAllReferences();
573 /// An raw_ostream inserter for modules.
574 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
579 } // End llvm namespace