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/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 /// This enumeration defines the supported behaviors of module flags.
151 enum ModFlagBehavior {
152 /// Emits an error if two values disagree, otherwise the resulting value is
153 /// that of the operands.
156 /// Emits a warning if two values disagree. The result value will be the
157 /// operand for the flag from the first module being linked.
160 /// Adds a requirement that another module flag be present and have a
161 /// specified value after linking is performed. The value must be a metadata
162 /// pair, where the first element of the pair is the ID of the module flag
163 /// to be restricted, and the second element of the pair is the value the
164 /// module flag should be restricted to. This behavior can be used to
165 /// restrict the allowable results (via triggering of an error) of linking
166 /// IDs with the **Override** behavior.
169 /// Uses the specified value, regardless of the behavior or value of the
170 /// other module. If both modules specify **Override**, but the values
171 /// differ, an error will be emitted.
174 /// Appends the two values, which are required to be metadata nodes.
177 /// Appends the two values, which are required to be metadata
178 /// nodes. However, duplicate entries in the second list are dropped
179 /// during the append operation.
183 struct ModuleFlagEntry {
184 ModFlagBehavior Behavior;
187 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
188 : Behavior(B), Key(K), Val(V) {}
192 /// @name Member Variables
195 LLVMContext &Context; ///< The LLVMContext from which types and
196 ///< constants are allocated.
197 GlobalListType GlobalList; ///< The Global Variables in the module
198 FunctionListType FunctionList; ///< The Functions in the module
199 AliasListType AliasList; ///< The Aliases in the module
200 NamedMDListType NamedMDList; ///< The named metadata in the module
201 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
202 ValueSymbolTable *ValSymTab; ///< Symbol table for values
203 OwningPtr<GVMaterializer> Materializer; ///< Used to materialize GlobalValues
204 std::string ModuleID; ///< Human readable identifier for the module
205 std::string TargetTriple; ///< Platform target triple Module compiled on
206 std::string DataLayout; ///< Target data description
207 void *NamedMDSymTab; ///< NamedMDNode names.
209 friend class Constant;
212 /// @name Constructors
215 /// The Module constructor. Note that there is no default constructor. You
216 /// must provide a name for the module upon construction.
217 explicit Module(StringRef ModuleID, LLVMContext& C);
218 /// The module destructor. This will dropAllReferences.
222 /// @name Module Level Accessors
225 /// Get the module identifier which is, essentially, the name of the module.
226 /// @returns the module identifier as a string
227 const std::string &getModuleIdentifier() const { return ModuleID; }
229 /// Get the data layout string for the module's target platform. This encodes
230 /// the type sizes and alignments expected by this module.
231 /// @returns the data layout as a string
232 const std::string &getDataLayout() const { return DataLayout; }
234 /// Get the target triple which is a string describing the target host.
235 /// @returns a string containing the target triple.
236 const std::string &getTargetTriple() const { return TargetTriple; }
238 /// Get the target endian information.
239 /// @returns Endianess - an enumeration for the endianess of the target
240 Endianness getEndianness() const;
242 /// Get the target pointer size.
243 /// @returns PointerSize - an enumeration for the size of the target's pointer
244 PointerSize getPointerSize() const;
246 /// Get the global data context.
247 /// @returns LLVMContext - a container for LLVM's global information
248 LLVMContext &getContext() const { return Context; }
250 /// Get any module-scope inline assembly blocks.
251 /// @returns a string containing the module-scope inline assembly blocks.
252 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
255 /// @name Module Level Mutators
258 /// Set the module identifier.
259 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
261 /// Set the data layout
262 void setDataLayout(StringRef DL) { DataLayout = DL; }
264 /// Set the target triple.
265 void setTargetTriple(StringRef T) { TargetTriple = T; }
267 /// Set the module-scope inline assembly blocks.
268 void setModuleInlineAsm(StringRef Asm) {
269 GlobalScopeAsm = Asm;
270 if (!GlobalScopeAsm.empty() &&
271 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
272 GlobalScopeAsm += '\n';
275 /// Append to the module-scope inline assembly blocks, automatically inserting
276 /// a separating newline if necessary.
277 void appendModuleInlineAsm(StringRef Asm) {
278 GlobalScopeAsm += Asm;
279 if (!GlobalScopeAsm.empty() &&
280 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
281 GlobalScopeAsm += '\n';
285 /// @name Generic Value Accessors
288 /// getNamedValue - Return the global value in the module with
289 /// the specified name, of arbitrary type. This method returns null
290 /// if a global with the specified name is not found.
291 GlobalValue *getNamedValue(StringRef Name) const;
293 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
294 /// This ID is uniqued across modules in the current LLVMContext.
295 unsigned getMDKindID(StringRef Name) const;
297 /// getMDKindNames - Populate client supplied SmallVector with the name for
298 /// custom metadata IDs registered in this LLVMContext.
299 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
302 typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
305 /// getTypeByName - Return the type with the specified name, or null if there
306 /// is none by that name.
307 StructType *getTypeByName(StringRef Name) const;
310 /// @name Function Accessors
313 /// getOrInsertFunction - Look up the specified function in the module symbol
314 /// table. Four possibilities:
315 /// 1. If it does not exist, add a prototype for the function and return it.
316 /// 2. If it exists, and has a local linkage, the existing function is
317 /// renamed and a new one is inserted.
318 /// 3. Otherwise, if the existing function has the correct prototype, return
319 /// the existing function.
320 /// 4. Finally, the function exists but has the wrong prototype: return the
321 /// function with a constantexpr cast to the right prototype.
322 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
323 AttributeSet AttributeList);
325 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
327 /// getOrInsertFunction - Look up the specified function in the module symbol
328 /// table. If it does not exist, add a prototype for the function and return
329 /// it. This function guarantees to return a constant of pointer to the
330 /// specified function type or a ConstantExpr BitCast of that type if the
331 /// named function has a different type. This version of the method takes a
332 /// null terminated list of function arguments, which makes it easier for
334 Constant *getOrInsertFunction(StringRef Name,
335 AttributeSet AttributeList,
336 Type *RetTy, ...) END_WITH_NULL;
338 /// getOrInsertFunction - Same as above, but without the attributes.
339 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
342 Constant *getOrInsertTargetIntrinsic(StringRef Name,
344 AttributeSet AttributeList);
346 /// getFunction - Look up the specified function in the module symbol table.
347 /// If it does not exist, return null.
348 Function *getFunction(StringRef Name) const;
351 /// @name Global Variable Accessors
354 /// getGlobalVariable - Look up the specified global variable in the module
355 /// symbol table. If it does not exist, return null. If AllowInternal is set
356 /// to true, this function will return types that have InternalLinkage. By
357 /// default, these types are not returned.
358 GlobalVariable *getGlobalVariable(StringRef Name,
359 bool AllowInternal = false) const;
361 /// getNamedGlobal - Return the global variable in the module with the
362 /// specified name, of arbitrary type. This method returns null if a global
363 /// with the specified name is not found.
364 GlobalVariable *getNamedGlobal(StringRef Name) const {
365 return getGlobalVariable(Name, true);
368 /// getOrInsertGlobal - Look up the specified global in the module symbol
370 /// 1. If it does not exist, add a declaration of the global and return it.
371 /// 2. Else, the global exists but has the wrong type: return the function
372 /// with a constantexpr cast to the right type.
373 /// 3. Finally, if the existing global is the correct declaration, return
374 /// the existing global.
375 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
378 /// @name Global Alias Accessors
381 /// getNamedAlias - Return the global alias in the module with the
382 /// specified name, of arbitrary type. This method returns null if a global
383 /// with the specified name is not found.
384 GlobalAlias *getNamedAlias(StringRef Name) const;
387 /// @name Named Metadata Accessors
390 /// getNamedMetadata - Return the NamedMDNode in the module with the
391 /// specified name. This method returns null if a NamedMDNode with the
392 /// specified name is not found.
393 NamedMDNode *getNamedMetadata(const Twine &Name) const;
395 /// getOrInsertNamedMetadata - Return the named MDNode in the module
396 /// with the specified name. This method returns a new NamedMDNode if a
397 /// NamedMDNode with the specified name is not found.
398 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
400 /// eraseNamedMetadata - Remove the given NamedMDNode from this module
402 void eraseNamedMetadata(NamedMDNode *NMD);
405 /// @name Module Flags Accessors
408 /// getModuleFlagsMetadata - Returns the module flags in the provided vector.
409 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
411 /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
412 /// represents module-level flags. This method returns null if there are no
413 /// module-level flags.
414 NamedMDNode *getModuleFlagsMetadata() const;
416 /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module
417 /// that represents module-level flags. If module-level flags aren't found,
418 /// it creates the named metadata that contains them.
419 NamedMDNode *getOrInsertModuleFlagsMetadata();
421 /// addModuleFlag - Add a module-level flag to the module-level flags
422 /// metadata. It will create the module-level flags named metadata if it
423 /// doesn't already exist.
424 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
425 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
426 void addModuleFlag(MDNode *Node);
429 /// @name Materialization
432 /// setMaterializer - Sets the GVMaterializer to GVM. This module must not
433 /// yet have a Materializer. To reset the materializer for a module that
434 /// already has one, call MaterializeAllPermanently first. Destroying this
435 /// module will destroy its materializer without materializing any more
436 /// GlobalValues. Without destroying the Module, there is no way to detach or
437 /// destroy a materializer without materializing all the GVs it controls, to
438 /// avoid leaving orphan unmaterialized GVs.
439 void setMaterializer(GVMaterializer *GVM);
440 /// getMaterializer - Retrieves the GVMaterializer, if any, for this Module.
441 GVMaterializer *getMaterializer() const { return Materializer.get(); }
443 /// isMaterializable - True if the definition of GV has yet to be materialized
444 /// from the GVMaterializer.
445 bool isMaterializable(const GlobalValue *GV) const;
446 /// isDematerializable - Returns true if this GV was loaded from this Module's
447 /// GVMaterializer and the GVMaterializer knows how to dematerialize the GV.
448 bool isDematerializable(const GlobalValue *GV) const;
450 /// Materialize - Make sure the GlobalValue is fully read. If the module is
451 /// corrupt, this returns true and fills in the optional string with
452 /// information about the problem. If successful, this returns false.
453 bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
454 /// Dematerialize - If the GlobalValue is read in, and if the GVMaterializer
455 /// supports it, release the memory for the function, and set it up to be
456 /// materialized lazily. If !isDematerializable(), this method is a noop.
457 void Dematerialize(GlobalValue *GV);
459 /// MaterializeAll - Make sure all GlobalValues in this Module are fully read.
460 /// If the module is corrupt, this returns true and fills in the optional
461 /// string with information about the problem. If successful, this returns
463 bool MaterializeAll(std::string *ErrInfo = 0);
465 /// MaterializeAllPermanently - Make sure all GlobalValues in this Module are
466 /// fully read and clear the Materializer. If the module is corrupt, this
467 /// returns true, fills in the optional string with information about the
468 /// problem, and DOES NOT clear the old Materializer. If successful, this
470 bool MaterializeAllPermanently(std::string *ErrInfo = 0);
473 /// @name Direct access to the globals list, functions list, and symbol table
476 /// Get the Module's list of global variables (constant).
477 const GlobalListType &getGlobalList() const { return GlobalList; }
478 /// Get the Module's list of global variables.
479 GlobalListType &getGlobalList() { return GlobalList; }
480 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
481 return &Module::GlobalList;
483 /// Get the Module's list of functions (constant).
484 const FunctionListType &getFunctionList() const { return FunctionList; }
485 /// Get the Module's list of functions.
486 FunctionListType &getFunctionList() { return FunctionList; }
487 static iplist<Function> Module::*getSublistAccess(Function*) {
488 return &Module::FunctionList;
490 /// Get the Module's list of aliases (constant).
491 const AliasListType &getAliasList() const { return AliasList; }
492 /// Get the Module's list of aliases.
493 AliasListType &getAliasList() { return AliasList; }
494 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
495 return &Module::AliasList;
497 /// Get the Module's list of named metadata (constant).
498 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
499 /// Get the Module's list of named metadata.
500 NamedMDListType &getNamedMDList() { return NamedMDList; }
501 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
502 return &Module::NamedMDList;
504 /// Get the symbol table of global variable and function identifiers
505 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
506 /// Get the Module's symbol table of global variable and function identifiers.
507 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
510 /// @name Global Variable Iteration
513 global_iterator global_begin() { return GlobalList.begin(); }
514 const_global_iterator global_begin() const { return GlobalList.begin(); }
515 global_iterator global_end () { return GlobalList.end(); }
516 const_global_iterator global_end () const { return GlobalList.end(); }
517 bool global_empty() const { return GlobalList.empty(); }
520 /// @name Function Iteration
523 iterator begin() { return FunctionList.begin(); }
524 const_iterator begin() const { return FunctionList.begin(); }
525 iterator end () { return FunctionList.end(); }
526 const_iterator end () const { return FunctionList.end(); }
527 size_t size() const { return FunctionList.size(); }
528 bool empty() const { return FunctionList.empty(); }
531 /// @name Alias Iteration
534 alias_iterator alias_begin() { return AliasList.begin(); }
535 const_alias_iterator alias_begin() const { return AliasList.begin(); }
536 alias_iterator alias_end () { return AliasList.end(); }
537 const_alias_iterator alias_end () const { return AliasList.end(); }
538 size_t alias_size () const { return AliasList.size(); }
539 bool alias_empty() const { return AliasList.empty(); }
543 /// @name Named Metadata Iteration
546 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
547 const_named_metadata_iterator named_metadata_begin() const {
548 return NamedMDList.begin();
551 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
552 const_named_metadata_iterator named_metadata_end() const {
553 return NamedMDList.end();
556 size_t named_metadata_size() const { return NamedMDList.size(); }
557 bool named_metadata_empty() const { return NamedMDList.empty(); }
561 /// @name Utility functions for printing and dumping Module objects
564 /// Print the module to an output stream with an optional
565 /// AssemblyAnnotationWriter.
566 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
568 /// Dump the module to stderr (for debugging).
571 /// This function causes all the subinstructions to "let go" of all references
572 /// that they are maintaining. This allows one to 'delete' a whole class at
573 /// a time, even though there may be circular references... first all
574 /// references are dropped, and all use counts go to zero. Then everything
575 /// is delete'd for real. Note that no operations are valid on an object
576 /// that has "dropped all references", except operator delete.
577 void dropAllReferences();
581 /// An raw_ostream inserter for modules.
582 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
587 } // End llvm namespace