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/iterator_range.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalAlias.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/Support/CBindingWrapping.h"
25 #include "llvm/Support/DataTypes.h"
26 #include <system_error>
32 class RandomNumberGenerator;
34 template<typename T> struct DenseMapInfo;
35 template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
37 template<> struct ilist_traits<Function>
38 : public SymbolTableListTraits<Function, Module> {
40 // createSentinel is used to get hold of the node that marks the end of the
41 // list... (same trick used here as in ilist_traits<Instruction>)
42 Function *createSentinel() const {
43 return static_cast<Function*>(&Sentinel);
45 static void destroySentinel(Function*) {}
47 Function *provideInitialHead() const { return createSentinel(); }
48 Function *ensureHead(Function*) const { return createSentinel(); }
49 static void noteHead(Function*, Function*) {}
52 mutable ilist_node<Function> Sentinel;
55 template<> struct ilist_traits<GlobalVariable>
56 : public SymbolTableListTraits<GlobalVariable, Module> {
57 // createSentinel is used to create a node that marks the end of the list.
58 GlobalVariable *createSentinel() const {
59 return static_cast<GlobalVariable*>(&Sentinel);
61 static void destroySentinel(GlobalVariable*) {}
63 GlobalVariable *provideInitialHead() const { return createSentinel(); }
64 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
65 static void noteHead(GlobalVariable*, GlobalVariable*) {}
67 mutable ilist_node<GlobalVariable> Sentinel;
70 template<> struct ilist_traits<GlobalAlias>
71 : public SymbolTableListTraits<GlobalAlias, Module> {
72 // createSentinel is used to create a node that marks the end of the list.
73 GlobalAlias *createSentinel() const {
74 return static_cast<GlobalAlias*>(&Sentinel);
76 static void destroySentinel(GlobalAlias*) {}
78 GlobalAlias *provideInitialHead() const { return createSentinel(); }
79 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
80 static void noteHead(GlobalAlias*, GlobalAlias*) {}
82 mutable ilist_node<GlobalAlias> Sentinel;
85 template<> struct ilist_traits<NamedMDNode>
86 : public ilist_default_traits<NamedMDNode> {
87 // createSentinel is used to get hold of a node that marks the end of
89 NamedMDNode *createSentinel() const {
90 return static_cast<NamedMDNode*>(&Sentinel);
92 static void destroySentinel(NamedMDNode*) {}
94 NamedMDNode *provideInitialHead() const { return createSentinel(); }
95 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
96 static void noteHead(NamedMDNode*, NamedMDNode*) {}
97 void addNodeToList(NamedMDNode *) {}
98 void removeNodeFromList(NamedMDNode *) {}
100 mutable ilist_node<NamedMDNode> Sentinel;
103 /// A Module instance is used to store all the information related to an
104 /// LLVM module. Modules are the top level container of all other LLVM
105 /// Intermediate Representation (IR) objects. Each module directly contains a
106 /// list of globals variables, a list of functions, a list of libraries (or
107 /// other modules) this module depends on, a symbol table, and various data
108 /// about the target's characteristics.
110 /// A module maintains a GlobalValRefMap object that is used to hold all
111 /// constant references to global variables in the module. When a global
112 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
113 /// @brief The main container class for the LLVM Intermediate Representation.
115 /// @name Types And Enumerations
118 /// The type for the list of global variables.
119 typedef iplist<GlobalVariable> GlobalListType;
120 /// The type for the list of functions.
121 typedef iplist<Function> FunctionListType;
122 /// The type for the list of aliases.
123 typedef iplist<GlobalAlias> AliasListType;
124 /// The type for the list of named metadata.
125 typedef ilist<NamedMDNode> NamedMDListType;
127 /// The Global Variable iterator.
128 typedef GlobalListType::iterator global_iterator;
129 /// The Global Variable constant iterator.
130 typedef GlobalListType::const_iterator const_global_iterator;
132 /// The Function iterators.
133 typedef FunctionListType::iterator iterator;
134 /// The Function constant iterator
135 typedef FunctionListType::const_iterator const_iterator;
137 /// The Global Alias iterators.
138 typedef AliasListType::iterator alias_iterator;
139 /// The Global Alias constant iterator
140 typedef AliasListType::const_iterator const_alias_iterator;
142 /// The named metadata iterators.
143 typedef NamedMDListType::iterator named_metadata_iterator;
144 /// The named metadata constant interators.
145 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
147 /// This enumeration defines the supported behaviors of module flags.
148 enum ModFlagBehavior {
149 /// Emits an error if two values disagree, otherwise the resulting value is
150 /// that of the operands.
153 /// Emits a warning if two values disagree. The result value will be the
154 /// operand for the flag from the first module being linked.
157 /// Adds a requirement that another module flag be present and have a
158 /// specified value after linking is performed. The value must be a metadata
159 /// pair, where the first element of the pair is the ID of the module flag
160 /// to be restricted, and the second element of the pair is the value the
161 /// module flag should be restricted to. This behavior can be used to
162 /// restrict the allowable results (via triggering of an error) of linking
163 /// IDs with the **Override** behavior.
166 /// Uses the specified value, regardless of the behavior or value of the
167 /// other module. If both modules specify **Override**, but the values
168 /// differ, an error will be emitted.
171 /// Appends the two values, which are required to be metadata nodes.
174 /// Appends the two values, which are required to be metadata
175 /// nodes. However, duplicate entries in the second list are dropped
176 /// during the append operation.
180 struct ModuleFlagEntry {
181 ModFlagBehavior Behavior;
184 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
185 : Behavior(B), Key(K), Val(V) {}
189 /// @name Member Variables
192 LLVMContext &Context; ///< The LLVMContext from which types and
193 ///< constants are allocated.
194 GlobalListType GlobalList; ///< The Global Variables in the module
195 FunctionListType FunctionList; ///< The Functions in the module
196 AliasListType AliasList; ///< The Aliases in the module
197 NamedMDListType NamedMDList; ///< The named metadata in the module
198 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
199 ValueSymbolTable *ValSymTab; ///< Symbol table for values
200 std::unique_ptr<GVMaterializer>
201 Materializer; ///< Used to materialize GlobalValues
202 std::string ModuleID; ///< Human readable identifier for the module
203 std::string TargetTriple; ///< Platform target triple Module compiled on
204 void *NamedMDSymTab; ///< NamedMDNode names.
205 // Allow lazy initialization in const method.
206 mutable RandomNumberGenerator *RNG; ///< The random number generator for this module.
208 // We need to keep the string because the C API expects us to own the string
210 // Since we have it, we also use an empty string to represent a module without
211 // a DataLayout. If it has a DataLayout, these variables are in sync and the
212 // string is just a cache of getDataLayout()->getStringRepresentation().
213 std::string DataLayoutStr;
216 friend class Constant;
219 /// @name Constructors
222 /// The Module constructor. Note that there is no default constructor. You
223 /// must provide a name for the module upon construction.
224 explicit Module(StringRef ModuleID, LLVMContext& C);
225 /// The module destructor. This will dropAllReferences.
229 /// @name Module Level Accessors
232 /// Get the module identifier which is, essentially, the name of the module.
233 /// @returns the module identifier as a string
234 const std::string &getModuleIdentifier() const { return ModuleID; }
236 /// Get the data layout string for the module's target platform. This is
237 /// equivalent to getDataLayout()->getStringRepresentation().
238 const std::string &getDataLayoutStr() const { return DataLayoutStr; }
240 /// Get the data layout for the module's target platform.
241 const DataLayout *getDataLayout() const;
243 /// Get the target triple which is a string describing the target host.
244 /// @returns a string containing the target triple.
245 const std::string &getTargetTriple() const { return TargetTriple; }
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; }
255 /// Get the RandomNumberGenerator for this module. The RNG can be
256 /// seeded via -rng-seed=<uint64> and is salted with the ModuleID.
257 /// The returned RNG should not be shared across threads.
258 RandomNumberGenerator &getRNG() const;
261 /// @name Module Level Mutators
264 /// Set the module identifier.
265 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
267 /// Set the data layout
268 void setDataLayout(StringRef Desc);
269 void setDataLayout(const DataLayout *Other);
271 /// Set the target triple.
272 void setTargetTriple(StringRef T) { TargetTriple = T; }
274 /// Set the module-scope inline assembly blocks.
275 void setModuleInlineAsm(StringRef Asm) {
276 GlobalScopeAsm = Asm;
277 if (!GlobalScopeAsm.empty() &&
278 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
279 GlobalScopeAsm += '\n';
282 /// Append to the module-scope inline assembly blocks, automatically inserting
283 /// a separating newline if necessary.
284 void appendModuleInlineAsm(StringRef Asm) {
285 GlobalScopeAsm += Asm;
286 if (!GlobalScopeAsm.empty() &&
287 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
288 GlobalScopeAsm += '\n';
292 /// @name Generic Value Accessors
295 /// Return the global value in the module with the specified name, of
296 /// arbitrary type. This method returns null if a global with the specified
297 /// name is not found.
298 GlobalValue *getNamedValue(StringRef Name) const;
300 /// Return a unique non-zero ID for the specified metadata kind. This ID is
301 /// uniqued across modules in the current LLVMContext.
302 unsigned getMDKindID(StringRef Name) const;
304 /// Populate client supplied SmallVector with the name for custom metadata IDs
305 /// registered in this LLVMContext.
306 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
308 /// Return the type with the specified name, or null if there is none by that
310 StructType *getTypeByName(StringRef Name) const;
313 /// @name Function Accessors
316 /// Look up the specified function in the module symbol table. Four
318 /// 1. If it does not exist, add a prototype for the function and return it.
319 /// 2. If it exists, and has a local linkage, the existing function is
320 /// renamed and a new one is inserted.
321 /// 3. Otherwise, if the existing function has the correct prototype, return
322 /// the existing function.
323 /// 4. Finally, the function exists but has the wrong prototype: return the
324 /// function with a constantexpr cast to the right prototype.
325 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
326 AttributeSet AttributeList);
328 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
330 /// Look up the specified function in the module symbol table. If it does not
331 /// exist, add a prototype for the function and return it. This function
332 /// guarantees to return a constant of pointer to the specified function type
333 /// or a ConstantExpr BitCast of that type if the named function has a
334 /// different type. This version of the method takes a null terminated list of
335 /// function arguments, which makes it easier for clients to use.
336 Constant *getOrInsertFunction(StringRef Name,
337 AttributeSet AttributeList,
338 Type *RetTy, ...) END_WITH_NULL;
340 /// Same as above, but without the attributes.
341 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
344 /// Look up the specified function in the module symbol table. If it does not
345 /// exist, return null.
346 Function *getFunction(StringRef Name) const;
349 /// @name Global Variable Accessors
352 /// Look up the specified global variable in the module symbol table. If it
353 /// does not exist, return null. If AllowInternal is set to true, this
354 /// function will return types that have InternalLinkage. By default, these
355 /// types are not returned.
356 const GlobalVariable *getGlobalVariable(StringRef Name,
357 bool AllowInternal = false) const {
358 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
361 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
363 /// Return the global variable in the module with the specified name, of
364 /// arbitrary type. This method returns null if a global with the specified
365 /// name is not found.
366 GlobalVariable *getNamedGlobal(StringRef Name) {
367 return getGlobalVariable(Name, true);
369 const GlobalVariable *getNamedGlobal(StringRef Name) const {
370 return const_cast<Module *>(this)->getNamedGlobal(Name);
373 /// Look up the specified global in the module symbol table.
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 /// Return the global alias in the module with the specified name, of
386 /// arbitrary type. This method returns null if a global with the specified
387 /// name is not found.
388 GlobalAlias *getNamedAlias(StringRef Name) const;
391 /// @name Named Metadata Accessors
394 /// Return the first NamedMDNode in the module with the specified name. This
395 /// method returns null if a NamedMDNode with the specified name is not found.
396 NamedMDNode *getNamedMetadata(const Twine &Name) const;
398 /// Return the named MDNode in the module with the specified name. This method
399 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
401 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
403 /// Remove the given NamedMDNode from this module and delete it.
404 void eraseNamedMetadata(NamedMDNode *NMD);
407 /// @name Module Flags Accessors
410 /// Returns the module flags in the provided vector.
411 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
413 /// Return the corresponding value if Key appears in module flags, otherwise
415 Value *getModuleFlag(StringRef Key) const;
417 /// Returns the NamedMDNode in the module that represents module-level flags.
418 /// This method returns null if there are no module-level flags.
419 NamedMDNode *getModuleFlagsMetadata() const;
421 /// Returns the NamedMDNode in the module that represents module-level flags.
422 /// If module-level flags aren't found, it creates the named metadata that
424 NamedMDNode *getOrInsertModuleFlagsMetadata();
426 /// Add a module-level flag to the module-level flags metadata. It will create
427 /// the module-level flags named metadata if it doesn't already exist.
428 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
429 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
430 void addModuleFlag(MDNode *Node);
433 /// @name Materialization
436 /// Sets the GVMaterializer to GVM. This module must not yet have a
437 /// Materializer. To reset the materializer for a module that already has one,
438 /// call MaterializeAllPermanently first. Destroying this module will destroy
439 /// its materializer without materializing any more GlobalValues. Without
440 /// destroying the Module, there is no way to detach or destroy a materializer
441 /// without materializing all the GVs it controls, to avoid leaving orphan
442 /// unmaterialized GVs.
443 void setMaterializer(GVMaterializer *GVM);
444 /// Retrieves the GVMaterializer, if any, for this Module.
445 GVMaterializer *getMaterializer() const { return Materializer.get(); }
447 /// True if the definition of GV has yet to be materializedfrom the
449 bool isMaterializable(const GlobalValue *GV) const;
450 /// Returns true if this GV was loaded from this Module's GVMaterializer and
451 /// the GVMaterializer knows how to dematerialize the GV.
452 bool isDematerializable(const GlobalValue *GV) const;
454 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
455 /// returns true and fills in the optional string with information about the
456 /// problem. If successful, this returns false.
457 bool Materialize(GlobalValue *GV, std::string *ErrInfo = nullptr);
458 /// If the GlobalValue is read in, and if the GVMaterializer supports it,
459 /// release the memory for the function, and set it up to be materialized
460 /// lazily. If !isDematerializable(), this method is a noop.
461 void Dematerialize(GlobalValue *GV);
463 /// Make sure all GlobalValues in this Module are fully read.
464 std::error_code materializeAll();
466 /// Make sure all GlobalValues in this Module are fully read and clear the
467 /// Materializer. If the module is corrupt, this DOES NOT clear the old
469 std::error_code materializeAllPermanently(bool ReleaseBuffer = false);
472 /// @name Direct access to the globals list, functions list, and symbol table
475 /// Get the Module's list of global variables (constant).
476 const GlobalListType &getGlobalList() const { return GlobalList; }
477 /// Get the Module's list of global variables.
478 GlobalListType &getGlobalList() { return GlobalList; }
479 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
480 return &Module::GlobalList;
482 /// Get the Module's list of functions (constant).
483 const FunctionListType &getFunctionList() const { return FunctionList; }
484 /// Get the Module's list of functions.
485 FunctionListType &getFunctionList() { return FunctionList; }
486 static iplist<Function> Module::*getSublistAccess(Function*) {
487 return &Module::FunctionList;
489 /// Get the Module's list of aliases (constant).
490 const AliasListType &getAliasList() const { return AliasList; }
491 /// Get the Module's list of aliases.
492 AliasListType &getAliasList() { return AliasList; }
493 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
494 return &Module::AliasList;
496 /// Get the Module's list of named metadata (constant).
497 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
498 /// Get the Module's list of named metadata.
499 NamedMDListType &getNamedMDList() { return NamedMDList; }
500 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
501 return &Module::NamedMDList;
503 /// Get the symbol table of global variable and function identifiers
504 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
505 /// Get the Module's symbol table of global variable and function identifiers.
506 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
509 /// @name Global Variable Iteration
512 global_iterator global_begin() { return GlobalList.begin(); }
513 const_global_iterator global_begin() const { return GlobalList.begin(); }
514 global_iterator global_end () { return GlobalList.end(); }
515 const_global_iterator global_end () const { return GlobalList.end(); }
516 bool global_empty() const { return GlobalList.empty(); }
518 iterator_range<global_iterator> globals() {
519 return iterator_range<global_iterator>(global_begin(), global_end());
521 iterator_range<const_global_iterator> globals() const {
522 return iterator_range<const_global_iterator>(global_begin(), global_end());
526 /// @name Function Iteration
529 iterator begin() { return FunctionList.begin(); }
530 const_iterator begin() const { return FunctionList.begin(); }
531 iterator end () { return FunctionList.end(); }
532 const_iterator end () const { return FunctionList.end(); }
533 size_t size() const { return FunctionList.size(); }
534 bool empty() const { return FunctionList.empty(); }
537 /// @name Alias Iteration
540 alias_iterator alias_begin() { return AliasList.begin(); }
541 const_alias_iterator alias_begin() const { return AliasList.begin(); }
542 alias_iterator alias_end () { return AliasList.end(); }
543 const_alias_iterator alias_end () const { return AliasList.end(); }
544 size_t alias_size () const { return AliasList.size(); }
545 bool alias_empty() const { return AliasList.empty(); }
547 iterator_range<alias_iterator> aliases() {
548 return iterator_range<alias_iterator>(alias_begin(), alias_end());
550 iterator_range<const_alias_iterator> aliases() const {
551 return iterator_range<const_alias_iterator>(alias_begin(), alias_end());
555 /// @name Named Metadata Iteration
558 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
559 const_named_metadata_iterator named_metadata_begin() const {
560 return NamedMDList.begin();
563 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
564 const_named_metadata_iterator named_metadata_end() const {
565 return NamedMDList.end();
568 size_t named_metadata_size() const { return NamedMDList.size(); }
569 bool named_metadata_empty() const { return NamedMDList.empty(); }
571 iterator_range<named_metadata_iterator> named_metadata() {
572 return iterator_range<named_metadata_iterator>(named_metadata_begin(),
573 named_metadata_end());
575 iterator_range<const_named_metadata_iterator> named_metadata() const {
576 return iterator_range<const_named_metadata_iterator>(named_metadata_begin(),
577 named_metadata_end());
581 /// @name Utility functions for printing and dumping Module objects
584 /// Print the module to an output stream with an optional
585 /// AssemblyAnnotationWriter.
586 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
588 /// Dump the module to stderr (for debugging).
591 /// This function causes all the subinstructions to "let go" of all references
592 /// that they are maintaining. This allows one to 'delete' a whole class at
593 /// a time, even though there may be circular references... first all
594 /// references are dropped, and all use counts go to zero. Then everything
595 /// is delete'd for real. Note that no operations are valid on an object
596 /// that has "dropped all references", except operator delete.
597 void dropAllReferences();
600 /// @name Utility functions for querying Debug information.
603 /// \brief Returns the Dwarf Version by checking module flags.
604 unsigned getDwarfVersion() const;
609 /// An raw_ostream inserter for modules.
610 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
615 // Create wrappers for C Binding types (see CBindingWrapping.h).
616 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
618 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
621 inline Module *unwrap(LLVMModuleProviderRef MP) {
622 return reinterpret_cast<Module*>(MP);
625 } // End llvm namespace