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 ModFlagBehaviorFirstVal = Error,
189 ModFlagBehaviorLastVal = AppendUnique
192 /// Checks if Value represents a valid ModFlagBehavior, and stores the
193 /// converted result in MFB.
194 static bool isValidModFlagBehavior(Value *V, ModFlagBehavior &MFB);
196 struct ModuleFlagEntry {
197 ModFlagBehavior Behavior;
200 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
201 : Behavior(B), Key(K), Val(V) {}
205 /// @name Member Variables
208 LLVMContext &Context; ///< The LLVMContext from which types and
209 ///< constants are allocated.
210 GlobalListType GlobalList; ///< The Global Variables in the module
211 FunctionListType FunctionList; ///< The Functions in the module
212 AliasListType AliasList; ///< The Aliases in the module
213 NamedMDListType NamedMDList; ///< The named metadata in the module
214 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
215 ValueSymbolTable *ValSymTab; ///< Symbol table for values
216 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
217 std::unique_ptr<GVMaterializer>
218 Materializer; ///< Used to materialize GlobalValues
219 std::string ModuleID; ///< Human readable identifier for the module
220 std::string TargetTriple; ///< Platform target triple Module compiled on
221 void *NamedMDSymTab; ///< NamedMDNode names.
222 // Allow lazy initialization in const method.
223 mutable RandomNumberGenerator *RNG; ///< The random number generator for this module.
225 // We need to keep the string because the C API expects us to own the string
227 // Since we have it, we also use an empty string to represent a module without
228 // a DataLayout. If it has a DataLayout, these variables are in sync and the
229 // string is just a cache of getDataLayout()->getStringRepresentation().
230 std::string DataLayoutStr;
233 friend class Constant;
236 /// @name Constructors
239 /// The Module constructor. Note that there is no default constructor. You
240 /// must provide a name for the module upon construction.
241 explicit Module(StringRef ModuleID, LLVMContext& C);
242 /// The module destructor. This will dropAllReferences.
246 /// @name Module Level Accessors
249 /// Get the module identifier which is, essentially, the name of the module.
250 /// @returns the module identifier as a string
251 const std::string &getModuleIdentifier() const { return ModuleID; }
253 /// Get the data layout string for the module's target platform. This is
254 /// equivalent to getDataLayout()->getStringRepresentation().
255 const std::string &getDataLayoutStr() const { return DataLayoutStr; }
257 /// Get the data layout for the module's target platform.
258 const DataLayout *getDataLayout() const;
260 /// Get the target triple which is a string describing the target host.
261 /// @returns a string containing the target triple.
262 const std::string &getTargetTriple() const { return TargetTriple; }
264 /// Get the global data context.
265 /// @returns LLVMContext - a container for LLVM's global information
266 LLVMContext &getContext() const { return Context; }
268 /// Get any module-scope inline assembly blocks.
269 /// @returns a string containing the module-scope inline assembly blocks.
270 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
272 /// Get the RandomNumberGenerator for this module. The RNG can be
273 /// seeded via -rng-seed=<uint64> and is salted with the ModuleID.
274 /// The returned RNG should not be shared across threads.
275 RandomNumberGenerator &getRNG() const;
278 /// @name Module Level Mutators
281 /// Set the module identifier.
282 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
284 /// Set the data layout
285 void setDataLayout(StringRef Desc);
286 void setDataLayout(const DataLayout *Other);
288 /// Set the target triple.
289 void setTargetTriple(StringRef T) { TargetTriple = T; }
291 /// Set the module-scope inline assembly blocks.
292 void setModuleInlineAsm(StringRef Asm) {
293 GlobalScopeAsm = Asm;
294 if (!GlobalScopeAsm.empty() &&
295 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
296 GlobalScopeAsm += '\n';
299 /// Append to the module-scope inline assembly blocks, automatically inserting
300 /// a separating newline if necessary.
301 void appendModuleInlineAsm(StringRef Asm) {
302 GlobalScopeAsm += Asm;
303 if (!GlobalScopeAsm.empty() &&
304 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
305 GlobalScopeAsm += '\n';
309 /// @name Generic Value Accessors
312 /// Return the global value in the module with the specified name, of
313 /// arbitrary type. This method returns null if a global with the specified
314 /// name is not found.
315 GlobalValue *getNamedValue(StringRef Name) const;
317 /// Return a unique non-zero ID for the specified metadata kind. This ID is
318 /// uniqued across modules in the current LLVMContext.
319 unsigned getMDKindID(StringRef Name) const;
321 /// Populate client supplied SmallVector with the name for custom metadata IDs
322 /// registered in this LLVMContext.
323 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
325 /// Return the type with the specified name, or null if there is none by that
327 StructType *getTypeByName(StringRef Name) const;
330 /// @name Function Accessors
333 /// Look up the specified function in the module symbol table. Four
335 /// 1. If it does not exist, add a prototype for the function and return it.
336 /// 2. If it exists, and has a local linkage, the existing function is
337 /// renamed and a new one is inserted.
338 /// 3. Otherwise, if the existing function has the correct prototype, return
339 /// the existing function.
340 /// 4. Finally, the function exists but has the wrong prototype: return the
341 /// function with a constantexpr cast to the right prototype.
342 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
343 AttributeSet AttributeList);
345 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
347 /// Look up the specified function in the module symbol table. If it does not
348 /// exist, add a prototype for the function and return it. This function
349 /// guarantees to return a constant of pointer to the specified function type
350 /// or a ConstantExpr BitCast of that type if the named function has a
351 /// different type. This version of the method takes a null terminated list of
352 /// function arguments, which makes it easier for clients to use.
353 Constant *getOrInsertFunction(StringRef Name,
354 AttributeSet AttributeList,
355 Type *RetTy, ...) END_WITH_NULL;
357 /// Same as above, but without the attributes.
358 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
361 /// Look up the specified function in the module symbol table. If it does not
362 /// exist, return null.
363 Function *getFunction(StringRef Name) const;
366 /// @name Global Variable Accessors
369 /// Look up the specified global variable in the module symbol table. If it
370 /// does not exist, return null. If AllowInternal is set to true, this
371 /// function will return types that have InternalLinkage. By default, these
372 /// types are not returned.
373 const GlobalVariable *getGlobalVariable(StringRef Name,
374 bool AllowInternal = false) const {
375 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
378 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
380 /// Return the global variable in the module with the specified name, of
381 /// arbitrary type. This method returns null if a global with the specified
382 /// name is not found.
383 GlobalVariable *getNamedGlobal(StringRef Name) {
384 return getGlobalVariable(Name, true);
386 const GlobalVariable *getNamedGlobal(StringRef Name) const {
387 return const_cast<Module *>(this)->getNamedGlobal(Name);
390 /// Look up the specified global in the module symbol table.
391 /// 1. If it does not exist, add a declaration of the global and return it.
392 /// 2. Else, the global exists but has the wrong type: return the function
393 /// with a constantexpr cast to the right type.
394 /// 3. Finally, if the existing global is the correct declaration, return
395 /// the existing global.
396 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
399 /// @name Global Alias Accessors
402 /// Return the global alias in the module with the specified name, of
403 /// arbitrary type. This method returns null if a global with the specified
404 /// name is not found.
405 GlobalAlias *getNamedAlias(StringRef Name) const;
408 /// @name Named Metadata Accessors
411 /// Return the first NamedMDNode in the module with the specified name. This
412 /// method returns null if a NamedMDNode with the specified name is not found.
413 NamedMDNode *getNamedMetadata(const Twine &Name) const;
415 /// Return the named MDNode in the module with the specified name. This method
416 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
418 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
420 /// Remove the given NamedMDNode from this module and delete it.
421 void eraseNamedMetadata(NamedMDNode *NMD);
424 /// @name Comdat Accessors
427 /// Return the Comdat in the module with the specified name. It is created
428 /// if it didn't already exist.
429 Comdat *getOrInsertComdat(StringRef Name);
432 /// @name Module Flags Accessors
435 /// Returns the module flags in the provided vector.
436 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
438 /// Return the corresponding value if Key appears in module flags, otherwise
440 Value *getModuleFlag(StringRef Key) const;
442 /// Returns the NamedMDNode in the module that represents module-level flags.
443 /// This method returns null if there are no module-level flags.
444 NamedMDNode *getModuleFlagsMetadata() const;
446 /// Returns the NamedMDNode in the module that represents module-level flags.
447 /// If module-level flags aren't found, it creates the named metadata that
449 NamedMDNode *getOrInsertModuleFlagsMetadata();
451 /// Add a module-level flag to the module-level flags metadata. It will create
452 /// the module-level flags named metadata if it doesn't already exist.
453 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
454 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
455 void addModuleFlag(MDNode *Node);
458 /// @name Materialization
461 /// Sets the GVMaterializer to GVM. This module must not yet have a
462 /// Materializer. To reset the materializer for a module that already has one,
463 /// call MaterializeAllPermanently first. Destroying this module will destroy
464 /// its materializer without materializing any more GlobalValues. Without
465 /// destroying the Module, there is no way to detach or destroy a materializer
466 /// without materializing all the GVs it controls, to avoid leaving orphan
467 /// unmaterialized GVs.
468 void setMaterializer(GVMaterializer *GVM);
469 /// Retrieves the GVMaterializer, if any, for this Module.
470 GVMaterializer *getMaterializer() const { return Materializer.get(); }
472 /// True if the definition of GV has yet to be materializedfrom the
474 bool isMaterializable(const GlobalValue *GV) const;
475 /// Returns true if this GV was loaded from this Module's GVMaterializer and
476 /// the GVMaterializer knows how to dematerialize the GV.
477 bool isDematerializable(const GlobalValue *GV) const;
479 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
480 /// returns true and fills in the optional string with information about the
481 /// problem. If successful, this returns false.
482 bool Materialize(GlobalValue *GV, std::string *ErrInfo = nullptr);
483 /// If the GlobalValue is read in, and if the GVMaterializer supports it,
484 /// release the memory for the function, and set it up to be materialized
485 /// lazily. If !isDematerializable(), this method is a noop.
486 void Dematerialize(GlobalValue *GV);
488 /// Make sure all GlobalValues in this Module are fully read.
489 std::error_code materializeAll();
491 /// Make sure all GlobalValues in this Module are fully read and clear the
492 /// Materializer. If the module is corrupt, this DOES NOT clear the old
494 std::error_code materializeAllPermanently();
497 /// @name Direct access to the globals list, functions list, and symbol table
500 /// Get the Module's list of global variables (constant).
501 const GlobalListType &getGlobalList() const { return GlobalList; }
502 /// Get the Module's list of global variables.
503 GlobalListType &getGlobalList() { return GlobalList; }
504 static iplist<GlobalVariable> Module::*getSublistAccess(GlobalVariable*) {
505 return &Module::GlobalList;
507 /// Get the Module's list of functions (constant).
508 const FunctionListType &getFunctionList() const { return FunctionList; }
509 /// Get the Module's list of functions.
510 FunctionListType &getFunctionList() { return FunctionList; }
511 static iplist<Function> Module::*getSublistAccess(Function*) {
512 return &Module::FunctionList;
514 /// Get the Module's list of aliases (constant).
515 const AliasListType &getAliasList() const { return AliasList; }
516 /// Get the Module's list of aliases.
517 AliasListType &getAliasList() { return AliasList; }
518 static iplist<GlobalAlias> Module::*getSublistAccess(GlobalAlias*) {
519 return &Module::AliasList;
521 /// Get the Module's list of named metadata (constant).
522 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
523 /// Get the Module's list of named metadata.
524 NamedMDListType &getNamedMDList() { return NamedMDList; }
525 static ilist<NamedMDNode> Module::*getSublistAccess(NamedMDNode*) {
526 return &Module::NamedMDList;
528 /// Get the symbol table of global variable and function identifiers
529 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
530 /// Get the Module's symbol table of global variable and function identifiers.
531 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
532 /// Get the Module's symbol table for COMDATs (constant).
533 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
534 /// Get the Module's symbol table for COMDATs.
535 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
538 /// @name Global Variable Iteration
541 global_iterator global_begin() { return GlobalList.begin(); }
542 const_global_iterator global_begin() const { return GlobalList.begin(); }
543 global_iterator global_end () { return GlobalList.end(); }
544 const_global_iterator global_end () const { return GlobalList.end(); }
545 bool global_empty() const { return GlobalList.empty(); }
547 iterator_range<global_iterator> globals() {
548 return iterator_range<global_iterator>(global_begin(), global_end());
550 iterator_range<const_global_iterator> globals() const {
551 return iterator_range<const_global_iterator>(global_begin(), global_end());
555 /// @name Function Iteration
558 iterator begin() { return FunctionList.begin(); }
559 const_iterator begin() const { return FunctionList.begin(); }
560 iterator end () { return FunctionList.end(); }
561 const_iterator end () const { return FunctionList.end(); }
562 reverse_iterator rbegin() { return FunctionList.rbegin(); }
563 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
564 reverse_iterator rend() { return FunctionList.rend(); }
565 const_reverse_iterator rend() const { return FunctionList.rend(); }
566 size_t size() const { return FunctionList.size(); }
567 bool empty() const { return FunctionList.empty(); }
570 /// @name Alias Iteration
573 alias_iterator alias_begin() { return AliasList.begin(); }
574 const_alias_iterator alias_begin() const { return AliasList.begin(); }
575 alias_iterator alias_end () { return AliasList.end(); }
576 const_alias_iterator alias_end () const { return AliasList.end(); }
577 size_t alias_size () const { return AliasList.size(); }
578 bool alias_empty() const { return AliasList.empty(); }
580 iterator_range<alias_iterator> aliases() {
581 return iterator_range<alias_iterator>(alias_begin(), alias_end());
583 iterator_range<const_alias_iterator> aliases() const {
584 return iterator_range<const_alias_iterator>(alias_begin(), alias_end());
588 /// @name Named Metadata Iteration
591 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
592 const_named_metadata_iterator named_metadata_begin() const {
593 return NamedMDList.begin();
596 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
597 const_named_metadata_iterator named_metadata_end() const {
598 return NamedMDList.end();
601 size_t named_metadata_size() const { return NamedMDList.size(); }
602 bool named_metadata_empty() const { return NamedMDList.empty(); }
604 iterator_range<named_metadata_iterator> named_metadata() {
605 return iterator_range<named_metadata_iterator>(named_metadata_begin(),
606 named_metadata_end());
608 iterator_range<const_named_metadata_iterator> named_metadata() const {
609 return iterator_range<const_named_metadata_iterator>(named_metadata_begin(),
610 named_metadata_end());
614 /// @name Utility functions for printing and dumping Module objects
617 /// Print the module to an output stream with an optional
618 /// AssemblyAnnotationWriter.
619 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW) const;
621 /// Dump the module to stderr (for debugging).
624 /// This function causes all the subinstructions to "let go" of all references
625 /// that they are maintaining. This allows one to 'delete' a whole class at
626 /// a time, even though there may be circular references... first all
627 /// references are dropped, and all use counts go to zero. Then everything
628 /// is delete'd for real. Note that no operations are valid on an object
629 /// that has "dropped all references", except operator delete.
630 void dropAllReferences();
633 /// @name Utility functions for querying Debug information.
636 /// \brief Returns the Dwarf Version by checking module flags.
637 unsigned getDwarfVersion() const;
642 /// An raw_ostream inserter for modules.
643 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
648 // Create wrappers for C Binding types (see CBindingWrapping.h).
649 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
651 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
654 inline Module *unwrap(LLVMModuleProviderRef MP) {
655 return reinterpret_cast<Module*>(MP);
658 } // End llvm namespace