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 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_MODULE_H
16 #define LLVM_IR_MODULE_H
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Metadata.h"
23 #include "llvm/Support/CBindingWrapping.h"
24 #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 Global Variable iterator.
126 typedef GlobalListType::iterator global_iterator;
127 /// The Global Variable constant iterator.
128 typedef GlobalListType::const_iterator const_global_iterator;
130 /// The Function iterators.
131 typedef FunctionListType::iterator iterator;
132 /// The Function constant iterator
133 typedef FunctionListType::const_iterator const_iterator;
135 /// The Global Alias iterators.
136 typedef AliasListType::iterator alias_iterator;
137 /// The Global Alias constant iterator
138 typedef AliasListType::const_iterator const_alias_iterator;
140 /// The named metadata iterators.
141 typedef NamedMDListType::iterator named_metadata_iterator;
142 /// The named metadata constant interators.
143 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
145 /// An enumeration for describing the endianess of the target machine.
146 enum Endianness { AnyEndianness, LittleEndian, BigEndian };
148 /// An enumeration for describing the size of a pointer on the target machine.
149 enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
151 /// This enumeration defines the supported behaviors of module flags.
152 enum ModFlagBehavior {
153 /// Emits an error if two values disagree, otherwise the resulting value is
154 /// that of the operands.
157 /// Emits a warning if two values disagree. The result value will be the
158 /// operand for the flag from the first module being linked.
161 /// Adds a requirement that another module flag be present and have a
162 /// specified value after linking is performed. The value must be a metadata
163 /// pair, where the first element of the pair is the ID of the module flag
164 /// to be restricted, and the second element of the pair is the value the
165 /// module flag should be restricted to. This behavior can be used to
166 /// restrict the allowable results (via triggering of an error) of linking
167 /// IDs with the **Override** behavior.
170 /// Uses the specified value, regardless of the behavior or value of the
171 /// other module. If both modules specify **Override**, but the values
172 /// differ, an error will be emitted.
175 /// Appends the two values, which are required to be metadata nodes.
178 /// Appends the two values, which are required to be metadata
179 /// nodes. However, duplicate entries in the second list are dropped
180 /// during the append operation.
184 struct ModuleFlagEntry {
185 ModFlagBehavior Behavior;
188 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
189 : Behavior(B), Key(K), Val(V) {}
193 /// @name Member Variables
196 LLVMContext &Context; ///< The LLVMContext from which types and
197 ///< constants are allocated.
198 GlobalListType GlobalList; ///< The Global Variables in the module
199 FunctionListType FunctionList; ///< The Functions in the module
200 AliasListType AliasList; ///< The Aliases in the module
201 NamedMDListType NamedMDList; ///< The named metadata in the module
202 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
203 ValueSymbolTable *ValSymTab; ///< Symbol table for values
204 OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
205 std::string ModuleID; ///< Human readable identifier for the module
206 std::string TargetTriple; ///< Platform target triple Module compiled on
207 std::string DataLayout; ///< Target data description
208 void *NamedMDSymTab; ///< NamedMDNode names.
210 friend class Constant;
213 /// @name Constructors
216 /// The Module constructor. Note that there is no default constructor. You
217 /// must provide a name for the module upon construction.
218 explicit Module(StringRef ModuleID, LLVMContext& C);
219 /// The module destructor. This will dropAllReferences.
223 /// @name Module Level Accessors
226 /// Get the module identifier which is, essentially, the name of the module.
227 /// @returns the module identifier as a string
228 const std::string &getModuleIdentifier() const { return ModuleID; }
230 /// Get the data layout string for the module's target platform. This encodes
231 /// the type sizes and alignments expected by this module.
232 /// @returns the data layout as a string
233 const std::string &getDataLayout() const { return DataLayout; }
235 /// Get the target triple which is a string describing the target host.
236 /// @returns a string containing the target triple.
237 const std::string &getTargetTriple() const { return TargetTriple; }
239 /// Get the target endian information.
240 /// @returns Endianess - an enumeration for the endianess of the target
241 Endianness getEndianness() const;
243 /// Get the target pointer size.
244 /// @returns PointerSize - an enumeration for the size of the target's pointer
245 PointerSize getPointerSize() const;
247 /// Get the global data context.
248 /// @returns LLVMContext - a container for LLVM's global information
249 LLVMContext &getContext() const { return Context; }
251 /// Get any module-scope inline assembly blocks.
252 /// @returns a string containing the module-scope inline assembly blocks.
253 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
256 /// @name Module Level Mutators
259 /// Set the module identifier.
260 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
262 /// Set the data layout
263 void setDataLayout(StringRef DL) { DataLayout = DL; }
265 /// Set the target triple.
266 void setTargetTriple(StringRef T) { TargetTriple = T; }
268 /// Set the module-scope inline assembly blocks.
269 void setModuleInlineAsm(StringRef Asm) {
270 GlobalScopeAsm = Asm;
271 if (!GlobalScopeAsm.empty() &&
272 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
273 GlobalScopeAsm += '\n';
276 /// Append to the module-scope inline assembly blocks, automatically inserting
277 /// a separating newline if necessary.
278 void appendModuleInlineAsm(StringRef Asm) {
279 GlobalScopeAsm += Asm;
280 if (!GlobalScopeAsm.empty() &&
281 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
282 GlobalScopeAsm += '\n';
286 /// @name Generic Value Accessors
289 /// getNamedValue - Return the global value in the module with
290 /// the specified name, of arbitrary type. This method returns null
291 /// if a global with the specified name is not found.
292 GlobalValue *getNamedValue(StringRef Name) const;
294 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
295 /// This ID is uniqued across modules in the current LLVMContext.
296 unsigned getMDKindID(StringRef Name) const;
298 /// getMDKindNames - Populate client supplied SmallVector with the name for
299 /// custom metadata IDs registered in this LLVMContext.
300 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
303 typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
306 /// getTypeByName - Return the type with the specified name, or null if there
307 /// is none by that name.
308 StructType *getTypeByName(StringRef Name) const;
311 /// @name Function Accessors
314 /// getOrInsertFunction - Look up the specified function in the module symbol
315 /// table. Four possibilities:
316 /// 1. If it does not exist, add a prototype for the function and return it.
317 /// 2. If it exists, and has a local linkage, the existing function is
318 /// renamed and a new one is inserted.
319 /// 3. Otherwise, if the existing function has the correct prototype, return
320 /// the existing function.
321 /// 4. Finally, the function exists but has the wrong prototype: return the
322 /// function with a constantexpr cast to the right prototype.
323 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
324 AttributeSet AttributeList);
326 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
328 /// getOrInsertFunction - Look up the specified function in the module symbol
329 /// table. If it does not exist, add a prototype for the function and return
330 /// it. This function guarantees to return a constant of pointer to the
331 /// specified function type or a ConstantExpr BitCast of that type if the
332 /// named function has a different type. This version of the method takes a
333 /// null terminated list of function arguments, which makes it easier for
335 Constant *getOrInsertFunction(StringRef Name,
336 AttributeSet AttributeList,
337 Type *RetTy, ...) END_WITH_NULL;
339 /// getOrInsertFunction - Same as above, but without the attributes.
340 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
343 /// getFunction - Look up the specified function in the module symbol table.
344 /// If it does not exist, return null.
345 Function *getFunction(StringRef Name) const;
348 /// @name Global Variable Accessors
351 /// getGlobalVariable - Look up the specified global variable in the module
352 /// symbol table. If it does not exist, return null. If AllowInternal is set
353 /// to true, this function will return types that have InternalLinkage. By
354 /// default, these types are not returned.
355 const GlobalVariable *getGlobalVariable(StringRef Name,
356 bool AllowInternal = false) const {
357 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
360 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
362 /// getNamedGlobal - Return the global variable in the module with the
363 /// specified name, of arbitrary type. This method returns null if a global
364 /// with the specified name is not found.
365 GlobalVariable *getNamedGlobal(StringRef Name) {
366 return getGlobalVariable(Name, true);
368 const GlobalVariable *getNamedGlobal(StringRef Name) const {
369 return const_cast<Module *>(this)->getNamedGlobal(Name);
372 /// getOrInsertGlobal - Look up the specified global in the module symbol
374 /// 1. If it does not exist, add a declaration of the global and return it.
375 /// 2. Else, the global exists but has the wrong type: return the function
376 /// with a constantexpr cast to the right type.
377 /// 3. Finally, if the existing global is the correct declaration, return
378 /// the existing global.
379 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
382 /// @name Global Alias Accessors
385 /// getNamedAlias - Return the global alias in the module with the
386 /// specified name, of arbitrary type. This method returns null if a global
387 /// with the specified name is not found.
388 GlobalAlias *getNamedAlias(StringRef Name) const;
391 /// @name Named Metadata Accessors
394 /// getNamedMetadata - Return the first NamedMDNode in the module with the
395 /// specified name. This method returns null if a NamedMDNode with the
396 /// specified name is not found.
397 NamedMDNode *getNamedMetadata(const Twine &Name) const;
399 /// getOrInsertNamedMetadata - Return the named MDNode in the module
400 /// with the specified name. This method returns a new NamedMDNode if a
401 /// NamedMDNode with the specified name is not found.
402 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
404 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
406 void eraseNamedMetadata(NamedMDNode *NMD);
409 /// @name Module Flags Accessors
412 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
413 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
415 /// Return the corresponding value if Key appears in module flags, otherwise
417 Value *getModuleFlag(StringRef Key) const;
419 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
420 /// represents module-level flags. This method returns null if there are no
421 /// module-level flags.
422 NamedMDNode *getModuleFlagsMetadata() const;
424 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
425 /// that represents module-level flags. If module-level flags aren't found,
426 /// it creates the named metadata that contains them.
427 NamedMDNode *getOrInsertModuleFlagsMetadata();
429 /// addModuleFlag - Add a module-level flag to the module-level flags
430 /// metadata. It will create the module-level flags named metadata if it
431 /// doesn't already exist.
432 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
433 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
434 void addModuleFlag(MDNode *Node);
437 /// @name Materialization
440 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
441 /// yet have a Materializer. To reset the materializer for a module that
442 /// already has one, call MaterializeAllPermanently first. Destroying this
443 /// module will destroy its materializer without materializing any more
444 /// GlobalValues. Without destroying the Module, there is no way to detach or
445 /// destroy a materializer without materializing all the GVs it controls, to
446 /// avoid leaving orphan unmaterialized GVs.
447 void setMaterializer(GVMaterializer *GVM);
448 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
449 GVMaterializer *getMaterializer() const { return Materializer.get(); }
451 /// isMaterializable - True if the definition of GV has yet to be materialized
452 /// from the GVMaterializer.
453 bool isMaterializable(const GlobalValue *GV) const;
454 /// isDematerializable - Returns true if this GV was loaded from this Module's
455 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
456 bool isDematerializable(const GlobalValue *GV) const;
458 /// Materialize - Make sure the GlobalValue is fully read. If the module is
459 /// corrupt, this returns true and fills in the optional string with
460 /// information about the problem. If successful, this returns false.
461 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
462 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
463 /// supports it, release the memory for the function, and set it up to be
464 /// materialized lazily. If !isDematerializable(), this method is a noop.
465 void Dematerialize(GlobalValue *GV);
467 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
468 /// If the module is corrupt, this returns true and fills in the optional
469 /// string with information about the problem. If successful, this returns
471 bool MaterializeAll(std::string *ErrInfo = 0);
473 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
474 /// fully read and clear the Materializer. If the module is corrupt, this
475 /// returns true, fills in the optional string with information about the
476 /// problem, and DOES NOT clear the old Materializer. If successful, this
478 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
481 /// @name Direct access to the globals list, functions list, and symbol table
484 /// Get the Module's list of global variables (constant).
485 const GlobalListType &getGlobalList() const { return GlobalList; }
486 /// Get the Module's list of global variables.
487 GlobalListType &getGlobalList() { return GlobalList; }
488 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
489 return &Module::GlobalList;
491 /// Get the Module's list of functions (constant).
492 const FunctionListType &getFunctionList() const { return FunctionList; }
493 /// Get the Module's list of functions.
494 FunctionListType &getFunctionList() { return FunctionList; }
495 static iplist<Function> Module::*getSublistAccess(Function*) {
496 return &Module::FunctionList;
498 /// Get the Module's list of aliases (constant).
499 const AliasListType &getAliasList() const { return AliasList; }
500 /// Get the Module's list of aliases.
501 AliasListType &getAliasList() { return AliasList; }
502 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
503 return &Module::AliasList;
505 /// Get the Module's list of named metadata (constant).
506 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
507 /// Get the Module's list of named metadata.
508 NamedMDListType &getNamedMDList() { return NamedMDList; }
509 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
510 return &Module::NamedMDList;
512 /// Get the symbol table of global variable and function identifiers
513 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
514 /// Get the Module's symbol table of global variable and function identifiers.
515 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
518 /// @name Global Variable Iteration
521 global_iterator global_begin() { return GlobalList.begin(); }
522 const_global_iterator global_begin() const { return GlobalList.begin(); }
523 global_iterator global_end () { return GlobalList.end(); }
524 const_global_iterator global_end () const { return GlobalList.end(); }
525 bool global_empty() const { return GlobalList.empty(); }
528 /// @name Function Iteration
531 iterator begin() { return FunctionList.begin(); }
532 const_iterator begin() const { return FunctionList.begin(); }
533 iterator end () { return FunctionList.end(); }
534 const_iterator end () const { return FunctionList.end(); }
535 size_t size() const { return FunctionList.size(); }
536 bool empty() const { return FunctionList.empty(); }
539 /// @name Alias Iteration
542 alias_iterator alias_begin() { return AliasList.begin(); }
543 const_alias_iterator alias_begin() const { return AliasList.begin(); }
544 alias_iterator alias_end () { return AliasList.end(); }
545 const_alias_iterator alias_end () const { return AliasList.end(); }
546 size_t alias_size () const { return AliasList.size(); }
547 bool alias_empty() const { return AliasList.empty(); }
551 /// @name Named Metadata Iteration
554 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
555 const_named_metadata_iterator named_metadata_begin() const {
556 return NamedMDList.begin();
559 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
560 const_named_metadata_iterator named_metadata_end() const {
561 return NamedMDList.end();
564 size_t named_metadata_size() const { return NamedMDList.size(); }
565 bool named_metadata_empty() const { return NamedMDList.empty(); }
569 /// @name Utility functions for printing and dumping Module objects
572 /// Print the module to an output stream with an optional
573 /// AssemblyAnnotationWriter.
574 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
576 /// Dump the module to stderr (for debugging).
579 /// This function causes all the subinstructions to "let go" of all references
580 /// that they are maintaining. This allows one to 'delete' a whole class at
581 /// a time, even though there may be circular references... first all
582 /// references are dropped, and all use counts go to zero. Then everything
583 /// is delete'd for real. Note that no operations are valid on an object
584 /// that has "dropped all references", except operator delete.
585 void dropAllReferences();
589 /// An raw_ostream inserter for modules.
590 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
595 // Create wrappers for C Binding types (see CBindingWrapping.h).
596 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
598 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
601 inline Module *unwrap(LLVMModuleProviderRef MP) {
602 return reinterpret_cast<Module*>(MP);
605 } // End llvm namespace