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/Comdat.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GlobalAlias.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/Support/CBindingWrapping.h"
26 #include "llvm/Support/DataTypes.h"
27 #include <system_error>
33 class RandomNumberGenerator;
35 template<typename T> struct DenseMapInfo;
36 template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
38 template<> struct ilist_traits<Function>
39 : public SymbolTableListTraits<Function, Module> {
41 // createSentinel is used to get hold of the node that marks the end of the
42 // list... (same trick used here as in ilist_traits<Instruction>)
43 Function *createSentinel() const {
44 return static_cast<Function*>(&Sentinel);
46 static void destroySentinel(Function*) {}
48 Function *provideInitialHead() const { return createSentinel(); }
49 Function *ensureHead(Function*) const { return createSentinel(); }
50 static void noteHead(Function*, Function*) {}
53 mutable ilist_node<Function> Sentinel;
56 template<> struct ilist_traits<GlobalVariable>
57 : public SymbolTableListTraits<GlobalVariable, Module> {
58 // createSentinel is used to create a node that marks the end of the list.
59 GlobalVariable *createSentinel() const {
60 return static_cast<GlobalVariable*>(&Sentinel);
62 static void destroySentinel(GlobalVariable*) {}
64 GlobalVariable *provideInitialHead() const { return createSentinel(); }
65 GlobalVariable *ensureHead(GlobalVariable*) const { return createSentinel(); }
66 static void noteHead(GlobalVariable*, GlobalVariable*) {}
68 mutable ilist_node<GlobalVariable> Sentinel;
71 template<> struct ilist_traits<GlobalAlias>
72 : public SymbolTableListTraits<GlobalAlias, Module> {
73 // createSentinel is used to create a node that marks the end of the list.
74 GlobalAlias *createSentinel() const {
75 return static_cast<GlobalAlias*>(&Sentinel);
77 static void destroySentinel(GlobalAlias*) {}
79 GlobalAlias *provideInitialHead() const { return createSentinel(); }
80 GlobalAlias *ensureHead(GlobalAlias*) const { return createSentinel(); }
81 static void noteHead(GlobalAlias*, GlobalAlias*) {}
83 mutable ilist_node<GlobalAlias> Sentinel;
86 template<> struct ilist_traits<NamedMDNode>
87 : public ilist_default_traits<NamedMDNode> {
88 // createSentinel is used to get hold of a node that marks the end of
90 NamedMDNode *createSentinel() const {
91 return static_cast<NamedMDNode*>(&Sentinel);
93 static void destroySentinel(NamedMDNode*) {}
95 NamedMDNode *provideInitialHead() const { return createSentinel(); }
96 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
97 static void noteHead(NamedMDNode*, NamedMDNode*) {}
98 void addNodeToList(NamedMDNode *) {}
99 void removeNodeFromList(NamedMDNode *) {}
101 mutable ilist_node<NamedMDNode> Sentinel;
104 /// A Module instance is used to store all the information related to an
105 /// LLVM module. Modules are the top level container of all other LLVM
106 /// Intermediate Representation (IR) objects. Each module directly contains a
107 /// list of globals variables, a list of functions, a list of libraries (or
108 /// other modules) this module depends on, a symbol table, and various data
109 /// about the target's characteristics.
111 /// A module maintains a GlobalValRefMap object that is used to hold all
112 /// constant references to global variables in the module. When a global
113 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
114 /// @brief The main container class for the LLVM Intermediate Representation.
116 /// @name Types And Enumerations
119 /// The type for the list of global variables.
120 typedef iplist<GlobalVariable> GlobalListType;
121 /// The type for the list of functions.
122 typedef iplist<Function> FunctionListType;
123 /// The type for the list of aliases.
124 typedef iplist<GlobalAlias> AliasListType;
125 /// The type for the list of named metadata.
126 typedef ilist<NamedMDNode> NamedMDListType;
127 /// The type of the comdat "symbol" table.
128 typedef StringMap<Comdat> ComdatSymTabType;
130 /// The Global Variable iterator.
131 typedef GlobalListType::iterator global_iterator;
132 /// The Global Variable constant iterator.
133 typedef GlobalListType::const_iterator const_global_iterator;
135 /// The Function iterators.
136 typedef FunctionListType::iterator iterator;
137 /// The Function constant iterator
138 typedef FunctionListType::const_iterator const_iterator;
140 /// The Function reverse iterator.
141 typedef FunctionListType::reverse_iterator reverse_iterator;
142 /// The Function constant reverse iterator.
143 typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
145 /// The Global Alias iterators.
146 typedef AliasListType::iterator alias_iterator;
147 /// The Global Alias constant iterator
148 typedef AliasListType::const_iterator const_alias_iterator;
150 /// The named metadata iterators.
151 typedef NamedMDListType::iterator named_metadata_iterator;
152 /// The named metadata constant interators.
153 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
155 /// This enumeration defines the supported behaviors of module flags.
156 enum ModFlagBehavior {
157 /// Emits an error if two values disagree, otherwise the resulting value is
158 /// that of the operands.
161 /// Emits a warning if two values disagree. The result value will be the
162 /// operand for the flag from the first module being linked.
165 /// Adds a requirement that another module flag be present and have a
166 /// specified value after linking is performed. The value must be a metadata
167 /// pair, where the first element of the pair is the ID of the module flag
168 /// to be restricted, and the second element of the pair is the value the
169 /// module flag should be restricted to. This behavior can be used to
170 /// restrict the allowable results (via triggering of an error) of linking
171 /// IDs with the **Override** behavior.
174 /// Uses the specified value, regardless of the behavior or value of the
175 /// other module. If both modules specify **Override**, but the values
176 /// differ, an error will be emitted.
179 /// Appends the two values, which are required to be metadata nodes.
182 /// Appends the two values, which are required to be metadata
183 /// nodes. However, duplicate entries in the second list are dropped
184 /// during the append operation.
188 struct ModuleFlagEntry {
189 ModFlagBehavior Behavior;
192 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
193 : Behavior(B), Key(K), Val(V) {}
197 /// @name Member Variables
200 LLVMContext &Context; ///< The LLVMContext from which types and
201 ///< constants are allocated.
202 GlobalListType GlobalList; ///< The Global Variables in the module
203 FunctionListType FunctionList; ///< The Functions in the module
204 AliasListType AliasList; ///< The Aliases in the module
205 NamedMDListType NamedMDList; ///< The named metadata in the module
206 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
207 ValueSymbolTable *ValSymTab; ///< Symbol table for values
208 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
209 std::unique_ptr<GVMaterializer>
210 Materializer; ///< Used to materialize GlobalValues
211 std::string ModuleID; ///< Human readable identifier for the module
212 std::string TargetTriple; ///< Platform target triple Module compiled on
213 void *NamedMDSymTab; ///< NamedMDNode names.
214 // Allow lazy initialization in const method.
215 mutable RandomNumberGenerator *RNG; ///< The random number generator for this module.
217 // We need to keep the string because the C API expects us to own the string
219 // Since we have it, we also use an empty string to represent a module without
220 // a DataLayout. If it has a DataLayout, these variables are in sync and the
221 // string is just a cache of getDataLayout()->getStringRepresentation().
222 std::string DataLayoutStr;
225 friend class Constant;
228 /// @name Constructors
231 /// The Module constructor. Note that there is no default constructor. You
232 /// must provide a name for the module upon construction.
233 explicit Module(StringRef ModuleID, LLVMContext& C);
234 /// The module destructor. This will dropAllReferences.
238 /// @name Module Level Accessors
241 /// Get the module identifier which is, essentially, the name of the module.
242 /// @returns the module identifier as a string
243 const std::string &getModuleIdentifier() const { return ModuleID; }
245 /// Get the data layout string for the module's target platform. This is
246 /// equivalent to getDataLayout()->getStringRepresentation().
247 const std::string &getDataLayoutStr() const { return DataLayoutStr; }
249 /// Get the data layout for the module's target platform.
250 const DataLayout *getDataLayout() const;
252 /// Get the target triple which is a string describing the target host.
253 /// @returns a string containing the target triple.
254 const std::string &getTargetTriple() const { return TargetTriple; }
256 /// Get the global data context.
257 /// @returns LLVMContext - a container for LLVM's global information
258 LLVMContext &getContext() const { return Context; }
260 /// Get any module-scope inline assembly blocks.
261 /// @returns a string containing the module-scope inline assembly blocks.
262 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
264 /// Get the RandomNumberGenerator for this module. The RNG can be
265 /// seeded via -rng-seed=<uint64> and is salted with the ModuleID.
266 /// The returned RNG should not be shared across threads.
267 RandomNumberGenerator &getRNG() const;
270 /// @name Module Level Mutators
273 /// Set the module identifier.
274 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
276 /// Set the data layout
277 void setDataLayout(StringRef Desc);
278 void setDataLayout(const DataLayout *Other);
280 /// Set the target triple.
281 void setTargetTriple(StringRef T) { TargetTriple = T; }
283 /// Set the module-scope inline assembly blocks.
284 void setModuleInlineAsm(StringRef Asm) {
285 GlobalScopeAsm = Asm;
286 if (!GlobalScopeAsm.empty() &&
287 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
288 GlobalScopeAsm += '\n';
291 /// Append to the module-scope inline assembly blocks, automatically inserting
292 /// a separating newline if necessary.
293 void appendModuleInlineAsm(StringRef Asm) {
294 GlobalScopeAsm += Asm;
295 if (!GlobalScopeAsm.empty() &&
296 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
297 GlobalScopeAsm += '\n';
301 /// @name Generic Value Accessors
304 /// Return the global value in the module with the specified name, of
305 /// arbitrary type. This method returns null if a global with the specified
306 /// name is not found.
307 GlobalValue *getNamedValue(StringRef Name) const;
309 /// Return a unique non-zero ID for the specified metadata kind. This ID is
310 /// uniqued across modules in the current LLVMContext.
311 unsigned getMDKindID(StringRef Name) const;
313 /// Populate client supplied SmallVector with the name for custom metadata IDs
314 /// registered in this LLVMContext.
315 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
317 /// Return the type with the specified name, or null if there is none by that
319 StructType *getTypeByName(StringRef Name) const;
322 /// @name Function Accessors
325 /// Look up the specified function in the module symbol table. Four
327 /// 1. If it does not exist, add a prototype for the function and return it.
328 /// 2. If it exists, and has a local linkage, the existing function is
329 /// renamed and a new one is inserted.
330 /// 3. Otherwise, if the existing function has the correct prototype, return
331 /// the existing function.
332 /// 4. Finally, the function exists but has the wrong prototype: return the
333 /// function with a constantexpr cast to the right prototype.
334 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
335 AttributeSet AttributeList);
337 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
339 /// Look up the specified function in the module symbol table. If it does not
340 /// exist, add a prototype for the function and return it. This function
341 /// guarantees to return a constant of pointer to the specified function type
342 /// or a ConstantExpr BitCast of that type if the named function has a
343 /// different type. This version of the method takes a null terminated list of
344 /// function arguments, which makes it easier for clients to use.
345 Constant *getOrInsertFunction(StringRef Name,
346 AttributeSet AttributeList,
347 Type *RetTy, ...) END_WITH_NULL;
349 /// Same as above, but without the attributes.
350 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
353 /// Look up the specified function in the module symbol table. If it does not
354 /// exist, return null.
355 Function *getFunction(StringRef Name) const;
358 /// @name Global Variable Accessors
361 /// Look up the specified global variable in the module symbol table. If it
362 /// does not exist, return null. If AllowInternal is set to true, this
363 /// function will return types that have InternalLinkage. By default, these
364 /// types are not returned.
365 const GlobalVariable *getGlobalVariable(StringRef Name,
366 bool AllowInternal = false) const {
367 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
370 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
372 /// Return the global variable in the module with the specified name, of
373 /// arbitrary type. This method returns null if a global with the specified
374 /// name is not found.
375 GlobalVariable *getNamedGlobal(StringRef Name) {
376 return getGlobalVariable(Name, true);
378 const GlobalVariable *getNamedGlobal(StringRef Name) const {
379 return const_cast<Module *>(this)->getNamedGlobal(Name);
382 /// Look up the specified global in the module symbol table.
383 /// 1. If it does not exist, add a declaration of the global and return it.
384 /// 2. Else, the global exists but has the wrong type: return the function
385 /// with a constantexpr cast to the right type.
386 /// 3. Finally, if the existing global is the correct declaration, return
387 /// the existing global.
388 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
391 /// @name Global Alias Accessors
394 /// Return the global alias in the module with the specified name, of
395 /// arbitrary type. This method returns null if a global with the specified
396 /// name is not found.
397 GlobalAlias *getNamedAlias(StringRef Name) const;
400 /// @name Named Metadata Accessors
403 /// Return the first NamedMDNode in the module with the specified name. This
404 /// method returns null if a NamedMDNode with the specified name is not found.
405 NamedMDNode *getNamedMetadata(const Twine &Name) const;
407 /// Return the named MDNode in the module with the specified name. This method
408 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
410 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
412 /// Remove the given NamedMDNode from this module and delete it.
413 void eraseNamedMetadata(NamedMDNode *NMD);
416 /// @name Comdat Accessors
419 /// Return the Comdat in the module with the specified name. It is created
420 /// if it didn't already exist.
421 Comdat *getOrInsertComdat(StringRef Name);
424 /// @name Module Flags Accessors
427 /// Returns the module flags in the provided vector.
428 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
430 /// Return the corresponding value if Key appears in module flags, otherwise
432 Value *getModuleFlag(StringRef Key) const;
434 /// Returns the NamedMDNode in the module that represents module-level flags.
435 /// This method returns null if there are no module-level flags.
436 NamedMDNode *getModuleFlagsMetadata() const;
438 /// Returns the NamedMDNode in the module that represents module-level flags.
439 /// If module-level flags aren't found, it creates the named metadata that
441 NamedMDNode *getOrInsertModuleFlagsMetadata();
443 /// Add a module-level flag to the module-level flags metadata. It will create
444 /// the module-level flags named metadata if it doesn't already exist.
445 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
446 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
447 void addModuleFlag(MDNode *Node);
450 /// @name Materialization
453 /// Sets the GVMaterializer to GVM. This module must not yet have a
454 /// Materializer. To reset the materializer for a module that already has one,
455 /// call MaterializeAllPermanently first. Destroying this module will destroy
456 /// its materializer without materializing any more GlobalValues. Without
457 /// destroying the Module, there is no way to detach or destroy a materializer
458 /// without materializing all the GVs it controls, to avoid leaving orphan
459 /// unmaterialized GVs.
460 void setMaterializer(GVMaterializer *GVM);
461 /// Retrieves the GVMaterializer, if any, for this Module.
462 GVMaterializer *getMaterializer() const { return Materializer.get(); }
464 /// True if the definition of GV has yet to be materializedfrom the
466 bool isMaterializable(const GlobalValue *GV) const;
467 /// Returns true if this GV was loaded from this Module's GVMaterializer and
468 /// the GVMaterializer knows how to dematerialize the GV.
469 bool isDematerializable(const GlobalValue *GV) const;
471 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
472 /// returns true and fills in the optional string with information about the
473 /// problem. If successful, this returns false.
474 bool Materialize(GlobalValue *GV, std::string *ErrInfo = nullptr);
475 /// If the GlobalValue is read in, and if the GVMaterializer supports it,
476 /// release the memory for the function, and set it up to be materialized
477 /// lazily. If !isDematerializable(), this method is a noop.
478 void Dematerialize(GlobalValue *GV);
480 /// Make sure all GlobalValues in this Module are fully read.
481 std::error_code materializeAll();
483 /// Make sure all GlobalValues in this Module are fully read and clear the
484 /// Materializer. If the module is corrupt, this DOES NOT clear the old
486 std::error_code materializeAllPermanently(bool ReleaseBuffer = false);
489 /// @name Direct access to the globals list, functions list, and symbol table
492 /// Get the Module's list of global variables (constant).
493 const GlobalListType &getGlobalList() const { return GlobalList; }
494 /// Get the Module's list of global variables.
495 GlobalListType &getGlobalList() { return GlobalList; }
496 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
497 return &Module::GlobalList;
499 /// Get the Module's list of functions (constant).
500 const FunctionListType &getFunctionList() const { return FunctionList; }
501 /// Get the Module's list of functions.
502 FunctionListType &getFunctionList() { return FunctionList; }
503 static iplist<Function> Module::*getSublistAccess(Function*) {
504 return &Module::FunctionList;
506 /// Get the Module's list of aliases (constant).
507 const AliasListType &getAliasList() const { return AliasList; }
508 /// Get the Module's list of aliases.
509 AliasListType &getAliasList() { return AliasList; }
510 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
511 return &Module::AliasList;
513 /// Get the Module's list of named metadata (constant).
514 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
515 /// Get the Module's list of named metadata.
516 NamedMDListType &getNamedMDList() { return NamedMDList; }
517 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
518 return &Module::NamedMDList;
520 /// Get the symbol table of global variable and function identifiers
521 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
522 /// Get the Module's symbol table of global variable and function identifiers.
523 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
524 /// Get the Module's symbol table for COMDATs (constant).
525 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
526 /// Get the Module's symbol table for COMDATs.
527 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
530 /// @name Global Variable Iteration
533 global_iterator global_begin() { return GlobalList.begin(); }
534 const_global_iterator global_begin() const { return GlobalList.begin(); }
535 global_iterator global_end () { return GlobalList.end(); }
536 const_global_iterator global_end () const { return GlobalList.end(); }
537 bool global_empty() const { return GlobalList.empty(); }
539 iterator_range<global_iterator> globals() {
540 return iterator_range<global_iterator>(global_begin(), global_end());
542 iterator_range<const_global_iterator> globals() const {
543 return iterator_range<const_global_iterator>(global_begin(), global_end());
547 /// @name Function Iteration
550 iterator begin() { return FunctionList.begin(); }
551 const_iterator begin() const { return FunctionList.begin(); }
552 iterator end () { return FunctionList.end(); }
553 const_iterator end () const { return FunctionList.end(); }
554 reverse_iterator rbegin() { return FunctionList.rbegin(); }
555 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
556 reverse_iterator rend() { return FunctionList.rend(); }
557 const_reverse_iterator rend() const { return FunctionList.rend(); }
558 size_t size() const { return FunctionList.size(); }
559 bool empty() const { return FunctionList.empty(); }
562 /// @name Alias Iteration
565 alias_iterator alias_begin() { return AliasList.begin(); }
566 const_alias_iterator alias_begin() const { return AliasList.begin(); }
567 alias_iterator alias_end () { return AliasList.end(); }
568 const_alias_iterator alias_end () const { return AliasList.end(); }
569 size_t alias_size () const { return AliasList.size(); }
570 bool alias_empty() const { return AliasList.empty(); }
572 iterator_range<alias_iterator> aliases() {
573 return iterator_range<alias_iterator>(alias_begin(), alias_end());
575 iterator_range<const_alias_iterator> aliases() const {
576 return iterator_range<const_alias_iterator>(alias_begin(), alias_end());
580 /// @name Named Metadata Iteration
583 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
584 const_named_metadata_iterator named_metadata_begin() const {
585 return NamedMDList.begin();
588 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
589 const_named_metadata_iterator named_metadata_end() const {
590 return NamedMDList.end();
593 size_t named_metadata_size() const { return NamedMDList.size(); }
594 bool named_metadata_empty() const { return NamedMDList.empty(); }
596 iterator_range<named_metadata_iterator> named_metadata() {
597 return iterator_range<named_metadata_iterator>(named_metadata_begin(),
598 named_metadata_end());
600 iterator_range<const_named_metadata_iterator> named_metadata() const {
601 return iterator_range<const_named_metadata_iterator>(named_metadata_begin(),
602 named_metadata_end());
606 /// @name Utility functions for printing and dumping Module objects
609 /// Print the module to an output stream with an optional
610 /// AssemblyAnnotationWriter.
611 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
613 /// Dump the module to stderr (for debugging).
616 /// This function causes all the subinstructions to "let go" of all references
617 /// that they are maintaining. This allows one to 'delete' a whole class at
618 /// a time, even though there may be circular references... first all
619 /// references are dropped, and all use counts go to zero. Then everything
620 /// is delete'd for real. Note that no operations are valid on an object
621 /// that has "dropped all references", except operator delete.
622 void dropAllReferences();
625 /// @name Utility functions for querying Debug information.
628 /// \brief Returns the Dwarf Version by checking module flags.
629 unsigned getDwarfVersion() const;
634 /// An raw_ostream inserter for modules.
635 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
640 // Create wrappers for C Binding types (see CBindingWrapping.h).
641 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
643 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
646 inline Module *unwrap(LLVMModuleProviderRef MP) {
647 return reinterpret_cast<Module*>(MP);
650 } // End llvm namespace