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 Constant *getOrInsertTargetIntrinsic(StringRef Name,
345 AttributeSet AttributeList);
347 /// getFunction - Look up the specified function in the module symbol table.
348 /// If it does not exist, return null.
349 Function *getFunction(StringRef Name) const;
352 /// @name Global Variable Accessors
355 /// getGlobalVariable - Look up the specified global variable in the module
356 /// symbol table. If it does not exist, return null. If AllowInternal is set
357 /// to true, this function will return types that have InternalLinkage. By
358 /// default, these types are not returned.
359 GlobalVariable *getGlobalVariable(StringRef Name,
360 bool AllowInternal = false) const;
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) const {
366 return getGlobalVariable(Name, true);
369 /// getOrInsertGlobal - Look up the specified global in the module symbol
371 /// 1. If it does not exist, add a declaration of the global and return it.
372 /// 2. Else, the global exists but has the wrong type: return the function
373 /// with a constantexpr cast to the right type.
374 /// 3. Finally, if the existing global is the correct declaration, return
375 /// the existing global.
376 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
379 /// @name Global Alias Accessors
382 /// getNamedAlias - Return the global alias in the module with the
383 /// specified name, of arbitrary type. This method returns null if a global
384 /// with the specified name is not found.
385 GlobalAlias *getNamedAlias(StringRef Name) const;
388 /// @name Named Metadata Accessors
391 /// getNamedMetadata - Return the NamedMDNode in the module with the
392 /// specified name. This method returns null if a NamedMDNode with the
393 /// specified name is not found.
394 NamedMDNode *getNamedMetadata(const Twine &Name) const;
396 /// getOrInsertNamedMetadata - Return the named MDNode in the module
397 /// with the specified name. This method returns a new NamedMDNode if a
398 /// NamedMDNode with the specified name is not found.
399 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
401 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
403 void eraseNamedMetadata(NamedMDNode *NMD);
406 /// @name Module Flags Accessors
409 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
410 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
412 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
413 /// represents module-level flags. This method returns null if there are no
414 /// module-level flags.
415 NamedMDNode *getModuleFlagsMetadata() const;
417 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
418 /// that represents module-level flags. If module-level flags aren't found,
419 /// it creates the named metadata that contains them.
420 NamedMDNode *getOrInsertModuleFlagsMetadata();
422 /// addModuleFlag - Add a module-level flag to the module-level flags
423 /// metadata. It will create the module-level flags named metadata if it
424 /// doesn't already exist.
425 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
426 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
427 void addModuleFlag(MDNode *Node);
430 /// @name Materialization
433 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
434 /// yet have a Materializer. To reset the materializer for a module that
435 /// already has one, call MaterializeAllPermanently first. Destroying this
436 /// module will destroy its materializer without materializing any more
437 /// GlobalValues. Without destroying the Module, there is no way to detach or
438 /// destroy a materializer without materializing all the GVs it controls, to
439 /// avoid leaving orphan unmaterialized GVs.
440 void setMaterializer(GVMaterializer *GVM);
441 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
442 GVMaterializer *getMaterializer() const { return Materializer.get(); }
444 /// isMaterializable - True if the definition of GV has yet to be materialized
445 /// from the GVMaterializer.
446 bool isMaterializable(const GlobalValue *GV) const;
447 /// isDematerializable - Returns true if this GV was loaded from this Module's
448 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
449 bool isDematerializable(const GlobalValue *GV) const;
451 /// Materialize - Make sure the GlobalValue is fully read. If the module is
452 /// corrupt, this returns true and fills in the optional string with
453 /// information about the problem. If successful, this returns false.
454 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
455 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
456 /// supports it, release the memory for the function, and set it up to be
457 /// materialized lazily. If !isDematerializable(), this method is a noop.
458 void Dematerialize(GlobalValue *GV);
460 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
461 /// If the module is corrupt, this returns true and fills in the optional
462 /// string with information about the problem. If successful, this returns
464 bool MaterializeAll(std::string *ErrInfo = 0);
466 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
467 /// fully read and clear the Materializer. If the module is corrupt, this
468 /// returns true, fills in the optional string with information about the
469 /// problem, and DOES NOT clear the old Materializer. If successful, this
471 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
474 /// @name Direct access to the globals list, functions list, and symbol table
477 /// Get the Module's list of global variables (constant).
478 const GlobalListType &getGlobalList() const { return GlobalList; }
479 /// Get the Module's list of global variables.
480 GlobalListType &getGlobalList() { return GlobalList; }
481 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
482 return &Module::GlobalList;
484 /// Get the Module's list of functions (constant).
485 const FunctionListType &getFunctionList() const { return FunctionList; }
486 /// Get the Module's list of functions.
487 FunctionListType &getFunctionList() { return FunctionList; }
488 static iplist<Function> Module::*getSublistAccess(Function*) {
489 return &Module::FunctionList;
491 /// Get the Module's list of aliases (constant).
492 const AliasListType &getAliasList() const { return AliasList; }
493 /// Get the Module's list of aliases.
494 AliasListType &getAliasList() { return AliasList; }
495 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
496 return &Module::AliasList;
498 /// Get the Module's list of named metadata (constant).
499 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
500 /// Get the Module's list of named metadata.
501 NamedMDListType &getNamedMDList() { return NamedMDList; }
502 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
503 return &Module::NamedMDList;
505 /// Get the symbol table of global variable and function identifiers
506 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
507 /// Get the Module's symbol table of global variable and function identifiers.
508 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
511 /// @name Global Variable Iteration
514 global_iterator global_begin() { return GlobalList.begin(); }
515 const_global_iterator global_begin() const { return GlobalList.begin(); }
516 global_iterator global_end () { return GlobalList.end(); }
517 const_global_iterator global_end () const { return GlobalList.end(); }
518 bool global_empty() const { return GlobalList.empty(); }
521 /// @name Function Iteration
524 iterator begin() { return FunctionList.begin(); }
525 const_iterator begin() const { return FunctionList.begin(); }
526 iterator end () { return FunctionList.end(); }
527 const_iterator end () const { return FunctionList.end(); }
528 size_t size() const { return FunctionList.size(); }
529 bool empty() const { return FunctionList.empty(); }
532 /// @name Alias Iteration
535 alias_iterator alias_begin() { return AliasList.begin(); }
536 const_alias_iterator alias_begin() const { return AliasList.begin(); }
537 alias_iterator alias_end () { return AliasList.end(); }
538 const_alias_iterator alias_end () const { return AliasList.end(); }
539 size_t alias_size () const { return AliasList.size(); }
540 bool alias_empty() const { return AliasList.empty(); }
544 /// @name Named Metadata Iteration
547 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
548 const_named_metadata_iterator named_metadata_begin() const {
549 return NamedMDList.begin();
552 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
553 const_named_metadata_iterator named_metadata_end() const {
554 return NamedMDList.end();
557 size_t named_metadata_size() const { return NamedMDList.size(); }
558 bool named_metadata_empty() const { return NamedMDList.empty(); }
562 /// @name Utility functions for printing and dumping Module objects
565 /// Print the module to an output stream with an optional
566 /// AssemblyAnnotationWriter.
567 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
569 /// Dump the module to stderr (for debugging).
572 /// This function causes all the subinstructions to "let go" of all references
573 /// that they are maintaining. This allows one to 'delete' a whole class at
574 /// a time, even though there may be circular references... first all
575 /// references are dropped, and all use counts go to zero. Then everything
576 /// is delete'd for real. Note that no operations are valid on an object
577 /// that has "dropped all references", except operator delete.
578 void dropAllReferences();
582 /// An raw_ostream inserter for modules.
583 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
588 // Create wrappers for C Binding types (see CBindingWrapping.h).
589 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
591 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
594 inline Module *unwrap(LLVMModuleProviderRef MP) {
595 return reinterpret_cast<Module*>(MP);
598 } // End llvm namespace