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/CodeGen.h"
27 #include "llvm/Support/DataTypes.h"
28 #include <system_error>
34 class RandomNumberGenerator;
37 template<> struct ilist_traits<NamedMDNode>
38 : public ilist_default_traits<NamedMDNode> {
39 // createSentinel is used to get hold of a node that marks the end of
41 NamedMDNode *createSentinel() const {
42 return static_cast<NamedMDNode*>(&Sentinel);
44 static void destroySentinel(NamedMDNode*) {}
46 NamedMDNode *provideInitialHead() const { return createSentinel(); }
47 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
48 static void noteHead(NamedMDNode*, NamedMDNode*) {}
49 void addNodeToList(NamedMDNode *) {}
50 void removeNodeFromList(NamedMDNode *) {}
53 mutable ilist_node<NamedMDNode> Sentinel;
56 /// A Module instance is used to store all the information related to an
57 /// LLVM module. Modules are the top level container of all other LLVM
58 /// Intermediate Representation (IR) objects. Each module directly contains a
59 /// list of globals variables, a list of functions, a list of libraries (or
60 /// other modules) this module depends on, a symbol table, and various data
61 /// about the target's characteristics.
63 /// A module maintains a GlobalValRefMap object that is used to hold all
64 /// constant references to global variables in the module. When a global
65 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
66 /// @brief The main container class for the LLVM Intermediate Representation.
68 /// @name Types And Enumerations
71 /// The type for the list of global variables.
72 typedef SymbolTableList<GlobalVariable> GlobalListType;
73 /// The type for the list of functions.
74 typedef SymbolTableList<Function> FunctionListType;
75 /// The type for the list of aliases.
76 typedef SymbolTableList<GlobalAlias> AliasListType;
77 /// The type for the list of named metadata.
78 typedef ilist<NamedMDNode> NamedMDListType;
79 /// The type of the comdat "symbol" table.
80 typedef StringMap<Comdat> ComdatSymTabType;
82 /// The Global Variable iterator.
83 typedef GlobalListType::iterator global_iterator;
84 /// The Global Variable constant iterator.
85 typedef GlobalListType::const_iterator const_global_iterator;
87 /// The Function iterators.
88 typedef FunctionListType::iterator iterator;
89 /// The Function constant iterator
90 typedef FunctionListType::const_iterator const_iterator;
92 /// The Function reverse iterator.
93 typedef FunctionListType::reverse_iterator reverse_iterator;
94 /// The Function constant reverse iterator.
95 typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
97 /// The Global Alias iterators.
98 typedef AliasListType::iterator alias_iterator;
99 /// The Global Alias constant iterator
100 typedef AliasListType::const_iterator const_alias_iterator;
102 /// The named metadata iterators.
103 typedef NamedMDListType::iterator named_metadata_iterator;
104 /// The named metadata constant iterators.
105 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
107 /// This enumeration defines the supported behaviors of module flags.
108 enum ModFlagBehavior {
109 /// Emits an error if two values disagree, otherwise the resulting value is
110 /// that of the operands.
113 /// Emits a warning if two values disagree. The result value will be the
114 /// operand for the flag from the first module being linked.
117 /// Adds a requirement that another module flag be present and have a
118 /// specified value after linking is performed. The value must be a metadata
119 /// pair, where the first element of the pair is the ID of the module flag
120 /// to be restricted, and the second element of the pair is the value the
121 /// module flag should be restricted to. This behavior can be used to
122 /// restrict the allowable results (via triggering of an error) of linking
123 /// IDs with the **Override** behavior.
126 /// Uses the specified value, regardless of the behavior or value of the
127 /// other module. If both modules specify **Override**, but the values
128 /// differ, an error will be emitted.
131 /// Appends the two values, which are required to be metadata nodes.
134 /// Appends the two values, which are required to be metadata
135 /// nodes. However, duplicate entries in the second list are dropped
136 /// during the append operation.
140 ModFlagBehaviorFirstVal = Error,
141 ModFlagBehaviorLastVal = AppendUnique
144 /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
145 /// converted result in MFB.
146 static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
148 struct ModuleFlagEntry {
149 ModFlagBehavior Behavior;
152 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
153 : Behavior(B), Key(K), Val(V) {}
157 /// @name Member Variables
160 LLVMContext &Context; ///< The LLVMContext from which types and
161 ///< constants are allocated.
162 GlobalListType GlobalList; ///< The Global Variables in the module
163 FunctionListType FunctionList; ///< The Functions in the module
164 AliasListType AliasList; ///< The Aliases in the module
165 NamedMDListType NamedMDList; ///< The named metadata in the module
166 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
167 ValueSymbolTable *ValSymTab; ///< Symbol table for values
168 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
169 std::unique_ptr<GVMaterializer>
170 Materializer; ///< Used to materialize GlobalValues
171 std::string ModuleID; ///< Human readable identifier for the module
172 std::string TargetTriple; ///< Platform target triple Module compiled on
173 ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
174 void *NamedMDSymTab; ///< NamedMDNode names.
175 DataLayout DL; ///< DataLayout associated with the module
177 friend class Constant;
180 /// @name Constructors
183 /// The Module constructor. Note that there is no default constructor. You
184 /// must provide a name for the module upon construction.
185 explicit Module(StringRef ModuleID, LLVMContext& C);
186 /// The module destructor. This will dropAllReferences.
190 /// @name Module Level Accessors
193 /// Get the module identifier which is, essentially, the name of the module.
194 /// @returns the module identifier as a string
195 const std::string &getModuleIdentifier() const { return ModuleID; }
197 /// \brief Get a short "name" for the module.
199 /// This is useful for debugging or logging. It is essentially a convenience
200 /// wrapper around getModuleIdentifier().
201 StringRef getName() const { return ModuleID; }
203 /// Get the data layout string for the module's target platform. This is
204 /// equivalent to getDataLayout()->getStringRepresentation().
205 const std::string &getDataLayoutStr() const {
206 return DL.getStringRepresentation();
209 /// Get the data layout for the module's target platform.
210 const DataLayout &getDataLayout() const;
212 /// Get the target triple which is a string describing the target host.
213 /// @returns a string containing the target triple.
214 const std::string &getTargetTriple() const { return TargetTriple; }
216 /// Get the global data context.
217 /// @returns LLVMContext - a container for LLVM's global information
218 LLVMContext &getContext() const { return Context; }
220 /// Get any module-scope inline assembly blocks.
221 /// @returns a string containing the module-scope inline assembly blocks.
222 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
224 /// Get a RandomNumberGenerator salted for use with this module. The
225 /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
226 /// ModuleID and the provided pass salt. The returned RNG should not
227 /// be shared across threads or passes.
229 /// A unique RNG per pass ensures a reproducible random stream even
230 /// when other randomness consuming passes are added or removed. In
231 /// addition, the random stream will be reproducible across LLVM
232 /// versions when the pass does not change.
233 RandomNumberGenerator *createRNG(const Pass* P) const;
236 /// @name Module Level Mutators
239 /// Set the module identifier.
240 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
242 /// Set the data layout
243 void setDataLayout(StringRef Desc);
244 void setDataLayout(const DataLayout &Other);
246 /// Set the target triple.
247 void setTargetTriple(StringRef T) { TargetTriple = T; }
249 /// Set the module-scope inline assembly blocks.
250 /// A trailing newline is added if the input doesn't have one.
251 void setModuleInlineAsm(StringRef Asm) {
252 GlobalScopeAsm = Asm;
253 if (!GlobalScopeAsm.empty() &&
254 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
255 GlobalScopeAsm += '\n';
258 /// Append to the module-scope inline assembly blocks.
259 /// A trailing newline is added if the input doesn't have one.
260 void appendModuleInlineAsm(StringRef Asm) {
261 GlobalScopeAsm += Asm;
262 if (!GlobalScopeAsm.empty() &&
263 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
264 GlobalScopeAsm += '\n';
268 /// @name Generic Value Accessors
271 /// Return the global value in the module with the specified name, of
272 /// arbitrary type. This method returns null if a global with the specified
273 /// name is not found.
274 GlobalValue *getNamedValue(StringRef Name) const;
276 /// Return a unique non-zero ID for the specified metadata kind. This ID is
277 /// uniqued across modules in the current LLVMContext.
278 unsigned getMDKindID(StringRef Name) const;
280 /// Populate client supplied SmallVector with the name for custom metadata IDs
281 /// registered in this LLVMContext.
282 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
284 /// Populate client supplied SmallVector with the bundle tags registered in
285 /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
286 /// \see LLVMContext::getOperandBundleTagID
287 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
289 /// Return the type with the specified name, or null if there is none by that
291 StructType *getTypeByName(StringRef Name) const;
293 std::vector<StructType *> getIdentifiedStructTypes() const;
296 /// @name Function Accessors
299 /// Look up the specified function in the module symbol table. Four
301 /// 1. If it does not exist, add a prototype for the function and return it.
302 /// 2. If it exists, and has a local linkage, the existing function is
303 /// renamed and a new one is inserted.
304 /// 3. Otherwise, if the existing function has the correct prototype, return
305 /// the existing function.
306 /// 4. Finally, the function exists but has the wrong prototype: return the
307 /// function with a constantexpr cast to the right prototype.
308 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
309 AttributeSet AttributeList);
311 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
313 /// Look up the specified function in the module symbol table. If it does not
314 /// exist, add a prototype for the function and return it. This function
315 /// guarantees to return a constant of pointer to the specified function type
316 /// or a ConstantExpr BitCast of that type if the named function has a
317 /// different type. This version of the method takes a null terminated list of
318 /// function arguments, which makes it easier for clients to use.
319 Constant *getOrInsertFunction(StringRef Name,
320 AttributeSet AttributeList,
321 Type *RetTy, ...) LLVM_END_WITH_NULL;
323 /// Same as above, but without the attributes.
324 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
327 /// Look up the specified function in the module symbol table. If it does not
328 /// exist, return null.
329 Function *getFunction(StringRef Name) const;
332 /// @name Global Variable Accessors
335 /// Look up the specified global variable in the module symbol table. If it
336 /// does not exist, return null. If AllowInternal is set to true, this
337 /// function will return types that have InternalLinkage. By default, these
338 /// types are not returned.
339 GlobalVariable *getGlobalVariable(StringRef Name) const {
340 return getGlobalVariable(Name, false);
343 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const {
344 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
347 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
349 /// Return the global variable in the module with the specified name, of
350 /// arbitrary type. This method returns null if a global with the specified
351 /// name is not found.
352 GlobalVariable *getNamedGlobal(StringRef Name) {
353 return getGlobalVariable(Name, true);
355 const GlobalVariable *getNamedGlobal(StringRef Name) const {
356 return const_cast<Module *>(this)->getNamedGlobal(Name);
359 /// Look up the specified global in the module symbol table.
360 /// 1. If it does not exist, add a declaration of the global and return it.
361 /// 2. Else, the global exists but has the wrong type: return the function
362 /// with a constantexpr cast to the right type.
363 /// 3. Finally, if the existing global is the correct declaration, return
364 /// the existing global.
365 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
368 /// @name Global Alias Accessors
371 /// Return the global alias in the module with the specified name, of
372 /// arbitrary type. This method returns null if a global with the specified
373 /// name is not found.
374 GlobalAlias *getNamedAlias(StringRef Name) const;
377 /// @name Named Metadata Accessors
380 /// Return the first NamedMDNode in the module with the specified name. This
381 /// method returns null if a NamedMDNode with the specified name is not found.
382 NamedMDNode *getNamedMetadata(const Twine &Name) const;
384 /// Return the named MDNode in the module with the specified name. This method
385 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
387 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
389 /// Remove the given NamedMDNode from this module and delete it.
390 void eraseNamedMetadata(NamedMDNode *NMD);
393 /// @name Comdat Accessors
396 /// Return the Comdat in the module with the specified name. It is created
397 /// if it didn't already exist.
398 Comdat *getOrInsertComdat(StringRef Name);
401 /// @name Module Flags Accessors
404 /// Returns the module flags in the provided vector.
405 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
407 /// Return the corresponding value if Key appears in module flags, otherwise
409 Metadata *getModuleFlag(StringRef Key) const;
411 /// Returns the NamedMDNode in the module that represents module-level flags.
412 /// This method returns null if there are no module-level flags.
413 NamedMDNode *getModuleFlagsMetadata() const;
415 /// Returns the NamedMDNode in the module that represents module-level flags.
416 /// If module-level flags aren't found, it creates the named metadata that
418 NamedMDNode *getOrInsertModuleFlagsMetadata();
420 /// Add a module-level flag to the module-level flags metadata. It will create
421 /// the module-level flags named metadata if it doesn't already exist.
422 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
423 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
424 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
425 void addModuleFlag(MDNode *Node);
428 /// @name Materialization
431 /// Sets the GVMaterializer to GVM. This module must not yet have a
432 /// Materializer. To reset the materializer for a module that already has one,
433 /// call MaterializeAllPermanently first. Destroying this module will destroy
434 /// its materializer without materializing any more GlobalValues. Without
435 /// destroying the Module, there is no way to detach or destroy a materializer
436 /// without materializing all the GVs it controls, to avoid leaving orphan
437 /// unmaterialized GVs.
438 void setMaterializer(GVMaterializer *GVM);
439 /// Retrieves the GVMaterializer, if any, for this Module.
440 GVMaterializer *getMaterializer() const { return Materializer.get(); }
442 /// Returns true if this GV was loaded from this Module's GVMaterializer and
443 /// the GVMaterializer knows how to dematerialize the GV.
444 bool isDematerializable(const GlobalValue *GV) const;
446 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
447 /// returns true and fills in the optional string with information about the
448 /// problem. If successful, this returns false.
449 std::error_code materialize(GlobalValue *GV);
450 /// If the GlobalValue is read in, and if the GVMaterializer supports it,
451 /// release the memory for the function, and set it up to be materialized
452 /// lazily. If !isDematerializable(), this method is a no-op.
453 void dematerialize(GlobalValue *GV);
455 /// Make sure all GlobalValues in this Module are fully read.
456 std::error_code materializeAll();
458 /// Make sure all GlobalValues in this Module are fully read and clear the
459 /// Materializer. If the module is corrupt, this DOES NOT clear the old
461 std::error_code materializeAllPermanently();
463 std::error_code materializeMetadata();
466 /// @name Direct access to the globals list, functions list, and symbol table
469 /// Get the Module's list of global variables (constant).
470 const GlobalListType &getGlobalList() const { return GlobalList; }
471 /// Get the Module's list of global variables.
472 GlobalListType &getGlobalList() { return GlobalList; }
473 static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
474 return &Module::GlobalList;
476 /// Get the Module's list of functions (constant).
477 const FunctionListType &getFunctionList() const { return FunctionList; }
478 /// Get the Module's list of functions.
479 FunctionListType &getFunctionList() { return FunctionList; }
480 static FunctionListType Module::*getSublistAccess(Function*) {
481 return &Module::FunctionList;
483 /// Get the Module's list of aliases (constant).
484 const AliasListType &getAliasList() const { return AliasList; }
485 /// Get the Module's list of aliases.
486 AliasListType &getAliasList() { return AliasList; }
487 static AliasListType Module::*getSublistAccess(GlobalAlias*) {
488 return &Module::AliasList;
490 /// Get the Module's list of named metadata (constant).
491 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
492 /// Get the Module's list of named metadata.
493 NamedMDListType &getNamedMDList() { return NamedMDList; }
494 static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
495 return &Module::NamedMDList;
497 /// Get the symbol table of global variable and function identifiers
498 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
499 /// Get the Module's symbol table of global variable and function identifiers.
500 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
501 /// Get the Module's symbol table for COMDATs (constant).
502 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
503 /// Get the Module's symbol table for COMDATs.
504 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
507 /// @name Global Variable Iteration
510 global_iterator global_begin() { return GlobalList.begin(); }
511 const_global_iterator global_begin() const { return GlobalList.begin(); }
512 global_iterator global_end () { return GlobalList.end(); }
513 const_global_iterator global_end () const { return GlobalList.end(); }
514 bool global_empty() const { return GlobalList.empty(); }
516 iterator_range<global_iterator> globals() {
517 return iterator_range<global_iterator>(global_begin(), global_end());
519 iterator_range<const_global_iterator> globals() const {
520 return iterator_range<const_global_iterator>(global_begin(), global_end());
524 /// @name Function Iteration
527 iterator begin() { return FunctionList.begin(); }
528 const_iterator begin() const { return FunctionList.begin(); }
529 iterator end () { return FunctionList.end(); }
530 const_iterator end () const { return FunctionList.end(); }
531 reverse_iterator rbegin() { return FunctionList.rbegin(); }
532 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
533 reverse_iterator rend() { return FunctionList.rend(); }
534 const_reverse_iterator rend() const { return FunctionList.rend(); }
535 size_t size() const { return FunctionList.size(); }
536 bool empty() const { return FunctionList.empty(); }
538 iterator_range<iterator> functions() {
539 return iterator_range<iterator>(begin(), end());
541 iterator_range<const_iterator> functions() const {
542 return iterator_range<const_iterator>(begin(), end());
546 /// @name Alias Iteration
549 alias_iterator alias_begin() { return AliasList.begin(); }
550 const_alias_iterator alias_begin() const { return AliasList.begin(); }
551 alias_iterator alias_end () { return AliasList.end(); }
552 const_alias_iterator alias_end () const { return AliasList.end(); }
553 size_t alias_size () const { return AliasList.size(); }
554 bool alias_empty() const { return AliasList.empty(); }
556 iterator_range<alias_iterator> aliases() {
557 return iterator_range<alias_iterator>(alias_begin(), alias_end());
559 iterator_range<const_alias_iterator> aliases() const {
560 return iterator_range<const_alias_iterator>(alias_begin(), alias_end());
564 /// @name Named Metadata Iteration
567 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
568 const_named_metadata_iterator named_metadata_begin() const {
569 return NamedMDList.begin();
572 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
573 const_named_metadata_iterator named_metadata_end() const {
574 return NamedMDList.end();
577 size_t named_metadata_size() const { return NamedMDList.size(); }
578 bool named_metadata_empty() const { return NamedMDList.empty(); }
580 iterator_range<named_metadata_iterator> named_metadata() {
581 return iterator_range<named_metadata_iterator>(named_metadata_begin(),
582 named_metadata_end());
584 iterator_range<const_named_metadata_iterator> named_metadata() const {
585 return iterator_range<const_named_metadata_iterator>(named_metadata_begin(),
586 named_metadata_end());
589 /// Destroy ConstantArrays in LLVMContext if they are not used.
590 /// ConstantArrays constructed during linking can cause quadratic memory
591 /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
592 /// slowdown for a large application.
594 /// NOTE: Constants are currently owned by LLVMContext. This can then only
595 /// be called where all uses of the LLVMContext are understood.
596 void dropTriviallyDeadConstantArrays();
599 /// @name Utility functions for printing and dumping Module objects
602 /// Print the module to an output stream with an optional
603 /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
604 /// uselistorder directives so that use-lists can be recreated when reading
606 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
607 bool ShouldPreserveUseListOrder = false,
608 bool IsForDebug = false) const;
610 /// Dump the module to stderr (for debugging).
613 /// This function causes all the subinstructions to "let go" of all references
614 /// that they are maintaining. This allows one to 'delete' a whole class at
615 /// a time, even though there may be circular references... first all
616 /// references are dropped, and all use counts go to zero. Then everything
617 /// is delete'd for real. Note that no operations are valid on an object
618 /// that has "dropped all references", except operator delete.
619 void dropAllReferences();
622 /// @name Utility functions for querying Debug information.
625 /// \brief Returns the Dwarf Version by checking module flags.
626 unsigned getDwarfVersion() const;
628 /// \brief Returns the CodeView Version by checking module flags.
629 /// Returns zero if not present in module.
630 unsigned getCodeViewFlag() const;
633 /// @name Utility functions for querying and setting PIC level
636 /// \brief Returns the PIC level (small or large model)
637 PICLevel::Level getPICLevel() const;
639 /// \brief Set the PIC level (small or large model)
640 void setPICLevel(PICLevel::Level PL);
644 /// An raw_ostream inserter for modules.
645 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
650 // Create wrappers for C Binding types (see CBindingWrapping.h).
651 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
653 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
656 inline Module *unwrap(LLVMModuleProviderRef MP) {
657 return reinterpret_cast<Module*>(MP);
660 } // End llvm namespace