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/Optional.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/IR/Comdat.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalAlias.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/Support/CBindingWrapping.h"
27 #include "llvm/Support/CodeGen.h"
28 #include "llvm/Support/DataTypes.h"
29 #include <system_error>
35 class RandomNumberGenerator;
38 template<> struct ilist_traits<NamedMDNode>
39 : public ilist_default_traits<NamedMDNode> {
40 // createSentinel is used to get hold of a node that marks the end of
42 NamedMDNode *createSentinel() const {
43 return static_cast<NamedMDNode*>(&Sentinel);
45 static void destroySentinel(NamedMDNode*) {}
47 NamedMDNode *provideInitialHead() const { return createSentinel(); }
48 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
49 static void noteHead(NamedMDNode*, NamedMDNode*) {}
50 void addNodeToList(NamedMDNode *) {}
51 void removeNodeFromList(NamedMDNode *) {}
54 mutable ilist_node<NamedMDNode> Sentinel;
57 /// A Module instance is used to store all the information related to an
58 /// LLVM module. Modules are the top level container of all other LLVM
59 /// Intermediate Representation (IR) objects. Each module directly contains a
60 /// list of globals variables, a list of functions, a list of libraries (or
61 /// other modules) this module depends on, a symbol table, and various data
62 /// about the target's characteristics.
64 /// A module maintains a GlobalValRefMap object that is used to hold all
65 /// constant references to global variables in the module. When a global
66 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
67 /// @brief The main container class for the LLVM Intermediate Representation.
69 /// @name Types And Enumerations
72 /// The type for the list of global variables.
73 typedef SymbolTableList<GlobalVariable> GlobalListType;
74 /// The type for the list of functions.
75 typedef SymbolTableList<Function> FunctionListType;
76 /// The type for the list of aliases.
77 typedef SymbolTableList<GlobalAlias> AliasListType;
78 /// The type for the list of named metadata.
79 typedef ilist<NamedMDNode> NamedMDListType;
80 /// The type of the comdat "symbol" table.
81 typedef StringMap<Comdat> ComdatSymTabType;
83 /// The Global Variable iterator.
84 typedef GlobalListType::iterator global_iterator;
85 /// The Global Variable constant iterator.
86 typedef GlobalListType::const_iterator const_global_iterator;
88 /// The Function iterators.
89 typedef FunctionListType::iterator iterator;
90 /// The Function constant iterator
91 typedef FunctionListType::const_iterator const_iterator;
93 /// The Function reverse iterator.
94 typedef FunctionListType::reverse_iterator reverse_iterator;
95 /// The Function constant reverse iterator.
96 typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
98 /// The Global Alias iterators.
99 typedef AliasListType::iterator alias_iterator;
100 /// The Global Alias constant iterator
101 typedef AliasListType::const_iterator const_alias_iterator;
103 /// The named metadata iterators.
104 typedef NamedMDListType::iterator named_metadata_iterator;
105 /// The named metadata constant iterators.
106 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
108 /// This enumeration defines the supported behaviors of module flags.
109 enum ModFlagBehavior {
110 /// Emits an error if two values disagree, otherwise the resulting value is
111 /// that of the operands.
114 /// Emits a warning if two values disagree. The result value will be the
115 /// operand for the flag from the first module being linked.
118 /// Adds a requirement that another module flag be present and have a
119 /// specified value after linking is performed. The value must be a metadata
120 /// pair, where the first element of the pair is the ID of the module flag
121 /// to be restricted, and the second element of the pair is the value the
122 /// module flag should be restricted to. This behavior can be used to
123 /// restrict the allowable results (via triggering of an error) of linking
124 /// IDs with the **Override** behavior.
127 /// Uses the specified value, regardless of the behavior or value of the
128 /// other module. If both modules specify **Override**, but the values
129 /// differ, an error will be emitted.
132 /// Appends the two values, which are required to be metadata nodes.
135 /// Appends the two values, which are required to be metadata
136 /// nodes. However, duplicate entries in the second list are dropped
137 /// during the append operation.
141 ModFlagBehaviorFirstVal = Error,
142 ModFlagBehaviorLastVal = AppendUnique
145 /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
146 /// converted result in MFB.
147 static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
149 struct ModuleFlagEntry {
150 ModFlagBehavior Behavior;
153 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
154 : Behavior(B), Key(K), Val(V) {}
158 /// @name Member Variables
161 LLVMContext &Context; ///< The LLVMContext from which types and
162 ///< constants are allocated.
163 GlobalListType GlobalList; ///< The Global Variables in the module
164 FunctionListType FunctionList; ///< The Functions in the module
165 AliasListType AliasList; ///< The Aliases in the module
166 NamedMDListType NamedMDList; ///< The named metadata in the module
167 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
168 ValueSymbolTable *ValSymTab; ///< Symbol table for values
169 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
170 std::unique_ptr<GVMaterializer>
171 Materializer; ///< Used to materialize GlobalValues
172 std::string ModuleID; ///< Human readable identifier for the module
173 std::string TargetTriple; ///< Platform target triple Module compiled on
174 ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
175 void *NamedMDSymTab; ///< NamedMDNode names.
176 DataLayout DL; ///< DataLayout associated with the module
178 friend class Constant;
181 /// @name Constructors
184 /// The Module constructor. Note that there is no default constructor. You
185 /// must provide a name for the module upon construction.
186 explicit Module(StringRef ModuleID, LLVMContext& C);
187 /// The module destructor. This will dropAllReferences.
191 /// @name Module Level Accessors
194 /// Get the module identifier which is, essentially, the name of the module.
195 /// @returns the module identifier as a string
196 const std::string &getModuleIdentifier() const { return ModuleID; }
198 /// \brief Get a short "name" for the module.
200 /// This is useful for debugging or logging. It is essentially a convenience
201 /// wrapper around getModuleIdentifier().
202 StringRef getName() const { return ModuleID; }
204 /// Get the data layout string for the module's target platform. This is
205 /// equivalent to getDataLayout()->getStringRepresentation().
206 const std::string &getDataLayoutStr() const {
207 return DL.getStringRepresentation();
210 /// Get the data layout for the module's target platform.
211 const DataLayout &getDataLayout() const;
213 /// Get the target triple which is a string describing the target host.
214 /// @returns a string containing the target triple.
215 const std::string &getTargetTriple() const { return TargetTriple; }
217 /// Get the global data context.
218 /// @returns LLVMContext - a container for LLVM's global information
219 LLVMContext &getContext() const { return Context; }
221 /// Get any module-scope inline assembly blocks.
222 /// @returns a string containing the module-scope inline assembly blocks.
223 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
225 /// Get a RandomNumberGenerator salted for use with this module. The
226 /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
227 /// ModuleID and the provided pass salt. The returned RNG should not
228 /// be shared across threads or passes.
230 /// A unique RNG per pass ensures a reproducible random stream even
231 /// when other randomness consuming passes are added or removed. In
232 /// addition, the random stream will be reproducible across LLVM
233 /// versions when the pass does not change.
234 RandomNumberGenerator *createRNG(const Pass* P) const;
237 /// @name Module Level Mutators
240 /// Set the module identifier.
241 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
243 /// Set the data layout
244 void setDataLayout(StringRef Desc);
245 void setDataLayout(const DataLayout &Other);
247 /// Set the target triple.
248 void setTargetTriple(StringRef T) { TargetTriple = T; }
250 /// Set the module-scope inline assembly blocks.
251 /// A trailing newline is added if the input doesn't have one.
252 void setModuleInlineAsm(StringRef Asm) {
253 GlobalScopeAsm = Asm;
254 if (!GlobalScopeAsm.empty() &&
255 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
256 GlobalScopeAsm += '\n';
259 /// Append to the module-scope inline assembly blocks.
260 /// A trailing newline is added if the input doesn't have one.
261 void appendModuleInlineAsm(StringRef Asm) {
262 GlobalScopeAsm += Asm;
263 if (!GlobalScopeAsm.empty() &&
264 GlobalScopeAsm[GlobalScopeAsm.size()-1] != '\n')
265 GlobalScopeAsm += '\n';
269 /// @name Generic Value Accessors
272 /// Return the global value in the module with the specified name, of
273 /// arbitrary type. This method returns null if a global with the specified
274 /// name is not found.
275 GlobalValue *getNamedValue(StringRef Name) const;
277 /// Return a unique non-zero ID for the specified metadata kind. This ID is
278 /// uniqued across modules in the current LLVMContext.
279 unsigned getMDKindID(StringRef Name) const;
281 /// Populate client supplied SmallVector with the name for custom metadata IDs
282 /// registered in this LLVMContext.
283 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
285 /// Populate client supplied SmallVector with the bundle tags registered in
286 /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
287 /// \see LLVMContext::getOperandBundleTagID
288 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
290 /// Return the type with the specified name, or null if there is none by that
292 StructType *getTypeByName(StringRef Name) const;
294 std::vector<StructType *> getIdentifiedStructTypes() const;
297 /// @name Function Accessors
300 /// Look up the specified function in the module symbol table. Four
302 /// 1. If it does not exist, add a prototype for the function and return it.
303 /// 2. If it exists, and has a local linkage, the existing function is
304 /// renamed and a new one is inserted.
305 /// 3. Otherwise, if the existing function has the correct prototype, return
306 /// the existing function.
307 /// 4. Finally, the function exists but has the wrong prototype: return the
308 /// function with a constantexpr cast to the right prototype.
309 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
310 AttributeSet AttributeList);
312 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
314 /// Look up the specified function in the module symbol table. If it does not
315 /// exist, add a prototype for the function and return it. This function
316 /// guarantees to return a constant of pointer to the specified function type
317 /// or a ConstantExpr BitCast of that type if the named function has a
318 /// different type. This version of the method takes a null terminated list of
319 /// function arguments, which makes it easier for clients to use.
320 Constant *getOrInsertFunction(StringRef Name,
321 AttributeSet AttributeList,
322 Type *RetTy, ...) LLVM_END_WITH_NULL;
324 /// Same as above, but without the attributes.
325 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
328 /// Look up the specified function in the module symbol table. If it does not
329 /// exist, return null.
330 Function *getFunction(StringRef Name) const;
333 /// @name Global Variable Accessors
336 /// Look up the specified global variable in the module symbol table. If it
337 /// does not exist, return null. If AllowInternal is set to true, this
338 /// function will return types that have InternalLinkage. By default, these
339 /// types are not returned.
340 GlobalVariable *getGlobalVariable(StringRef Name) const {
341 return getGlobalVariable(Name, false);
344 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const {
345 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
348 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
350 /// Return the global variable in the module with the specified name, of
351 /// arbitrary type. This method returns null if a global with the specified
352 /// name is not found.
353 GlobalVariable *getNamedGlobal(StringRef Name) {
354 return getGlobalVariable(Name, true);
356 const GlobalVariable *getNamedGlobal(StringRef Name) const {
357 return const_cast<Module *>(this)->getNamedGlobal(Name);
360 /// Look up the specified global in the module symbol table.
361 /// 1. If it does not exist, add a declaration of the global and return it.
362 /// 2. Else, the global exists but has the wrong type: return the function
363 /// with a constantexpr cast to the right type.
364 /// 3. Finally, if the existing global is the correct declaration, return
365 /// the existing global.
366 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
369 /// @name Global Alias Accessors
372 /// Return the global alias 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 GlobalAlias *getNamedAlias(StringRef Name) const;
378 /// @name Named Metadata Accessors
381 /// Return the first NamedMDNode in the module with the specified name. This
382 /// method returns null if a NamedMDNode with the specified name is not found.
383 NamedMDNode *getNamedMetadata(const Twine &Name) const;
385 /// Return the named MDNode in the module with the specified name. This method
386 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
388 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
390 /// Remove the given NamedMDNode from this module and delete it.
391 void eraseNamedMetadata(NamedMDNode *NMD);
394 /// @name Comdat Accessors
397 /// Return the Comdat in the module with the specified name. It is created
398 /// if it didn't already exist.
399 Comdat *getOrInsertComdat(StringRef Name);
402 /// @name Module Flags Accessors
405 /// Returns the module flags in the provided vector.
406 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
408 /// Return the corresponding value if Key appears in module flags, otherwise
410 Metadata *getModuleFlag(StringRef Key) const;
412 /// Returns the NamedMDNode in the module that represents module-level flags.
413 /// This method returns null if there are no module-level flags.
414 NamedMDNode *getModuleFlagsMetadata() const;
416 /// Returns the NamedMDNode in the module that represents module-level flags.
417 /// If module-level flags aren't found, it creates the named metadata that
419 NamedMDNode *getOrInsertModuleFlagsMetadata();
421 /// Add a module-level flag to the module-level flags metadata. It will create
422 /// the module-level flags named metadata if it doesn't already exist.
423 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
424 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
425 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
426 void addModuleFlag(MDNode *Node);
429 /// @name Materialization
432 /// Sets the GVMaterializer to GVM. This module must not yet have a
433 /// Materializer. To reset the materializer for a module that already has one,
434 /// call MaterializeAllPermanently first. Destroying this module will destroy
435 /// its materializer without materializing any more GlobalValues. Without
436 /// destroying the Module, there is no way to detach or destroy a materializer
437 /// without materializing all the GVs it controls, to avoid leaving orphan
438 /// unmaterialized GVs.
439 void setMaterializer(GVMaterializer *GVM);
440 /// Retrieves the GVMaterializer, if any, for this Module.
441 GVMaterializer *getMaterializer() const { return Materializer.get(); }
443 /// Returns true if this GV was loaded from this Module's GVMaterializer and
444 /// the GVMaterializer knows how to dematerialize the GV.
445 bool isDematerializable(const GlobalValue *GV) const;
447 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
448 /// returns true and fills in the optional string with information about the
449 /// problem. If successful, this returns false.
450 std::error_code materialize(GlobalValue *GV);
451 /// If the GlobalValue is read in, and if the GVMaterializer supports it,
452 /// release the memory for the function, and set it up to be materialized
453 /// lazily. If !isDematerializable(), this method is a no-op.
454 void dematerialize(GlobalValue *GV);
456 /// Make sure all GlobalValues in this Module are fully read.
457 std::error_code materializeAll();
459 /// Make sure all GlobalValues in this Module are fully read and clear the
460 /// Materializer. If the module is corrupt, this DOES NOT clear the old
462 std::error_code materializeAllPermanently();
464 std::error_code materializeMetadata();
467 /// @name Direct access to the globals list, functions list, and symbol table
470 /// Get the Module's list of global variables (constant).
471 const GlobalListType &getGlobalList() const { return GlobalList; }
472 /// Get the Module's list of global variables.
473 GlobalListType &getGlobalList() { return GlobalList; }
474 static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
475 return &Module::GlobalList;
477 /// Get the Module's list of functions (constant).
478 const FunctionListType &getFunctionList() const { return FunctionList; }
479 /// Get the Module's list of functions.
480 FunctionListType &getFunctionList() { return FunctionList; }
481 static FunctionListType Module::*getSublistAccess(Function*) {
482 return &Module::FunctionList;
484 /// Get the Module's list of aliases (constant).
485 const AliasListType &getAliasList() const { return AliasList; }
486 /// Get the Module's list of aliases.
487 AliasListType &getAliasList() { return AliasList; }
488 static AliasListType Module::*getSublistAccess(GlobalAlias*) {
489 return &Module::AliasList;
491 /// Get the Module's list of named metadata (constant).
492 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
493 /// Get the Module's list of named metadata.
494 NamedMDListType &getNamedMDList() { return NamedMDList; }
495 static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
496 return &Module::NamedMDList;
498 /// Get the symbol table of global variable and function identifiers
499 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
500 /// Get the Module's symbol table of global variable and function identifiers.
501 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
502 /// Get the Module's symbol table for COMDATs (constant).
503 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
504 /// Get the Module's symbol table for COMDATs.
505 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
508 /// @name Global Variable Iteration
511 global_iterator global_begin() { return GlobalList.begin(); }
512 const_global_iterator global_begin() const { return GlobalList.begin(); }
513 global_iterator global_end () { return GlobalList.end(); }
514 const_global_iterator global_end () const { return GlobalList.end(); }
515 bool global_empty() const { return GlobalList.empty(); }
517 iterator_range<global_iterator> globals() {
518 return make_range(global_begin(), global_end());
520 iterator_range<const_global_iterator> globals() const {
521 return make_range(global_begin(), global_end());
525 /// @name Function Iteration
528 iterator begin() { return FunctionList.begin(); }
529 const_iterator begin() const { return FunctionList.begin(); }
530 iterator end () { return FunctionList.end(); }
531 const_iterator end () const { return FunctionList.end(); }
532 reverse_iterator rbegin() { return FunctionList.rbegin(); }
533 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
534 reverse_iterator rend() { return FunctionList.rend(); }
535 const_reverse_iterator rend() const { return FunctionList.rend(); }
536 size_t size() const { return FunctionList.size(); }
537 bool empty() const { return FunctionList.empty(); }
539 iterator_range<iterator> functions() {
540 return make_range(begin(), end());
542 iterator_range<const_iterator> functions() const {
543 return make_range(begin(), end());
547 /// @name Alias Iteration
550 alias_iterator alias_begin() { return AliasList.begin(); }
551 const_alias_iterator alias_begin() const { return AliasList.begin(); }
552 alias_iterator alias_end () { return AliasList.end(); }
553 const_alias_iterator alias_end () const { return AliasList.end(); }
554 size_t alias_size () const { return AliasList.size(); }
555 bool alias_empty() const { return AliasList.empty(); }
557 iterator_range<alias_iterator> aliases() {
558 return make_range(alias_begin(), alias_end());
560 iterator_range<const_alias_iterator> aliases() const {
561 return make_range(alias_begin(), alias_end());
565 /// @name Named Metadata Iteration
568 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
569 const_named_metadata_iterator named_metadata_begin() const {
570 return NamedMDList.begin();
573 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
574 const_named_metadata_iterator named_metadata_end() const {
575 return NamedMDList.end();
578 size_t named_metadata_size() const { return NamedMDList.size(); }
579 bool named_metadata_empty() const { return NamedMDList.empty(); }
581 iterator_range<named_metadata_iterator> named_metadata() {
582 return make_range(named_metadata_begin(), named_metadata_end());
584 iterator_range<const_named_metadata_iterator> named_metadata() const {
585 return make_range(named_metadata_begin(), named_metadata_end());
588 /// Destroy ConstantArrays in LLVMContext if they are not used.
589 /// ConstantArrays constructed during linking can cause quadratic memory
590 /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
591 /// slowdown for a large application.
593 /// NOTE: Constants are currently owned by LLVMContext. This can then only
594 /// be called where all uses of the LLVMContext are understood.
595 void dropTriviallyDeadConstantArrays();
598 /// @name Utility functions for printing and dumping Module objects
601 /// Print the module to an output stream with an optional
602 /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
603 /// uselistorder directives so that use-lists can be recreated when reading
605 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
606 bool ShouldPreserveUseListOrder = false,
607 bool IsForDebug = false) const;
609 /// Dump the module to stderr (for debugging).
612 /// This function causes all the subinstructions to "let go" of all references
613 /// that they are maintaining. This allows one to 'delete' a whole class at
614 /// a time, even though there may be circular references... first all
615 /// references are dropped, and all use counts go to zero. Then everything
616 /// is delete'd for real. Note that no operations are valid on an object
617 /// that has "dropped all references", except operator delete.
618 void dropAllReferences();
621 /// @name Utility functions for querying Debug information.
624 /// \brief Returns the Dwarf Version by checking module flags.
625 unsigned getDwarfVersion() const;
627 /// \brief Returns the CodeView Version by checking module flags.
628 /// Returns zero if not present in module.
629 unsigned getCodeViewFlag() const;
632 /// @name Utility functions for querying and setting PIC level
635 /// \brief Returns the PIC level (small or large model)
636 PICLevel::Level getPICLevel() const;
638 /// \brief Set the PIC level (small or large model)
639 void setPICLevel(PICLevel::Level PL);
642 /// @name Utility functions for querying and setting PGO counts
645 /// \brief Set maximum function count in PGO mode
646 void setMaximumFunctionCount(uint64_t);
648 /// \brief Returns maximum function count in PGO mode
649 Optional<uint64_t> getMaximumFunctionCount();
653 /// An raw_ostream inserter for modules.
654 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
659 // Create wrappers for C Binding types (see CBindingWrapping.h).
660 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
662 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
665 inline Module *unwrap(LLVMModuleProviderRef MP) {
666 return reinterpret_cast<Module*>(MP);
669 } // End llvm namespace