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/GlobalIFunc.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>
32 template <typename T> class Optional;
36 class RandomNumberGenerator;
38 template <class PtrType> class SmallPtrSetImpl;
40 template<> struct ilist_traits<NamedMDNode>
41 : public ilist_default_traits<NamedMDNode> {
42 // createSentinel is used to get hold of a node that marks the end of
44 NamedMDNode *createSentinel() const {
45 return static_cast<NamedMDNode*>(&Sentinel);
47 static void destroySentinel(NamedMDNode*) {}
49 NamedMDNode *provideInitialHead() const { return createSentinel(); }
50 NamedMDNode *ensureHead(NamedMDNode*) const { return createSentinel(); }
51 static void noteHead(NamedMDNode*, NamedMDNode*) {}
52 void addNodeToList(NamedMDNode *) {}
53 void removeNodeFromList(NamedMDNode *) {}
56 mutable ilist_node<NamedMDNode> Sentinel;
59 /// A Module instance is used to store all the information related to an
60 /// LLVM module. Modules are the top level container of all other LLVM
61 /// Intermediate Representation (IR) objects. Each module directly contains a
62 /// list of globals variables, a list of functions, a list of libraries (or
63 /// other modules) this module depends on, a symbol table, and various data
64 /// about the target's characteristics.
66 /// A module maintains a GlobalValRefMap object that is used to hold all
67 /// constant references to global variables in the module. When a global
68 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
69 /// @brief The main container class for the LLVM Intermediate Representation.
71 /// @name Types And Enumerations
74 /// The type for the list of global variables.
75 typedef SymbolTableList<GlobalVariable> GlobalListType;
76 /// The type for the list of functions.
77 typedef SymbolTableList<Function> FunctionListType;
78 /// The type for the list of aliases.
79 typedef SymbolTableList<GlobalAlias> AliasListType;
80 /// The type for the list of ifuncs.
81 typedef SymbolTableList<GlobalIFunc> IFuncListType;
82 /// The type for the list of named metadata.
83 typedef ilist<NamedMDNode> NamedMDListType;
84 /// The type of the comdat "symbol" table.
85 typedef StringMap<Comdat> ComdatSymTabType;
87 /// The Global Variable iterator.
88 typedef GlobalListType::iterator global_iterator;
89 /// The Global Variable constant iterator.
90 typedef GlobalListType::const_iterator const_global_iterator;
92 /// The Function iterators.
93 typedef FunctionListType::iterator iterator;
94 /// The Function constant iterator
95 typedef FunctionListType::const_iterator const_iterator;
97 /// The Function reverse iterator.
98 typedef FunctionListType::reverse_iterator reverse_iterator;
99 /// The Function constant reverse iterator.
100 typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
102 /// The Global Alias iterators.
103 typedef AliasListType::iterator alias_iterator;
104 /// The Global Alias constant iterator
105 typedef AliasListType::const_iterator const_alias_iterator;
107 /// The Global IFunc iterators.
108 typedef IFuncListType::iterator ifunc_iterator;
109 /// The Global IFunc constant iterator
110 typedef IFuncListType::const_iterator const_ifunc_iterator;
112 /// The named metadata iterators.
113 typedef NamedMDListType::iterator named_metadata_iterator;
114 /// The named metadata constant iterators.
115 typedef NamedMDListType::const_iterator const_named_metadata_iterator;
117 /// This enumeration defines the supported behaviors of module flags.
118 enum ModFlagBehavior {
119 /// Emits an error if two values disagree, otherwise the resulting value is
120 /// that of the operands.
123 /// Emits a warning if two values disagree. The result value will be the
124 /// operand for the flag from the first module being linked.
127 /// Adds a requirement that another module flag be present and have a
128 /// specified value after linking is performed. The value must be a metadata
129 /// pair, where the first element of the pair is the ID of the module flag
130 /// to be restricted, and the second element of the pair is the value the
131 /// module flag should be restricted to. This behavior can be used to
132 /// restrict the allowable results (via triggering of an error) of linking
133 /// IDs with the **Override** behavior.
136 /// Uses the specified value, regardless of the behavior or value of the
137 /// other module. If both modules specify **Override**, but the values
138 /// differ, an error will be emitted.
141 /// Appends the two values, which are required to be metadata nodes.
144 /// Appends the two values, which are required to be metadata
145 /// nodes. However, duplicate entries in the second list are dropped
146 /// during the append operation.
150 ModFlagBehaviorFirstVal = Error,
151 ModFlagBehaviorLastVal = AppendUnique
154 /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
155 /// converted result in MFB.
156 static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
158 struct ModuleFlagEntry {
159 ModFlagBehavior Behavior;
162 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
163 : Behavior(B), Key(K), Val(V) {}
167 /// @name Member Variables
170 LLVMContext &Context; ///< The LLVMContext from which types and
171 ///< constants are allocated.
172 GlobalListType GlobalList; ///< The Global Variables in the module
173 FunctionListType FunctionList; ///< The Functions in the module
174 AliasListType AliasList; ///< The Aliases in the module
175 IFuncListType IFuncList; ///< The IFuncs in the module
176 NamedMDListType NamedMDList; ///< The named metadata in the module
177 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
178 ValueSymbolTable *ValSymTab; ///< Symbol table for values
179 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
180 std::unique_ptr<GVMaterializer>
181 Materializer; ///< Used to materialize GlobalValues
182 std::string ModuleID; ///< Human readable identifier for the module
183 std::string SourceFileName; ///< Original source file name for module,
184 ///< recorded in bitcode.
185 std::string TargetTriple; ///< Platform target triple Module compiled on
186 ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
187 void *NamedMDSymTab; ///< NamedMDNode names.
188 DataLayout DL; ///< DataLayout associated with the module
190 friend class Constant;
193 /// @name Constructors
196 /// The Module constructor. Note that there is no default constructor. You
197 /// must provide a name for the module upon construction.
198 explicit Module(StringRef ModuleID, LLVMContext& C);
199 /// The module destructor. This will dropAllReferences.
203 /// @name Module Level Accessors
206 /// Get the module identifier which is, essentially, the name of the module.
207 /// @returns the module identifier as a string
208 const std::string &getModuleIdentifier() const { return ModuleID; }
210 /// Get the module's original source file name. When compiling from
211 /// bitcode, this is taken from a bitcode record where it was recorded.
212 /// For other compiles it is the same as the ModuleID, which would
213 /// contain the source file name.
214 const std::string &getSourceFileName() const { return SourceFileName; }
216 /// \brief Get a short "name" for the module.
218 /// This is useful for debugging or logging. It is essentially a convenience
219 /// wrapper around getModuleIdentifier().
220 StringRef getName() const { return ModuleID; }
222 /// Get the data layout string for the module's target platform. This is
223 /// equivalent to getDataLayout()->getStringRepresentation().
224 const std::string &getDataLayoutStr() const {
225 return DL.getStringRepresentation();
228 /// Get the data layout for the module's target platform.
229 const DataLayout &getDataLayout() const;
231 /// Get the target triple which is a string describing the target host.
232 /// @returns a string containing the target triple.
233 const std::string &getTargetTriple() const { return TargetTriple; }
235 /// Get the global data context.
236 /// @returns LLVMContext - a container for LLVM's global information
237 LLVMContext &getContext() const { return Context; }
239 /// Get any module-scope inline assembly blocks.
240 /// @returns a string containing the module-scope inline assembly blocks.
241 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
243 /// Get a RandomNumberGenerator salted for use with this module. The
244 /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
245 /// ModuleID and the provided pass salt. The returned RNG should not
246 /// be shared across threads or passes.
248 /// A unique RNG per pass ensures a reproducible random stream even
249 /// when other randomness consuming passes are added or removed. In
250 /// addition, the random stream will be reproducible across LLVM
251 /// versions when the pass does not change.
252 RandomNumberGenerator *createRNG(const Pass* P) const;
255 /// @name Module Level Mutators
258 /// Set the module identifier.
259 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
261 /// Set the module's original source file name.
262 void setSourceFileName(StringRef Name) { SourceFileName = Name; }
264 /// Set the data layout
265 void setDataLayout(StringRef Desc);
266 void setDataLayout(const DataLayout &Other);
268 /// Set the target triple.
269 void setTargetTriple(StringRef T) { TargetTriple = T; }
271 /// Set the module-scope inline assembly blocks.
272 /// A trailing newline is added if the input doesn't have one.
273 void setModuleInlineAsm(StringRef Asm) {
274 GlobalScopeAsm = Asm;
275 if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
276 GlobalScopeAsm += '\n';
279 /// Append to the module-scope inline assembly blocks.
280 /// A trailing newline is added if the input doesn't have one.
281 void appendModuleInlineAsm(StringRef Asm) {
282 GlobalScopeAsm += Asm;
283 if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
284 GlobalScopeAsm += '\n';
288 /// @name Generic Value Accessors
291 /// Return the global value in the module with the specified name, of
292 /// arbitrary type. This method returns null if a global with the specified
293 /// name is not found.
294 GlobalValue *getNamedValue(StringRef Name) const;
296 /// Return a unique non-zero ID for the specified metadata kind. This ID is
297 /// uniqued across modules in the current LLVMContext.
298 unsigned getMDKindID(StringRef Name) const;
300 /// Populate client supplied SmallVector with the name for custom metadata IDs
301 /// registered in this LLVMContext.
302 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
304 /// Populate client supplied SmallVector with the bundle tags registered in
305 /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
306 /// \see LLVMContext::getOperandBundleTagID
307 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
309 /// Return the type with the specified name, or null if there is none by that
311 StructType *getTypeByName(StringRef Name) const;
313 std::vector<StructType *> getIdentifiedStructTypes() const;
316 /// @name Function Accessors
319 /// Look up the specified function in the module symbol table. Four
321 /// 1. If it does not exist, add a prototype for the function and return it.
322 /// 2. If it exists, and has a local linkage, the existing function is
323 /// renamed and a new one is inserted.
324 /// 3. Otherwise, if the existing function has the correct prototype, return
325 /// the existing function.
326 /// 4. Finally, the function exists but has the wrong prototype: return the
327 /// function with a constantexpr cast to the right prototype.
328 Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
329 AttributeSet AttributeList);
331 Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
333 /// Look up the specified function in the module symbol table. If it does not
334 /// exist, add a prototype for the function and return it. This function
335 /// guarantees to return a constant of pointer to the specified function type
336 /// or a ConstantExpr BitCast of that type if the named function has a
337 /// different type. This version of the method takes a null terminated list of
338 /// function arguments, which makes it easier for clients to use.
339 Constant *getOrInsertFunction(StringRef Name,
340 AttributeSet AttributeList,
341 Type *RetTy, ...) LLVM_END_WITH_NULL;
343 /// Same as above, but without the attributes.
344 Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ...)
347 /// Look up the specified function in the module symbol table. If it does not
348 /// exist, return null.
349 Function *getFunction(StringRef Name) const;
352 /// @name Global Variable Accessors
355 /// Look up the specified global variable in the module symbol table. If it
356 /// does not exist, return null. If AllowInternal is set to true, this
357 /// function will return types that have InternalLinkage. By default, these
358 /// types are not returned.
359 GlobalVariable *getGlobalVariable(StringRef Name) const {
360 return getGlobalVariable(Name, false);
363 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const {
364 return const_cast<Module *>(this)->getGlobalVariable(Name, AllowInternal);
367 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal = false);
369 /// Return the global variable in the module with the specified name, of
370 /// arbitrary type. This method returns null if a global with the specified
371 /// name is not found.
372 GlobalVariable *getNamedGlobal(StringRef Name) {
373 return getGlobalVariable(Name, true);
375 const GlobalVariable *getNamedGlobal(StringRef Name) const {
376 return const_cast<Module *>(this)->getNamedGlobal(Name);
379 /// Look up the specified global in the module symbol table.
380 /// 1. If it does not exist, add a declaration of the global and return it.
381 /// 2. Else, the global exists but has the wrong type: return the function
382 /// with a constantexpr cast to the right type.
383 /// 3. Finally, if the existing global is the correct declaration, return
384 /// the existing global.
385 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
388 /// @name Global Alias Accessors
391 /// Return the global alias in the module with the specified name, of
392 /// arbitrary type. This method returns null if a global with the specified
393 /// name is not found.
394 GlobalAlias *getNamedAlias(StringRef Name) const;
397 /// @name Global IFunc Accessors
400 /// Return the global ifunc in the module with the specified name, of
401 /// arbitrary type. This method returns null if a global with the specified
402 /// name is not found.
403 GlobalIFunc *getNamedIFunc(StringRef Name) const;
406 /// @name Named Metadata Accessors
409 /// Return the first NamedMDNode in the module with the specified name. This
410 /// method returns null if a NamedMDNode with the specified name is not found.
411 NamedMDNode *getNamedMetadata(const Twine &Name) const;
413 /// Return the named MDNode in the module with the specified name. This method
414 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
416 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
418 /// Remove the given NamedMDNode from this module and delete it.
419 void eraseNamedMetadata(NamedMDNode *NMD);
422 /// @name Comdat Accessors
425 /// Return the Comdat in the module with the specified name. It is created
426 /// if it didn't already exist.
427 Comdat *getOrInsertComdat(StringRef Name);
430 /// @name Module Flags Accessors
433 /// Returns the module flags in the provided vector.
434 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
436 /// Return the corresponding value if Key appears in module flags, otherwise
438 Metadata *getModuleFlag(StringRef Key) const;
440 /// Returns the NamedMDNode in the module that represents module-level flags.
441 /// This method returns null if there are no module-level flags.
442 NamedMDNode *getModuleFlagsMetadata() const;
444 /// Returns the NamedMDNode in the module that represents module-level flags.
445 /// If module-level flags aren't found, it creates the named metadata that
447 NamedMDNode *getOrInsertModuleFlagsMetadata();
449 /// Add a module-level flag to the module-level flags metadata. It will create
450 /// the module-level flags named metadata if it doesn't already exist.
451 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
452 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
453 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
454 void addModuleFlag(MDNode *Node);
457 /// @name Materialization
460 /// Sets the GVMaterializer to GVM. This module must not yet have a
461 /// Materializer. To reset the materializer for a module that already has one,
462 /// call materializeAll first. Destroying this module will destroy
463 /// its materializer without materializing any more GlobalValues. Without
464 /// destroying the Module, there is no way to detach or destroy a materializer
465 /// without materializing all the GVs it controls, to avoid leaving orphan
466 /// unmaterialized GVs.
467 void setMaterializer(GVMaterializer *GVM);
468 /// Retrieves the GVMaterializer, if any, for this Module.
469 GVMaterializer *getMaterializer() const { return Materializer.get(); }
470 bool isMaterialized() const { return !getMaterializer(); }
472 /// Make sure the GlobalValue is fully read. If the module is corrupt, this
473 /// returns true and fills in the optional string with information about the
474 /// problem. If successful, this returns false.
475 std::error_code materialize(GlobalValue *GV);
477 /// Make sure all GlobalValues in this Module are fully read and clear the
479 std::error_code materializeAll();
481 std::error_code materializeMetadata();
484 /// @name Direct access to the globals list, functions list, and symbol table
487 /// Get the Module's list of global variables (constant).
488 const GlobalListType &getGlobalList() const { return GlobalList; }
489 /// Get the Module's list of global variables.
490 GlobalListType &getGlobalList() { return GlobalList; }
491 static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
492 return &Module::GlobalList;
494 /// Get the Module's list of functions (constant).
495 const FunctionListType &getFunctionList() const { return FunctionList; }
496 /// Get the Module's list of functions.
497 FunctionListType &getFunctionList() { return FunctionList; }
498 static FunctionListType Module::*getSublistAccess(Function*) {
499 return &Module::FunctionList;
501 /// Get the Module's list of aliases (constant).
502 const AliasListType &getAliasList() const { return AliasList; }
503 /// Get the Module's list of aliases.
504 AliasListType &getAliasList() { return AliasList; }
505 static AliasListType Module::*getSublistAccess(GlobalAlias*) {
506 return &Module::AliasList;
508 /// Get the Module's list of ifuncs (constant).
509 const IFuncListType &getIFuncList() const { return IFuncList; }
510 /// Get the Module's list of ifuncs.
511 IFuncListType &getIFuncList() { return IFuncList; }
512 static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
513 return &Module::IFuncList;
515 /// Get the Module's list of named metadata (constant).
516 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
517 /// Get the Module's list of named metadata.
518 NamedMDListType &getNamedMDList() { return NamedMDList; }
519 static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
520 return &Module::NamedMDList;
522 /// Get the symbol table of global variable and function identifiers
523 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
524 /// Get the Module's symbol table of global variable and function identifiers.
525 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
526 /// Get the Module's symbol table for COMDATs (constant).
527 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
528 /// Get the Module's symbol table for COMDATs.
529 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
532 /// @name Global Variable Iteration
535 global_iterator global_begin() { return GlobalList.begin(); }
536 const_global_iterator global_begin() const { return GlobalList.begin(); }
537 global_iterator global_end () { return GlobalList.end(); }
538 const_global_iterator global_end () const { return GlobalList.end(); }
539 bool global_empty() const { return GlobalList.empty(); }
541 iterator_range<global_iterator> globals() {
542 return make_range(global_begin(), global_end());
544 iterator_range<const_global_iterator> globals() const {
545 return make_range(global_begin(), global_end());
549 /// @name Function Iteration
552 iterator begin() { return FunctionList.begin(); }
553 const_iterator begin() const { return FunctionList.begin(); }
554 iterator end () { return FunctionList.end(); }
555 const_iterator end () const { return FunctionList.end(); }
556 reverse_iterator rbegin() { return FunctionList.rbegin(); }
557 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
558 reverse_iterator rend() { return FunctionList.rend(); }
559 const_reverse_iterator rend() const { return FunctionList.rend(); }
560 size_t size() const { return FunctionList.size(); }
561 bool empty() const { return FunctionList.empty(); }
563 iterator_range<iterator> functions() {
564 return make_range(begin(), end());
566 iterator_range<const_iterator> functions() const {
567 return make_range(begin(), end());
571 /// @name Alias Iteration
574 alias_iterator alias_begin() { return AliasList.begin(); }
575 const_alias_iterator alias_begin() const { return AliasList.begin(); }
576 alias_iterator alias_end () { return AliasList.end(); }
577 const_alias_iterator alias_end () const { return AliasList.end(); }
578 size_t alias_size () const { return AliasList.size(); }
579 bool alias_empty() const { return AliasList.empty(); }
581 iterator_range<alias_iterator> aliases() {
582 return make_range(alias_begin(), alias_end());
584 iterator_range<const_alias_iterator> aliases() const {
585 return make_range(alias_begin(), alias_end());
589 /// @name IFunc Iteration
592 ifunc_iterator ifunc_begin() { return IFuncList.begin(); }
593 const_ifunc_iterator ifunc_begin() const { return IFuncList.begin(); }
594 ifunc_iterator ifunc_end () { return IFuncList.end(); }
595 const_ifunc_iterator ifunc_end () const { return IFuncList.end(); }
596 size_t ifunc_size () const { return IFuncList.size(); }
597 bool ifunc_empty() const { return IFuncList.empty(); }
599 iterator_range<ifunc_iterator> ifuncs() {
600 return make_range(ifunc_begin(), ifunc_end());
602 iterator_range<const_ifunc_iterator> ifuncs() const {
603 return make_range(ifunc_begin(), ifunc_end());
607 /// @name Convenience iterators
610 template <bool IsConst> class global_object_iterator_t {
613 typename std::conditional<IsConst, const_iterator, iterator>::type
616 typename std::conditional<IsConst, const_global_iterator,
617 global_iterator>::type global_i;
620 typename std::conditional<IsConst, const Module, Module>::type ModuleTy;
622 global_object_iterator_t(ModuleTy &M)
623 : function_i(M.begin()), function_e(M.end()),
624 global_i(M.global_begin()) {}
625 global_object_iterator_t(ModuleTy &M, int)
626 : function_i(M.end()), function_e(M.end()), global_i(M.global_end()) {}
629 global_object_iterator_t &operator++() {
630 if (function_i != function_e)
637 typename std::conditional<IsConst, const GlobalObject, GlobalObject>::type &
639 if (function_i != function_e)
645 bool operator!=(const global_object_iterator_t &other) const {
646 return function_i != other.function_i || global_i != other.global_i;
650 typedef global_object_iterator_t</*IsConst=*/false> global_object_iterator;
651 typedef global_object_iterator_t</*IsConst=*/true>
652 const_global_object_iterator;
654 global_object_iterator global_object_begin() {
655 return global_object_iterator(*this);
657 global_object_iterator global_object_end() {
658 return global_object_iterator(*this, 0);
661 const_global_object_iterator global_object_begin() const {
662 return const_global_object_iterator(*this);
664 const_global_object_iterator global_object_end() const {
665 return const_global_object_iterator(*this, 0);
668 iterator_range<global_object_iterator> global_objects() {
669 return make_range(global_object_begin(), global_object_end());
671 iterator_range<const_global_object_iterator> global_objects() const {
672 return make_range(global_object_begin(), global_object_end());
676 /// @name Named Metadata Iteration
679 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
680 const_named_metadata_iterator named_metadata_begin() const {
681 return NamedMDList.begin();
684 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
685 const_named_metadata_iterator named_metadata_end() const {
686 return NamedMDList.end();
689 size_t named_metadata_size() const { return NamedMDList.size(); }
690 bool named_metadata_empty() const { return NamedMDList.empty(); }
692 iterator_range<named_metadata_iterator> named_metadata() {
693 return make_range(named_metadata_begin(), named_metadata_end());
695 iterator_range<const_named_metadata_iterator> named_metadata() const {
696 return make_range(named_metadata_begin(), named_metadata_end());
699 /// An iterator for DICompileUnits that skips those marked NoDebug.
700 class debug_compile_units_iterator
701 : public std::iterator<std::input_iterator_tag, DICompileUnit *> {
704 void SkipNoDebugCUs();
706 explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
707 : CUs(CUs), Idx(Idx) {
710 debug_compile_units_iterator &operator++() {
715 debug_compile_units_iterator operator++(int) {
716 debug_compile_units_iterator T(*this);
720 bool operator==(const debug_compile_units_iterator &I) const {
723 bool operator!=(const debug_compile_units_iterator &I) const {
726 DICompileUnit *operator*() const;
727 DICompileUnit *operator->() const;
730 debug_compile_units_iterator debug_compile_units_begin() const {
731 auto *CUs = getNamedMetadata("llvm.dbg.cu");
732 return debug_compile_units_iterator(CUs, 0);
735 debug_compile_units_iterator debug_compile_units_end() const {
736 auto *CUs = getNamedMetadata("llvm.dbg.cu");
737 return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
740 /// Return an iterator for all DICompileUnits listed in this Module's
741 /// llvm.dbg.cu named metadata node and aren't explicitly marked as
743 iterator_range<debug_compile_units_iterator> debug_compile_units() const {
744 auto *CUs = getNamedMetadata("llvm.dbg.cu");
746 debug_compile_units_iterator(CUs, 0),
747 debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
751 /// Destroy ConstantArrays in LLVMContext if they are not used.
752 /// ConstantArrays constructed during linking can cause quadratic memory
753 /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
754 /// slowdown for a large application.
756 /// NOTE: Constants are currently owned by LLVMContext. This can then only
757 /// be called where all uses of the LLVMContext are understood.
758 void dropTriviallyDeadConstantArrays();
760 /// @name Utility functions for printing and dumping Module objects
763 /// Print the module to an output stream with an optional
764 /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
765 /// uselistorder directives so that use-lists can be recreated when reading
767 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
768 bool ShouldPreserveUseListOrder = false,
769 bool IsForDebug = false) const;
771 /// Dump the module to stderr (for debugging).
774 /// This function causes all the subinstructions to "let go" of all references
775 /// that they are maintaining. This allows one to 'delete' a whole class at
776 /// a time, even though there may be circular references... first all
777 /// references are dropped, and all use counts go to zero. Then everything
778 /// is delete'd for real. Note that no operations are valid on an object
779 /// that has "dropped all references", except operator delete.
780 void dropAllReferences();
783 /// @name Utility functions for querying Debug information.
786 /// \brief Returns the Dwarf Version by checking module flags.
787 unsigned getDwarfVersion() const;
789 /// \brief Returns the CodeView Version by checking module flags.
790 /// Returns zero if not present in module.
791 unsigned getCodeViewFlag() const;
794 /// @name Utility functions for querying and setting PIC level
797 /// \brief Returns the PIC level (small or large model)
798 PICLevel::Level getPICLevel() const;
800 /// \brief Set the PIC level (small or large model)
801 void setPICLevel(PICLevel::Level PL);
805 /// @name Utility functions for querying and setting PIE level
808 /// \brief Returns the PIE level (small or large model)
809 PIELevel::Level getPIELevel() const;
811 /// \brief Set the PIE level (small or large model)
812 void setPIELevel(PIELevel::Level PL);
815 /// @name Utility functions for querying and setting PGO summary
818 /// \brief Attach profile summary metadata to this module.
819 void setProfileSummary(Metadata *M);
821 /// \brief Returns profile summary metadata
822 Metadata *getProfileSummary();
826 /// \brief Given "llvm.used" or "llvm.compiler.used" as a global name, collect
827 /// the initializer elements of that global in Set and return the global itself.
828 GlobalVariable *collectUsedGlobalVariables(const Module &M,
829 SmallPtrSetImpl<GlobalValue *> &Set,
832 /// An raw_ostream inserter for modules.
833 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
838 // Create wrappers for C Binding types (see CBindingWrapping.h).
839 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
841 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
844 inline Module *unwrap(LLVMModuleProviderRef MP) {
845 return reinterpret_cast<Module*>(MP);
848 } // End llvm namespace