Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / Module.h
blob7373b84854119d1f6bada03e3e70726f98d47ec5
1 //===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// @file
10 /// Module.h This file contains the declarations for the Module class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_MODULE_H
15 #define LLVM_IR_MODULE_H
17 #include "llvm-c/Types.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Attributes.h"
24 #include "llvm/IR/Comdat.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalAlias.h"
28 #include "llvm/IR/GlobalIFunc.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/SymbolTableListTraits.h"
32 #include "llvm/Support/CBindingWrapping.h"
33 #include "llvm/Support/CodeGen.h"
34 #include <cstddef>
35 #include <cstdint>
36 #include <iterator>
37 #include <memory>
38 #include <string>
39 #include <vector>
41 namespace llvm {
43 class Error;
44 class FunctionType;
45 class GVMaterializer;
46 class LLVMContext;
47 class MemoryBuffer;
48 class RandomNumberGenerator;
49 template <class PtrType> class SmallPtrSetImpl;
50 class StructType;
51 class VersionTuple;
53 /// A Module instance is used to store all the information related to an
54 /// LLVM module. Modules are the top level container of all other LLVM
55 /// Intermediate Representation (IR) objects. Each module directly contains a
56 /// list of globals variables, a list of functions, a list of libraries (or
57 /// other modules) this module depends on, a symbol table, and various data
58 /// about the target's characteristics.
59 ///
60 /// A module maintains a GlobalValRefMap object that is used to hold all
61 /// constant references to global variables in the module. When a global
62 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
63 /// The main container class for the LLVM Intermediate Representation.
64 class Module {
65 /// @name Types And Enumerations
66 /// @{
67 public:
68 /// The type for the list of global variables.
69 using GlobalListType = SymbolTableList<GlobalVariable>;
70 /// The type for the list of functions.
71 using FunctionListType = SymbolTableList<Function>;
72 /// The type for the list of aliases.
73 using AliasListType = SymbolTableList<GlobalAlias>;
74 /// The type for the list of ifuncs.
75 using IFuncListType = SymbolTableList<GlobalIFunc>;
76 /// The type for the list of named metadata.
77 using NamedMDListType = ilist<NamedMDNode>;
78 /// The type of the comdat "symbol" table.
79 using ComdatSymTabType = StringMap<Comdat>;
81 /// The Global Variable iterator.
82 using global_iterator = GlobalListType::iterator;
83 /// The Global Variable constant iterator.
84 using const_global_iterator = GlobalListType::const_iterator;
86 /// The Function iterators.
87 using iterator = FunctionListType::iterator;
88 /// The Function constant iterator
89 using const_iterator = FunctionListType::const_iterator;
91 /// The Function reverse iterator.
92 using reverse_iterator = FunctionListType::reverse_iterator;
93 /// The Function constant reverse iterator.
94 using const_reverse_iterator = FunctionListType::const_reverse_iterator;
96 /// The Global Alias iterators.
97 using alias_iterator = AliasListType::iterator;
98 /// The Global Alias constant iterator
99 using const_alias_iterator = AliasListType::const_iterator;
101 /// The Global IFunc iterators.
102 using ifunc_iterator = IFuncListType::iterator;
103 /// The Global IFunc constant iterator
104 using const_ifunc_iterator = IFuncListType::const_iterator;
106 /// The named metadata iterators.
107 using named_metadata_iterator = NamedMDListType::iterator;
108 /// The named metadata constant iterators.
109 using const_named_metadata_iterator = NamedMDListType::const_iterator;
111 /// This enumeration defines the supported behaviors of module flags.
112 enum ModFlagBehavior {
113 /// Emits an error if two values disagree, otherwise the resulting value is
114 /// that of the operands.
115 Error = 1,
117 /// Emits a warning if two values disagree. The result value will be the
118 /// operand for the flag from the first module being linked.
119 Warning = 2,
121 /// Adds a requirement that another module flag be present and have a
122 /// specified value after linking is performed. The value must be a metadata
123 /// pair, where the first element of the pair is the ID of the module flag
124 /// to be restricted, and the second element of the pair is the value the
125 /// module flag should be restricted to. This behavior can be used to
126 /// restrict the allowable results (via triggering of an error) of linking
127 /// IDs with the **Override** behavior.
128 Require = 3,
130 /// Uses the specified value, regardless of the behavior or value of the
131 /// other module. If both modules specify **Override**, but the values
132 /// differ, an error will be emitted.
133 Override = 4,
135 /// Appends the two values, which are required to be metadata nodes.
136 Append = 5,
138 /// Appends the two values, which are required to be metadata
139 /// nodes. However, duplicate entries in the second list are dropped
140 /// during the append operation.
141 AppendUnique = 6,
143 /// Takes the max of the two values, which are required to be integers.
144 Max = 7,
146 // Markers:
147 ModFlagBehaviorFirstVal = Error,
148 ModFlagBehaviorLastVal = Max
151 /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
152 /// converted result in MFB.
153 static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
155 struct ModuleFlagEntry {
156 ModFlagBehavior Behavior;
157 MDString *Key;
158 Metadata *Val;
160 ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
161 : Behavior(B), Key(K), Val(V) {}
164 /// @}
165 /// @name Member Variables
166 /// @{
167 private:
168 LLVMContext &Context; ///< The LLVMContext from which types and
169 ///< constants are allocated.
170 GlobalListType GlobalList; ///< The Global Variables in the module
171 FunctionListType FunctionList; ///< The Functions in the module
172 AliasListType AliasList; ///< The Aliases in the module
173 IFuncListType IFuncList; ///< The IFuncs in the module
174 NamedMDListType NamedMDList; ///< The named metadata in the module
175 std::string GlobalScopeAsm; ///< Inline Asm at global scope.
176 ValueSymbolTable *ValSymTab; ///< Symbol table for values
177 ComdatSymTabType ComdatSymTab; ///< Symbol table for COMDATs
178 std::unique_ptr<MemoryBuffer>
179 OwnedMemoryBuffer; ///< Memory buffer directly owned by this
180 ///< module, for legacy clients only.
181 std::unique_ptr<GVMaterializer>
182 Materializer; ///< Used to materialize GlobalValues
183 std::string ModuleID; ///< Human readable identifier for the module
184 std::string SourceFileName; ///< Original source file name for module,
185 ///< recorded in bitcode.
186 std::string TargetTriple; ///< Platform target triple Module compiled on
187 ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
188 void *NamedMDSymTab; ///< NamedMDNode names.
189 DataLayout DL; ///< DataLayout associated with the module
191 friend class Constant;
193 /// @}
194 /// @name Constructors
195 /// @{
196 public:
197 /// The Module constructor. Note that there is no default constructor. You
198 /// must provide a name for the module upon construction.
199 explicit Module(StringRef ModuleID, LLVMContext& C);
200 /// The module destructor. This will dropAllReferences.
201 ~Module();
203 /// @}
204 /// @name Module Level Accessors
205 /// @{
207 /// Get the module identifier which is, essentially, the name of the module.
208 /// @returns the module identifier as a string
209 const std::string &getModuleIdentifier() const { return ModuleID; }
211 /// Returns the number of non-debug IR instructions in the module.
212 /// This is equivalent to the sum of the IR instruction counts of each
213 /// function contained in the module.
214 unsigned getInstructionCount();
216 /// Get the module's original source file name. When compiling from
217 /// bitcode, this is taken from a bitcode record where it was recorded.
218 /// For other compiles it is the same as the ModuleID, which would
219 /// contain the source file name.
220 const std::string &getSourceFileName() const { return SourceFileName; }
222 /// Get a short "name" for the module.
224 /// This is useful for debugging or logging. It is essentially a convenience
225 /// wrapper around getModuleIdentifier().
226 StringRef getName() const { return ModuleID; }
228 /// Get the data layout string for the module's target platform. This is
229 /// equivalent to getDataLayout()->getStringRepresentation().
230 const std::string &getDataLayoutStr() const {
231 return DL.getStringRepresentation();
234 /// Get the data layout for the module's target platform.
235 const DataLayout &getDataLayout() const;
237 /// Get the target triple which is a string describing the target host.
238 /// @returns a string containing the target triple.
239 const std::string &getTargetTriple() const { return TargetTriple; }
241 /// Get the global data context.
242 /// @returns LLVMContext - a container for LLVM's global information
243 LLVMContext &getContext() const { return Context; }
245 /// Get any module-scope inline assembly blocks.
246 /// @returns a string containing the module-scope inline assembly blocks.
247 const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
249 /// Get a RandomNumberGenerator salted for use with this module. The
250 /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
251 /// ModuleID and the provided pass salt. The returned RNG should not
252 /// be shared across threads or passes.
254 /// A unique RNG per pass ensures a reproducible random stream even
255 /// when other randomness consuming passes are added or removed. In
256 /// addition, the random stream will be reproducible across LLVM
257 /// versions when the pass does not change.
258 std::unique_ptr<RandomNumberGenerator> createRNG(const Pass* P) const;
260 /// Return true if size-info optimization remark is enabled, false
261 /// otherwise.
262 bool shouldEmitInstrCountChangedRemark() {
263 return getContext().getDiagHandlerPtr()->isAnalysisRemarkEnabled(
264 "size-info");
267 /// @}
268 /// @name Module Level Mutators
269 /// @{
271 /// Set the module identifier.
272 void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
274 /// Set the module's original source file name.
275 void setSourceFileName(StringRef Name) { SourceFileName = Name; }
277 /// Set the data layout
278 void setDataLayout(StringRef Desc);
279 void setDataLayout(const DataLayout &Other);
281 /// Set the target triple.
282 void setTargetTriple(StringRef T) { TargetTriple = T; }
284 /// Set the module-scope inline assembly blocks.
285 /// A trailing newline is added if the input doesn't have one.
286 void setModuleInlineAsm(StringRef Asm) {
287 GlobalScopeAsm = Asm;
288 if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
289 GlobalScopeAsm += '\n';
292 /// Append to the module-scope inline assembly blocks.
293 /// A trailing newline is added if the input doesn't have one.
294 void appendModuleInlineAsm(StringRef Asm) {
295 GlobalScopeAsm += Asm;
296 if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
297 GlobalScopeAsm += '\n';
300 /// @}
301 /// @name Generic Value Accessors
302 /// @{
304 /// Return the global value in the module with the specified name, of
305 /// arbitrary type. This method returns null if a global with the specified
306 /// name is not found.
307 GlobalValue *getNamedValue(StringRef Name) const;
309 /// Return a unique non-zero ID for the specified metadata kind. This ID is
310 /// uniqued across modules in the current LLVMContext.
311 unsigned getMDKindID(StringRef Name) const;
313 /// Populate client supplied SmallVector with the name for custom metadata IDs
314 /// registered in this LLVMContext.
315 void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
317 /// Populate client supplied SmallVector with the bundle tags registered in
318 /// this LLVMContext. The bundle tags are ordered by increasing bundle IDs.
319 /// \see LLVMContext::getOperandBundleTagID
320 void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
322 /// Return the type with the specified name, or null if there is none by that
323 /// name.
324 StructType *getTypeByName(StringRef Name) const;
326 std::vector<StructType *> getIdentifiedStructTypes() const;
328 /// @}
329 /// @name Function Accessors
330 /// @{
332 /// Look up the specified function in the module symbol table. Four
333 /// possibilities:
334 /// 1. If it does not exist, add a prototype for the function and return it.
335 /// 2. Otherwise, if the existing function has the correct prototype, return
336 /// the existing function.
337 /// 3. Finally, the function exists but has the wrong prototype: return the
338 /// function with a constantexpr cast to the right prototype.
340 /// In all cases, the returned value is a FunctionCallee wrapper around the
341 /// 'FunctionType *T' passed in, as well as a 'Value*' either of the Function or
342 /// the bitcast to the function.
343 FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T,
344 AttributeList AttributeList);
346 FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T);
348 /// Look up the specified function in the module symbol table. If it does not
349 /// exist, add a prototype for the function and return it. This function
350 /// guarantees to return a constant of pointer to the specified function type
351 /// or a ConstantExpr BitCast of that type if the named function has a
352 /// different type. This version of the method takes a list of
353 /// function arguments, which makes it easier for clients to use.
354 template <typename... ArgsTy>
355 FunctionCallee getOrInsertFunction(StringRef Name,
356 AttributeList AttributeList, Type *RetTy,
357 ArgsTy... Args) {
358 SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
359 return getOrInsertFunction(Name,
360 FunctionType::get(RetTy, ArgTys, false),
361 AttributeList);
364 /// Same as above, but without the attributes.
365 template <typename... ArgsTy>
366 FunctionCallee getOrInsertFunction(StringRef Name, Type *RetTy,
367 ArgsTy... Args) {
368 return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
371 // Avoid an incorrect ordering that'd otherwise compile incorrectly.
372 template <typename... ArgsTy>
373 FunctionCallee
374 getOrInsertFunction(StringRef Name, AttributeList AttributeList,
375 FunctionType *Invalid, ArgsTy... Args) = delete;
377 /// Look up the specified function in the module symbol table. If it does not
378 /// exist, return null.
379 Function *getFunction(StringRef Name) const;
381 /// @}
382 /// @name Global Variable Accessors
383 /// @{
385 /// Look up the specified global variable in the module symbol table. If it
386 /// does not exist, return null. If AllowInternal is set to true, this
387 /// function will return types that have InternalLinkage. By default, these
388 /// types are not returned.
389 GlobalVariable *getGlobalVariable(StringRef Name) const {
390 return getGlobalVariable(Name, false);
393 GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
395 GlobalVariable *getGlobalVariable(StringRef Name,
396 bool AllowInternal = false) {
397 return static_cast<const Module *>(this)->getGlobalVariable(Name,
398 AllowInternal);
401 /// Return the global variable in the module with the specified name, of
402 /// arbitrary type. This method returns null if a global with the specified
403 /// name is not found.
404 const GlobalVariable *getNamedGlobal(StringRef Name) const {
405 return getGlobalVariable(Name, true);
407 GlobalVariable *getNamedGlobal(StringRef Name) {
408 return const_cast<GlobalVariable *>(
409 static_cast<const Module *>(this)->getNamedGlobal(Name));
412 /// Look up the specified global in the module symbol table.
413 /// If it does not exist, invoke a callback to create a declaration of the
414 /// global and return it. The global is constantexpr casted to the expected
415 /// type if necessary.
416 Constant *
417 getOrInsertGlobal(StringRef Name, Type *Ty,
418 function_ref<GlobalVariable *()> CreateGlobalCallback);
420 /// Look up the specified global in the module symbol table. If required, this
421 /// overload constructs the global variable using its constructor's defaults.
422 Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
424 /// @}
425 /// @name Global Alias Accessors
426 /// @{
428 /// Return the global alias in the module with the specified name, of
429 /// arbitrary type. This method returns null if a global with the specified
430 /// name is not found.
431 GlobalAlias *getNamedAlias(StringRef Name) const;
433 /// @}
434 /// @name Global IFunc Accessors
435 /// @{
437 /// Return the global ifunc in the module with the specified name, of
438 /// arbitrary type. This method returns null if a global with the specified
439 /// name is not found.
440 GlobalIFunc *getNamedIFunc(StringRef Name) const;
442 /// @}
443 /// @name Named Metadata Accessors
444 /// @{
446 /// Return the first NamedMDNode in the module with the specified name. This
447 /// method returns null if a NamedMDNode with the specified name is not found.
448 NamedMDNode *getNamedMetadata(const Twine &Name) const;
450 /// Return the named MDNode in the module with the specified name. This method
451 /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
452 /// found.
453 NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
455 /// Remove the given NamedMDNode from this module and delete it.
456 void eraseNamedMetadata(NamedMDNode *NMD);
458 /// @}
459 /// @name Comdat Accessors
460 /// @{
462 /// Return the Comdat in the module with the specified name. It is created
463 /// if it didn't already exist.
464 Comdat *getOrInsertComdat(StringRef Name);
466 /// @}
467 /// @name Module Flags Accessors
468 /// @{
470 /// Returns the module flags in the provided vector.
471 void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
473 /// Return the corresponding value if Key appears in module flags, otherwise
474 /// return null.
475 Metadata *getModuleFlag(StringRef Key) const;
477 /// Returns the NamedMDNode in the module that represents module-level flags.
478 /// This method returns null if there are no module-level flags.
479 NamedMDNode *getModuleFlagsMetadata() const;
481 /// Returns the NamedMDNode in the module that represents module-level flags.
482 /// If module-level flags aren't found, it creates the named metadata that
483 /// contains them.
484 NamedMDNode *getOrInsertModuleFlagsMetadata();
486 /// Add a module-level flag to the module-level flags metadata. It will create
487 /// the module-level flags named metadata if it doesn't already exist.
488 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
489 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
490 void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
491 void addModuleFlag(MDNode *Node);
493 /// @}
494 /// @name Materialization
495 /// @{
497 /// Sets the GVMaterializer to GVM. This module must not yet have a
498 /// Materializer. To reset the materializer for a module that already has one,
499 /// call materializeAll first. Destroying this module will destroy
500 /// its materializer without materializing any more GlobalValues. Without
501 /// destroying the Module, there is no way to detach or destroy a materializer
502 /// without materializing all the GVs it controls, to avoid leaving orphan
503 /// unmaterialized GVs.
504 void setMaterializer(GVMaterializer *GVM);
505 /// Retrieves the GVMaterializer, if any, for this Module.
506 GVMaterializer *getMaterializer() const { return Materializer.get(); }
507 bool isMaterialized() const { return !getMaterializer(); }
509 /// Make sure the GlobalValue is fully read.
510 llvm::Error materialize(GlobalValue *GV);
512 /// Make sure all GlobalValues in this Module are fully read and clear the
513 /// Materializer.
514 llvm::Error materializeAll();
516 llvm::Error materializeMetadata();
518 /// @}
519 /// @name Direct access to the globals list, functions list, and symbol table
520 /// @{
522 /// Get the Module's list of global variables (constant).
523 const GlobalListType &getGlobalList() const { return GlobalList; }
524 /// Get the Module's list of global variables.
525 GlobalListType &getGlobalList() { return GlobalList; }
527 static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
528 return &Module::GlobalList;
531 /// Get the Module's list of functions (constant).
532 const FunctionListType &getFunctionList() const { return FunctionList; }
533 /// Get the Module's list of functions.
534 FunctionListType &getFunctionList() { return FunctionList; }
535 static FunctionListType Module::*getSublistAccess(Function*) {
536 return &Module::FunctionList;
539 /// Get the Module's list of aliases (constant).
540 const AliasListType &getAliasList() const { return AliasList; }
541 /// Get the Module's list of aliases.
542 AliasListType &getAliasList() { return AliasList; }
544 static AliasListType Module::*getSublistAccess(GlobalAlias*) {
545 return &Module::AliasList;
548 /// Get the Module's list of ifuncs (constant).
549 const IFuncListType &getIFuncList() const { return IFuncList; }
550 /// Get the Module's list of ifuncs.
551 IFuncListType &getIFuncList() { return IFuncList; }
553 static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
554 return &Module::IFuncList;
557 /// Get the Module's list of named metadata (constant).
558 const NamedMDListType &getNamedMDList() const { return NamedMDList; }
559 /// Get the Module's list of named metadata.
560 NamedMDListType &getNamedMDList() { return NamedMDList; }
562 static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
563 return &Module::NamedMDList;
566 /// Get the symbol table of global variable and function identifiers
567 const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
568 /// Get the Module's symbol table of global variable and function identifiers.
569 ValueSymbolTable &getValueSymbolTable() { return *ValSymTab; }
571 /// Get the Module's symbol table for COMDATs (constant).
572 const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
573 /// Get the Module's symbol table for COMDATs.
574 ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
576 /// @}
577 /// @name Global Variable Iteration
578 /// @{
580 global_iterator global_begin() { return GlobalList.begin(); }
581 const_global_iterator global_begin() const { return GlobalList.begin(); }
582 global_iterator global_end () { return GlobalList.end(); }
583 const_global_iterator global_end () const { return GlobalList.end(); }
584 bool global_empty() const { return GlobalList.empty(); }
586 iterator_range<global_iterator> globals() {
587 return make_range(global_begin(), global_end());
589 iterator_range<const_global_iterator> globals() const {
590 return make_range(global_begin(), global_end());
593 /// @}
594 /// @name Function Iteration
595 /// @{
597 iterator begin() { return FunctionList.begin(); }
598 const_iterator begin() const { return FunctionList.begin(); }
599 iterator end () { return FunctionList.end(); }
600 const_iterator end () const { return FunctionList.end(); }
601 reverse_iterator rbegin() { return FunctionList.rbegin(); }
602 const_reverse_iterator rbegin() const{ return FunctionList.rbegin(); }
603 reverse_iterator rend() { return FunctionList.rend(); }
604 const_reverse_iterator rend() const { return FunctionList.rend(); }
605 size_t size() const { return FunctionList.size(); }
606 bool empty() const { return FunctionList.empty(); }
608 iterator_range<iterator> functions() {
609 return make_range(begin(), end());
611 iterator_range<const_iterator> functions() const {
612 return make_range(begin(), end());
615 /// @}
616 /// @name Alias Iteration
617 /// @{
619 alias_iterator alias_begin() { return AliasList.begin(); }
620 const_alias_iterator alias_begin() const { return AliasList.begin(); }
621 alias_iterator alias_end () { return AliasList.end(); }
622 const_alias_iterator alias_end () const { return AliasList.end(); }
623 size_t alias_size () const { return AliasList.size(); }
624 bool alias_empty() const { return AliasList.empty(); }
626 iterator_range<alias_iterator> aliases() {
627 return make_range(alias_begin(), alias_end());
629 iterator_range<const_alias_iterator> aliases() const {
630 return make_range(alias_begin(), alias_end());
633 /// @}
634 /// @name IFunc Iteration
635 /// @{
637 ifunc_iterator ifunc_begin() { return IFuncList.begin(); }
638 const_ifunc_iterator ifunc_begin() const { return IFuncList.begin(); }
639 ifunc_iterator ifunc_end () { return IFuncList.end(); }
640 const_ifunc_iterator ifunc_end () const { return IFuncList.end(); }
641 size_t ifunc_size () const { return IFuncList.size(); }
642 bool ifunc_empty() const { return IFuncList.empty(); }
644 iterator_range<ifunc_iterator> ifuncs() {
645 return make_range(ifunc_begin(), ifunc_end());
647 iterator_range<const_ifunc_iterator> ifuncs() const {
648 return make_range(ifunc_begin(), ifunc_end());
651 /// @}
652 /// @name Convenience iterators
653 /// @{
655 using global_object_iterator =
656 concat_iterator<GlobalObject, iterator, global_iterator>;
657 using const_global_object_iterator =
658 concat_iterator<const GlobalObject, const_iterator,
659 const_global_iterator>;
661 iterator_range<global_object_iterator> global_objects() {
662 return concat<GlobalObject>(functions(), globals());
664 iterator_range<const_global_object_iterator> global_objects() const {
665 return concat<const GlobalObject>(functions(), globals());
668 global_object_iterator global_object_begin() {
669 return global_objects().begin();
671 global_object_iterator global_object_end() { return global_objects().end(); }
673 const_global_object_iterator global_object_begin() const {
674 return global_objects().begin();
676 const_global_object_iterator global_object_end() const {
677 return global_objects().end();
680 using global_value_iterator =
681 concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator,
682 ifunc_iterator>;
683 using const_global_value_iterator =
684 concat_iterator<const GlobalValue, const_iterator, const_global_iterator,
685 const_alias_iterator, const_ifunc_iterator>;
687 iterator_range<global_value_iterator> global_values() {
688 return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
690 iterator_range<const_global_value_iterator> global_values() const {
691 return concat<const GlobalValue>(functions(), globals(), aliases(),
692 ifuncs());
695 global_value_iterator global_value_begin() { return global_values().begin(); }
696 global_value_iterator global_value_end() { return global_values().end(); }
698 const_global_value_iterator global_value_begin() const {
699 return global_values().begin();
701 const_global_value_iterator global_value_end() const {
702 return global_values().end();
705 /// @}
706 /// @name Named Metadata Iteration
707 /// @{
709 named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
710 const_named_metadata_iterator named_metadata_begin() const {
711 return NamedMDList.begin();
714 named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
715 const_named_metadata_iterator named_metadata_end() const {
716 return NamedMDList.end();
719 size_t named_metadata_size() const { return NamedMDList.size(); }
720 bool named_metadata_empty() const { return NamedMDList.empty(); }
722 iterator_range<named_metadata_iterator> named_metadata() {
723 return make_range(named_metadata_begin(), named_metadata_end());
725 iterator_range<const_named_metadata_iterator> named_metadata() const {
726 return make_range(named_metadata_begin(), named_metadata_end());
729 /// An iterator for DICompileUnits that skips those marked NoDebug.
730 class debug_compile_units_iterator
731 : public std::iterator<std::input_iterator_tag, DICompileUnit *> {
732 NamedMDNode *CUs;
733 unsigned Idx;
735 void SkipNoDebugCUs();
737 public:
738 explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
739 : CUs(CUs), Idx(Idx) {
740 SkipNoDebugCUs();
743 debug_compile_units_iterator &operator++() {
744 ++Idx;
745 SkipNoDebugCUs();
746 return *this;
749 debug_compile_units_iterator operator++(int) {
750 debug_compile_units_iterator T(*this);
751 ++Idx;
752 return T;
755 bool operator==(const debug_compile_units_iterator &I) const {
756 return Idx == I.Idx;
759 bool operator!=(const debug_compile_units_iterator &I) const {
760 return Idx != I.Idx;
763 DICompileUnit *operator*() const;
764 DICompileUnit *operator->() const;
767 debug_compile_units_iterator debug_compile_units_begin() const {
768 auto *CUs = getNamedMetadata("llvm.dbg.cu");
769 return debug_compile_units_iterator(CUs, 0);
772 debug_compile_units_iterator debug_compile_units_end() const {
773 auto *CUs = getNamedMetadata("llvm.dbg.cu");
774 return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
777 /// Return an iterator for all DICompileUnits listed in this Module's
778 /// llvm.dbg.cu named metadata node and aren't explicitly marked as
779 /// NoDebug.
780 iterator_range<debug_compile_units_iterator> debug_compile_units() const {
781 auto *CUs = getNamedMetadata("llvm.dbg.cu");
782 return make_range(
783 debug_compile_units_iterator(CUs, 0),
784 debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
786 /// @}
788 /// Destroy ConstantArrays in LLVMContext if they are not used.
789 /// ConstantArrays constructed during linking can cause quadratic memory
790 /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
791 /// slowdown for a large application.
793 /// NOTE: Constants are currently owned by LLVMContext. This can then only
794 /// be called where all uses of the LLVMContext are understood.
795 void dropTriviallyDeadConstantArrays();
797 /// @name Utility functions for printing and dumping Module objects
798 /// @{
800 /// Print the module to an output stream with an optional
801 /// AssemblyAnnotationWriter. If \c ShouldPreserveUseListOrder, then include
802 /// uselistorder directives so that use-lists can be recreated when reading
803 /// the assembly.
804 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
805 bool ShouldPreserveUseListOrder = false,
806 bool IsForDebug = false) const;
808 /// Dump the module to stderr (for debugging).
809 void dump() const;
811 /// This function causes all the subinstructions to "let go" of all references
812 /// that they are maintaining. This allows one to 'delete' a whole class at
813 /// a time, even though there may be circular references... first all
814 /// references are dropped, and all use counts go to zero. Then everything
815 /// is delete'd for real. Note that no operations are valid on an object
816 /// that has "dropped all references", except operator delete.
817 void dropAllReferences();
819 /// @}
820 /// @name Utility functions for querying Debug information.
821 /// @{
823 /// Returns the Number of Register ParametersDwarf Version by checking
824 /// module flags.
825 unsigned getNumberRegisterParameters() const;
827 /// Returns the Dwarf Version by checking module flags.
828 unsigned getDwarfVersion() const;
830 /// Returns the CodeView Version by checking module flags.
831 /// Returns zero if not present in module.
832 unsigned getCodeViewFlag() const;
834 /// @}
835 /// @name Utility functions for querying and setting PIC level
836 /// @{
838 /// Returns the PIC level (small or large model)
839 PICLevel::Level getPICLevel() const;
841 /// Set the PIC level (small or large model)
842 void setPICLevel(PICLevel::Level PL);
843 /// @}
845 /// @}
846 /// @name Utility functions for querying and setting PIE level
847 /// @{
849 /// Returns the PIE level (small or large model)
850 PIELevel::Level getPIELevel() const;
852 /// Set the PIE level (small or large model)
853 void setPIELevel(PIELevel::Level PL);
854 /// @}
856 /// @}
857 /// @name Utility function for querying and setting code model
858 /// @{
860 /// Returns the code model (tiny, small, kernel, medium or large model)
861 Optional<CodeModel::Model> getCodeModel() const;
863 /// Set the code model (tiny, small, kernel, medium or large)
864 void setCodeModel(CodeModel::Model CL);
865 /// @}
867 /// @name Utility functions for querying and setting PGO summary
868 /// @{
870 /// Attach profile summary metadata to this module.
871 void setProfileSummary(Metadata *M);
873 /// Returns profile summary metadata
874 Metadata *getProfileSummary();
875 /// @}
877 /// Returns true if PLT should be avoided for RTLib calls.
878 bool getRtLibUseGOT() const;
880 /// Set that PLT should be avoid for RTLib calls.
881 void setRtLibUseGOT();
883 /// @name Utility functions for querying and setting the build SDK version
884 /// @{
886 /// Attach a build SDK version metadata to this module.
887 void setSDKVersion(const VersionTuple &V);
889 /// Get the build SDK version metadata.
891 /// An empty version is returned if no such metadata is attached.
892 VersionTuple getSDKVersion() const;
893 /// @}
895 /// Take ownership of the given memory buffer.
896 void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
899 /// Given "llvm.used" or "llvm.compiler.used" as a global name, collect
900 /// the initializer elements of that global in Set and return the global itself.
901 GlobalVariable *collectUsedGlobalVariables(const Module &M,
902 SmallPtrSetImpl<GlobalValue *> &Set,
903 bool CompilerUsed);
905 /// An raw_ostream inserter for modules.
906 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
907 M.print(O, nullptr);
908 return O;
911 // Create wrappers for C Binding types (see CBindingWrapping.h).
912 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
914 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
915 * Module.
917 inline Module *unwrap(LLVMModuleProviderRef MP) {
918 return reinterpret_cast<Module*>(MP);
921 } // end namespace llvm
923 #endif // LLVM_IR_MODULE_H