Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:08

0001 //===- llvm/Module.h - C++ class to represent a VM module -------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// @file
0010 /// Module.h This file contains the declarations for the Module class.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_IR_MODULE_H
0015 #define LLVM_IR_MODULE_H
0016 
0017 #include "llvm-c/Types.h"
0018 #include "llvm/ADT/STLExtras.h"
0019 #include "llvm/ADT/StringMap.h"
0020 #include "llvm/ADT/StringRef.h"
0021 #include "llvm/ADT/iterator_range.h"
0022 #include "llvm/IR/Attributes.h"
0023 #include "llvm/IR/Comdat.h"
0024 #include "llvm/IR/DataLayout.h"
0025 #include "llvm/IR/Function.h"
0026 #include "llvm/IR/GlobalAlias.h"
0027 #include "llvm/IR/GlobalIFunc.h"
0028 #include "llvm/IR/GlobalVariable.h"
0029 #include "llvm/IR/Metadata.h"
0030 #include "llvm/IR/ProfileSummary.h"
0031 #include "llvm/IR/SymbolTableListTraits.h"
0032 #include "llvm/Support/CBindingWrapping.h"
0033 #include "llvm/Support/CodeGen.h"
0034 #include <cstddef>
0035 #include <cstdint>
0036 #include <iterator>
0037 #include <memory>
0038 #include <optional>
0039 #include <string>
0040 #include <vector>
0041 
0042 namespace llvm {
0043 
0044 class Error;
0045 class FunctionType;
0046 class GVMaterializer;
0047 class LLVMContext;
0048 class MemoryBuffer;
0049 class ModuleSummaryIndex;
0050 class RandomNumberGenerator;
0051 class StructType;
0052 class VersionTuple;
0053 
0054 /// A Module instance is used to store all the information related to an
0055 /// LLVM module. Modules are the top level container of all other LLVM
0056 /// Intermediate Representation (IR) objects. Each module directly contains a
0057 /// list of globals variables, a list of functions, a list of libraries (or
0058 /// other modules) this module depends on, a symbol table, and various data
0059 /// about the target's characteristics.
0060 ///
0061 /// A module maintains a GlobalList object that is used to hold all
0062 /// constant references to global variables in the module.  When a global
0063 /// variable is destroyed, it should have no entries in the GlobalList.
0064 /// The main container class for the LLVM Intermediate Representation.
0065 class LLVM_ABI Module {
0066   /// @name Types And Enumerations
0067   /// @{
0068 public:
0069   /// The type for the list of global variables.
0070   using GlobalListType = SymbolTableList<GlobalVariable>;
0071   /// The type for the list of functions.
0072   using FunctionListType = SymbolTableList<Function>;
0073   /// The type for the list of aliases.
0074   using AliasListType = SymbolTableList<GlobalAlias>;
0075   /// The type for the list of ifuncs.
0076   using IFuncListType = SymbolTableList<GlobalIFunc>;
0077   /// The type for the list of named metadata.
0078   using NamedMDListType = ilist<NamedMDNode>;
0079   /// The type of the comdat "symbol" table.
0080   using ComdatSymTabType = StringMap<Comdat>;
0081   /// The type for mapping names to named metadata.
0082   using NamedMDSymTabType = StringMap<NamedMDNode *>;
0083 
0084   /// The Global Variable iterator.
0085   using global_iterator = GlobalListType::iterator;
0086   /// The Global Variable constant iterator.
0087   using const_global_iterator = GlobalListType::const_iterator;
0088 
0089   /// The Function iterators.
0090   using iterator = FunctionListType::iterator;
0091   /// The Function constant iterator
0092   using const_iterator = FunctionListType::const_iterator;
0093 
0094   /// The Function reverse iterator.
0095   using reverse_iterator = FunctionListType::reverse_iterator;
0096   /// The Function constant reverse iterator.
0097   using const_reverse_iterator = FunctionListType::const_reverse_iterator;
0098 
0099   /// The Global Alias iterators.
0100   using alias_iterator = AliasListType::iterator;
0101   /// The Global Alias constant iterator
0102   using const_alias_iterator = AliasListType::const_iterator;
0103 
0104   /// The Global IFunc iterators.
0105   using ifunc_iterator = IFuncListType::iterator;
0106   /// The Global IFunc constant iterator
0107   using const_ifunc_iterator = IFuncListType::const_iterator;
0108 
0109   /// The named metadata iterators.
0110   using named_metadata_iterator = NamedMDListType::iterator;
0111   /// The named metadata constant iterators.
0112   using const_named_metadata_iterator = NamedMDListType::const_iterator;
0113 
0114   /// This enumeration defines the supported behaviors of module flags.
0115   enum ModFlagBehavior {
0116     /// Emits an error if two values disagree, otherwise the resulting value is
0117     /// that of the operands.
0118     Error = 1,
0119 
0120     /// Emits a warning if two values disagree. The result value will be the
0121     /// operand for the flag from the first module being linked.
0122     Warning = 2,
0123 
0124     /// Adds a requirement that another module flag be present and have a
0125     /// specified value after linking is performed. The value must be a metadata
0126     /// pair, where the first element of the pair is the ID of the module flag
0127     /// to be restricted, and the second element of the pair is the value the
0128     /// module flag should be restricted to. This behavior can be used to
0129     /// restrict the allowable results (via triggering of an error) of linking
0130     /// IDs with the **Override** behavior.
0131     Require = 3,
0132 
0133     /// Uses the specified value, regardless of the behavior or value of the
0134     /// other module. If both modules specify **Override**, but the values
0135     /// differ, an error will be emitted.
0136     Override = 4,
0137 
0138     /// Appends the two values, which are required to be metadata nodes.
0139     Append = 5,
0140 
0141     /// Appends the two values, which are required to be metadata
0142     /// nodes. However, duplicate entries in the second list are dropped
0143     /// during the append operation.
0144     AppendUnique = 6,
0145 
0146     /// Takes the max of the two values, which are required to be integers.
0147     Max = 7,
0148 
0149     /// Takes the min of the two values, which are required to be integers.
0150     Min = 8,
0151 
0152     // Markers:
0153     ModFlagBehaviorFirstVal = Error,
0154     ModFlagBehaviorLastVal = Min
0155   };
0156 
0157   /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
0158   /// converted result in MFB.
0159   static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
0160 
0161   struct ModuleFlagEntry {
0162     ModFlagBehavior Behavior;
0163     MDString *Key;
0164     Metadata *Val;
0165 
0166     ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
0167         : Behavior(B), Key(K), Val(V) {}
0168   };
0169 
0170 /// @}
0171 /// @name Member Variables
0172 /// @{
0173 private:
0174   LLVMContext &Context;           ///< The LLVMContext from which types and
0175                                   ///< constants are allocated.
0176   GlobalListType GlobalList;      ///< The Global Variables in the module
0177   FunctionListType FunctionList;  ///< The Functions in the module
0178   AliasListType AliasList;        ///< The Aliases in the module
0179   IFuncListType IFuncList;        ///< The IFuncs in the module
0180   NamedMDListType NamedMDList;    ///< The named metadata in the module
0181   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
0182   std::unique_ptr<ValueSymbolTable> ValSymTab; ///< Symbol table for values
0183   ComdatSymTabType ComdatSymTab;  ///< Symbol table for COMDATs
0184   std::unique_ptr<MemoryBuffer>
0185   OwnedMemoryBuffer;              ///< Memory buffer directly owned by this
0186                                   ///< module, for legacy clients only.
0187   std::unique_ptr<GVMaterializer>
0188   Materializer;                   ///< Used to materialize GlobalValues
0189   std::string ModuleID;           ///< Human readable identifier for the module
0190   std::string SourceFileName;     ///< Original source file name for module,
0191                                   ///< recorded in bitcode.
0192   std::string TargetTriple;       ///< Platform target triple Module compiled on
0193                                   ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
0194   NamedMDSymTabType NamedMDSymTab;  ///< NamedMDNode names.
0195   DataLayout DL;                  ///< DataLayout associated with the module
0196   StringMap<unsigned>
0197       CurrentIntrinsicIds; ///< Keep track of the current unique id count for
0198                            ///< the specified intrinsic basename.
0199   DenseMap<std::pair<Intrinsic::ID, const FunctionType *>, unsigned>
0200       UniquedIntrinsicNames; ///< Keep track of uniqued names of intrinsics
0201                              ///< based on unnamed types. The combination of
0202                              ///< ID and FunctionType maps to the extension that
0203                              ///< is used to make the intrinsic name unique.
0204 
0205   /// llvm.module.flags metadata
0206   NamedMDNode *ModuleFlags = nullptr;
0207 
0208   friend class Constant;
0209 
0210 /// @}
0211 /// @name Constructors
0212 /// @{
0213 public:
0214   /// Is this Module using intrinsics to record the position of debugging
0215   /// information, or non-intrinsic records? See IsNewDbgInfoFormat in
0216   /// \ref BasicBlock.
0217   bool IsNewDbgInfoFormat;
0218 
0219   /// Used when printing this module in the new debug info format; removes all
0220   /// declarations of debug intrinsics that are replaced by non-intrinsic
0221   /// records in the new format.
0222   void removeDebugIntrinsicDeclarations();
0223 
0224   /// \see BasicBlock::convertToNewDbgValues.
0225   void convertToNewDbgValues() {
0226     for (auto &F : *this) {
0227       F.convertToNewDbgValues();
0228     }
0229     IsNewDbgInfoFormat = true;
0230   }
0231 
0232   /// \see BasicBlock::convertFromNewDbgValues.
0233   void convertFromNewDbgValues() {
0234     for (auto &F : *this) {
0235       F.convertFromNewDbgValues();
0236     }
0237     IsNewDbgInfoFormat = false;
0238   }
0239 
0240   void setIsNewDbgInfoFormat(bool UseNewFormat) {
0241     if (UseNewFormat && !IsNewDbgInfoFormat)
0242       convertToNewDbgValues();
0243     else if (!UseNewFormat && IsNewDbgInfoFormat)
0244       convertFromNewDbgValues();
0245   }
0246   void setNewDbgInfoFormatFlag(bool NewFlag) {
0247     for (auto &F : *this) {
0248       F.setNewDbgInfoFormatFlag(NewFlag);
0249     }
0250     IsNewDbgInfoFormat = NewFlag;
0251   }
0252 
0253   /// The Module constructor. Note that there is no default constructor. You
0254   /// must provide a name for the module upon construction.
0255   explicit Module(StringRef ModuleID, LLVMContext& C);
0256   /// The module destructor. This will dropAllReferences.
0257   ~Module();
0258 
0259   /// Move assignment.
0260   Module &operator=(Module &&Other);
0261 
0262   /// @}
0263   /// @name Module Level Accessors
0264   /// @{
0265 
0266   /// Get the module identifier which is, essentially, the name of the module.
0267   /// @returns the module identifier as a string
0268   const std::string &getModuleIdentifier() const { return ModuleID; }
0269 
0270   /// Returns the number of non-debug IR instructions in the module.
0271   /// This is equivalent to the sum of the IR instruction counts of each
0272   /// function contained in the module.
0273   unsigned getInstructionCount() const;
0274 
0275   /// Get the module's original source file name. When compiling from
0276   /// bitcode, this is taken from a bitcode record where it was recorded.
0277   /// For other compiles it is the same as the ModuleID, which would
0278   /// contain the source file name.
0279   const std::string &getSourceFileName() const { return SourceFileName; }
0280 
0281   /// Get a short "name" for the module.
0282   ///
0283   /// This is useful for debugging or logging. It is essentially a convenience
0284   /// wrapper around getModuleIdentifier().
0285   StringRef getName() const { return ModuleID; }
0286 
0287   /// Get the data layout string for the module's target platform. This is
0288   /// equivalent to getDataLayout()->getStringRepresentation().
0289   const std::string &getDataLayoutStr() const {
0290     return DL.getStringRepresentation();
0291   }
0292 
0293   /// Get the data layout for the module's target platform.
0294   const DataLayout &getDataLayout() const { return DL; }
0295 
0296   /// Get the target triple which is a string describing the target host.
0297   /// @returns a string containing the target triple.
0298   const std::string &getTargetTriple() const { return TargetTriple; }
0299 
0300   /// Get the global data context.
0301   /// @returns LLVMContext - a container for LLVM's global information
0302   LLVMContext &getContext() const { return Context; }
0303 
0304   /// Get any module-scope inline assembly blocks.
0305   /// @returns a string containing the module-scope inline assembly blocks.
0306   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
0307 
0308   /// Get a RandomNumberGenerator salted for use with this module. The
0309   /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
0310   /// ModuleID and the provided pass salt. The returned RNG should not
0311   /// be shared across threads or passes.
0312   ///
0313   /// A unique RNG per pass ensures a reproducible random stream even
0314   /// when other randomness consuming passes are added or removed. In
0315   /// addition, the random stream will be reproducible across LLVM
0316   /// versions when the pass does not change.
0317   std::unique_ptr<RandomNumberGenerator> createRNG(const StringRef Name) const;
0318 
0319   /// Return true if size-info optimization remark is enabled, false
0320   /// otherwise.
0321   bool shouldEmitInstrCountChangedRemark() {
0322     return getContext().getDiagHandlerPtr()->isAnalysisRemarkEnabled(
0323         "size-info");
0324   }
0325 
0326   /// @}
0327   /// @name Module Level Mutators
0328   /// @{
0329 
0330   /// Set the module identifier.
0331   void setModuleIdentifier(StringRef ID) { ModuleID = std::string(ID); }
0332 
0333   /// Set the module's original source file name.
0334   void setSourceFileName(StringRef Name) { SourceFileName = std::string(Name); }
0335 
0336   /// Set the data layout
0337   void setDataLayout(StringRef Desc);
0338   void setDataLayout(const DataLayout &Other);
0339 
0340   /// Set the target triple.
0341   void setTargetTriple(StringRef T) { TargetTriple = std::string(T); }
0342 
0343   /// Set the module-scope inline assembly blocks.
0344   /// A trailing newline is added if the input doesn't have one.
0345   void setModuleInlineAsm(StringRef Asm) {
0346     GlobalScopeAsm = std::string(Asm);
0347     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
0348       GlobalScopeAsm += '\n';
0349   }
0350 
0351   /// Append to the module-scope inline assembly blocks.
0352   /// A trailing newline is added if the input doesn't have one.
0353   void appendModuleInlineAsm(StringRef Asm) {
0354     GlobalScopeAsm += Asm;
0355     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
0356       GlobalScopeAsm += '\n';
0357   }
0358 
0359 /// @}
0360 /// @name Generic Value Accessors
0361 /// @{
0362 
0363   /// Return the global value in the module with the specified name, of
0364   /// arbitrary type. This method returns null if a global with the specified
0365   /// name is not found.
0366   GlobalValue *getNamedValue(StringRef Name) const;
0367 
0368   /// Return the number of global values in the module.
0369   unsigned getNumNamedValues() const;
0370 
0371   /// Return a unique non-zero ID for the specified metadata kind. This ID is
0372   /// uniqued across modules in the current LLVMContext.
0373   unsigned getMDKindID(StringRef Name) const;
0374 
0375   /// Populate client supplied SmallVector with the name for custom metadata IDs
0376   /// registered in this LLVMContext.
0377   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
0378 
0379   /// Populate client supplied SmallVector with the bundle tags registered in
0380   /// this LLVMContext.  The bundle tags are ordered by increasing bundle IDs.
0381   /// \see LLVMContext::getOperandBundleTagID
0382   void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
0383 
0384   std::vector<StructType *> getIdentifiedStructTypes() const;
0385 
0386   /// Return a unique name for an intrinsic whose mangling is based on an
0387   /// unnamed type. The Proto represents the function prototype.
0388   std::string getUniqueIntrinsicName(StringRef BaseName, Intrinsic::ID Id,
0389                                      const FunctionType *Proto);
0390 
0391 /// @}
0392 /// @name Function Accessors
0393 /// @{
0394 
0395   /// Look up the specified function in the module symbol table. If it does not
0396   /// exist, add a prototype for the function and return it. Otherwise, return
0397   /// the existing function.
0398   ///
0399   /// In all cases, the returned value is a FunctionCallee wrapper around the
0400   /// 'FunctionType *T' passed in, as well as the 'Value*' of the Function. The
0401   /// function type of the function may differ from the function type stored in
0402   /// FunctionCallee if it was previously created with a different type.
0403   ///
0404   /// Note: For library calls getOrInsertLibFunc() should be used instead.
0405   FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T,
0406                                      AttributeList AttributeList);
0407 
0408   FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T);
0409 
0410   /// Same as above, but takes a list of function arguments, which makes it
0411   /// easier for clients to use.
0412   template <typename... ArgsTy>
0413   FunctionCallee getOrInsertFunction(StringRef Name,
0414                                      AttributeList AttributeList, Type *RetTy,
0415                                      ArgsTy... Args) {
0416     SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
0417     return getOrInsertFunction(Name,
0418                                FunctionType::get(RetTy, ArgTys, false),
0419                                AttributeList);
0420   }
0421 
0422   /// Same as above, but without the attributes.
0423   template <typename... ArgsTy>
0424   FunctionCallee getOrInsertFunction(StringRef Name, Type *RetTy,
0425                                      ArgsTy... Args) {
0426     return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
0427   }
0428 
0429   // Avoid an incorrect ordering that'd otherwise compile incorrectly.
0430   template <typename... ArgsTy>
0431   FunctionCallee
0432   getOrInsertFunction(StringRef Name, AttributeList AttributeList,
0433                       FunctionType *Invalid, ArgsTy... Args) = delete;
0434 
0435   /// Look up the specified function in the module symbol table. If it does not
0436   /// exist, return null.
0437   Function *getFunction(StringRef Name) const;
0438 
0439 /// @}
0440 /// @name Global Variable Accessors
0441 /// @{
0442 
0443   /// Look up the specified global variable in the module symbol table. If it
0444   /// does not exist, return null. If AllowInternal is set to true, this
0445   /// function will return types that have InternalLinkage. By default, these
0446   /// types are not returned.
0447   GlobalVariable *getGlobalVariable(StringRef Name) const {
0448     return getGlobalVariable(Name, false);
0449   }
0450 
0451   GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
0452 
0453   GlobalVariable *getGlobalVariable(StringRef Name,
0454                                     bool AllowInternal = false) {
0455     return static_cast<const Module *>(this)->getGlobalVariable(Name,
0456                                                                 AllowInternal);
0457   }
0458 
0459   /// Return the global variable in the module with the specified name, of
0460   /// arbitrary type. This method returns null if a global with the specified
0461   /// name is not found.
0462   const GlobalVariable *getNamedGlobal(StringRef Name) const {
0463     return getGlobalVariable(Name, true);
0464   }
0465   GlobalVariable *getNamedGlobal(StringRef Name) {
0466     return const_cast<GlobalVariable *>(
0467                        static_cast<const Module *>(this)->getNamedGlobal(Name));
0468   }
0469 
0470   /// Look up the specified global in the module symbol table.
0471   /// If it does not exist, invoke a callback to create a declaration of the
0472   /// global and return it. The global is constantexpr casted to the expected
0473   /// type if necessary.
0474   Constant *
0475   getOrInsertGlobal(StringRef Name, Type *Ty,
0476                     function_ref<GlobalVariable *()> CreateGlobalCallback);
0477 
0478   /// Look up the specified global in the module symbol table. If required, this
0479   /// overload constructs the global variable using its constructor's defaults.
0480   Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
0481 
0482 /// @}
0483 /// @name Global Alias Accessors
0484 /// @{
0485 
0486   /// Return the global alias in the module with the specified name, of
0487   /// arbitrary type. This method returns null if a global with the specified
0488   /// name is not found.
0489   GlobalAlias *getNamedAlias(StringRef Name) const;
0490 
0491 /// @}
0492 /// @name Global IFunc Accessors
0493 /// @{
0494 
0495   /// Return the global ifunc in the module with the specified name, of
0496   /// arbitrary type. This method returns null if a global with the specified
0497   /// name is not found.
0498   GlobalIFunc *getNamedIFunc(StringRef Name) const;
0499 
0500 /// @}
0501 /// @name Named Metadata Accessors
0502 /// @{
0503 
0504   /// Return the first NamedMDNode in the module with the specified name. This
0505   /// method returns null if a NamedMDNode with the specified name is not found.
0506   NamedMDNode *getNamedMetadata(StringRef Name) const;
0507 
0508   /// Return the named MDNode in the module with the specified name. This method
0509   /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
0510   /// found.
0511   NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
0512 
0513   /// Remove the given NamedMDNode from this module and delete it.
0514   void eraseNamedMetadata(NamedMDNode *NMD);
0515 
0516 /// @}
0517 /// @name Comdat Accessors
0518 /// @{
0519 
0520   /// Return the Comdat in the module with the specified name. It is created
0521   /// if it didn't already exist.
0522   Comdat *getOrInsertComdat(StringRef Name);
0523 
0524 /// @}
0525 /// @name Module Flags Accessors
0526 /// @{
0527 
0528   /// Returns the module flags in the provided vector.
0529   void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
0530 
0531   /// Return the corresponding value if Key appears in module flags, otherwise
0532   /// return null.
0533   Metadata *getModuleFlag(StringRef Key) const;
0534 
0535   /// Returns the NamedMDNode in the module that represents module-level flags.
0536   /// This method returns null if there are no module-level flags.
0537   NamedMDNode *getModuleFlagsMetadata() const { return ModuleFlags; }
0538 
0539   /// Returns the NamedMDNode in the module that represents module-level flags.
0540   /// If module-level flags aren't found, it creates the named metadata that
0541   /// contains them.
0542   NamedMDNode *getOrInsertModuleFlagsMetadata();
0543 
0544   /// Add a module-level flag to the module-level flags metadata. It will create
0545   /// the module-level flags named metadata if it doesn't already exist.
0546   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
0547   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
0548   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
0549   void addModuleFlag(MDNode *Node);
0550   /// Like addModuleFlag but replaces the old module flag if it already exists.
0551   void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
0552   void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
0553   void setModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
0554 
0555   /// @}
0556   /// @name Materialization
0557   /// @{
0558 
0559   /// Sets the GVMaterializer to GVM. This module must not yet have a
0560   /// Materializer. To reset the materializer for a module that already has one,
0561   /// call materializeAll first. Destroying this module will destroy
0562   /// its materializer without materializing any more GlobalValues. Without
0563   /// destroying the Module, there is no way to detach or destroy a materializer
0564   /// without materializing all the GVs it controls, to avoid leaving orphan
0565   /// unmaterialized GVs.
0566   void setMaterializer(GVMaterializer *GVM);
0567   /// Retrieves the GVMaterializer, if any, for this Module.
0568   GVMaterializer *getMaterializer() const { return Materializer.get(); }
0569   bool isMaterialized() const { return !getMaterializer(); }
0570 
0571   /// Make sure the GlobalValue is fully read.
0572   llvm::Error materialize(GlobalValue *GV);
0573 
0574   /// Make sure all GlobalValues in this Module are fully read and clear the
0575   /// Materializer.
0576   llvm::Error materializeAll();
0577 
0578   llvm::Error materializeMetadata();
0579 
0580   /// Detach global variable \p GV from the list but don't delete it.
0581   void removeGlobalVariable(GlobalVariable *GV) { GlobalList.remove(GV); }
0582   /// Remove global variable \p GV from the list and delete it.
0583   void eraseGlobalVariable(GlobalVariable *GV) { GlobalList.erase(GV); }
0584   /// Insert global variable \p GV at the end of the global variable list and
0585   /// take ownership.
0586   void insertGlobalVariable(GlobalVariable *GV) {
0587     insertGlobalVariable(GlobalList.end(), GV);
0588   }
0589   /// Insert global variable \p GV into the global variable list before \p
0590   /// Where and take ownership.
0591   void insertGlobalVariable(GlobalListType::iterator Where, GlobalVariable *GV) {
0592     GlobalList.insert(Where, GV);
0593   }
0594   // Use global_size() to get the total number of global variables.
0595   // Use globals() to get the range of all global variables.
0596 
0597 private:
0598 /// @}
0599 /// @name Direct access to the globals list, functions list, and symbol table
0600 /// @{
0601 
0602   /// Get the Module's list of global variables (constant).
0603   const GlobalListType   &getGlobalList() const       { return GlobalList; }
0604   /// Get the Module's list of global variables.
0605   GlobalListType         &getGlobalList()             { return GlobalList; }
0606 
0607   static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
0608     return &Module::GlobalList;
0609   }
0610   friend class llvm::SymbolTableListTraits<llvm::GlobalVariable>;
0611 
0612 public:
0613   /// Get the Module's list of functions (constant).
0614   const FunctionListType &getFunctionList() const     { return FunctionList; }
0615   /// Get the Module's list of functions.
0616   FunctionListType       &getFunctionList()           { return FunctionList; }
0617   static FunctionListType Module::*getSublistAccess(Function*) {
0618     return &Module::FunctionList;
0619   }
0620 
0621   /// Detach \p Alias from the list but don't delete it.
0622   void removeAlias(GlobalAlias *Alias) { AliasList.remove(Alias); }
0623   /// Remove \p Alias from the list and delete it.
0624   void eraseAlias(GlobalAlias *Alias) { AliasList.erase(Alias); }
0625   /// Insert \p Alias at the end of the alias list and take ownership.
0626   void insertAlias(GlobalAlias *Alias) { AliasList.insert(AliasList.end(), Alias); }
0627   // Use alias_size() to get the size of AliasList.
0628   // Use aliases() to get a range of all Alias objects in AliasList.
0629 
0630   /// Detach \p IFunc from the list but don't delete it.
0631   void removeIFunc(GlobalIFunc *IFunc) { IFuncList.remove(IFunc); }
0632   /// Remove \p IFunc from the list and delete it.
0633   void eraseIFunc(GlobalIFunc *IFunc) { IFuncList.erase(IFunc); }
0634   /// Insert \p IFunc at the end of the alias list and take ownership.
0635   void insertIFunc(GlobalIFunc *IFunc) { IFuncList.push_back(IFunc); }
0636   // Use ifunc_size() to get the number of functions in IFuncList.
0637   // Use ifuncs() to get the range of all IFuncs.
0638 
0639   /// Detach \p MDNode from the list but don't delete it.
0640   void removeNamedMDNode(NamedMDNode *MDNode) { NamedMDList.remove(MDNode); }
0641   /// Remove \p MDNode from the list and delete it.
0642   void eraseNamedMDNode(NamedMDNode *MDNode) { NamedMDList.erase(MDNode); }
0643   /// Insert \p MDNode at the end of the alias list and take ownership.
0644   void insertNamedMDNode(NamedMDNode *MDNode) {
0645     NamedMDList.push_back(MDNode);
0646   }
0647   // Use named_metadata_size() to get the size of the named meatadata list.
0648   // Use named_metadata() to get the range of all named metadata.
0649 
0650 private: // Please use functions like insertAlias(), removeAlias() etc.
0651   /// Get the Module's list of aliases (constant).
0652   const AliasListType    &getAliasList() const        { return AliasList; }
0653   /// Get the Module's list of aliases.
0654   AliasListType          &getAliasList()              { return AliasList; }
0655 
0656   static AliasListType Module::*getSublistAccess(GlobalAlias*) {
0657     return &Module::AliasList;
0658   }
0659   friend class llvm::SymbolTableListTraits<llvm::GlobalAlias>;
0660 
0661   /// Get the Module's list of ifuncs (constant).
0662   const IFuncListType    &getIFuncList() const        { return IFuncList; }
0663   /// Get the Module's list of ifuncs.
0664   IFuncListType          &getIFuncList()              { return IFuncList; }
0665 
0666   static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
0667     return &Module::IFuncList;
0668   }
0669   friend class llvm::SymbolTableListTraits<llvm::GlobalIFunc>;
0670 
0671   /// Get the Module's list of named metadata (constant).
0672   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
0673   /// Get the Module's list of named metadata.
0674   NamedMDListType        &getNamedMDList()            { return NamedMDList; }
0675 
0676   static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
0677     return &Module::NamedMDList;
0678   }
0679 
0680 public:
0681   /// Get the symbol table of global variable and function identifiers
0682   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
0683   /// Get the Module's symbol table of global variable and function identifiers.
0684   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
0685 
0686   /// Get the Module's symbol table for COMDATs (constant).
0687   const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
0688   /// Get the Module's symbol table for COMDATs.
0689   ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
0690 
0691 /// @}
0692 /// @name Global Variable Iteration
0693 /// @{
0694 
0695   global_iterator       global_begin()       { return GlobalList.begin(); }
0696   const_global_iterator global_begin() const { return GlobalList.begin(); }
0697   global_iterator       global_end  ()       { return GlobalList.end(); }
0698   const_global_iterator global_end  () const { return GlobalList.end(); }
0699   size_t                global_size () const { return GlobalList.size(); }
0700   bool                  global_empty() const { return GlobalList.empty(); }
0701 
0702   iterator_range<global_iterator> globals() {
0703     return make_range(global_begin(), global_end());
0704   }
0705   iterator_range<const_global_iterator> globals() const {
0706     return make_range(global_begin(), global_end());
0707   }
0708 
0709 /// @}
0710 /// @name Function Iteration
0711 /// @{
0712 
0713   iterator                begin()       { return FunctionList.begin(); }
0714   const_iterator          begin() const { return FunctionList.begin(); }
0715   iterator                end  ()       { return FunctionList.end();   }
0716   const_iterator          end  () const { return FunctionList.end();   }
0717   reverse_iterator        rbegin()      { return FunctionList.rbegin(); }
0718   const_reverse_iterator  rbegin() const{ return FunctionList.rbegin(); }
0719   reverse_iterator        rend()        { return FunctionList.rend(); }
0720   const_reverse_iterator  rend() const  { return FunctionList.rend(); }
0721   size_t                  size() const  { return FunctionList.size(); }
0722   bool                    empty() const { return FunctionList.empty(); }
0723 
0724   iterator_range<iterator> functions() {
0725     return make_range(begin(), end());
0726   }
0727   iterator_range<const_iterator> functions() const {
0728     return make_range(begin(), end());
0729   }
0730 
0731 /// @}
0732 /// @name Alias Iteration
0733 /// @{
0734 
0735   alias_iterator       alias_begin()            { return AliasList.begin(); }
0736   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
0737   alias_iterator       alias_end  ()            { return AliasList.end();   }
0738   const_alias_iterator alias_end  () const      { return AliasList.end();   }
0739   size_t               alias_size () const      { return AliasList.size();  }
0740   bool                 alias_empty() const      { return AliasList.empty(); }
0741 
0742   iterator_range<alias_iterator> aliases() {
0743     return make_range(alias_begin(), alias_end());
0744   }
0745   iterator_range<const_alias_iterator> aliases() const {
0746     return make_range(alias_begin(), alias_end());
0747   }
0748 
0749 /// @}
0750 /// @name IFunc Iteration
0751 /// @{
0752 
0753   ifunc_iterator       ifunc_begin()            { return IFuncList.begin(); }
0754   const_ifunc_iterator ifunc_begin() const      { return IFuncList.begin(); }
0755   ifunc_iterator       ifunc_end  ()            { return IFuncList.end();   }
0756   const_ifunc_iterator ifunc_end  () const      { return IFuncList.end();   }
0757   size_t               ifunc_size () const      { return IFuncList.size();  }
0758   bool                 ifunc_empty() const      { return IFuncList.empty(); }
0759 
0760   iterator_range<ifunc_iterator> ifuncs() {
0761     return make_range(ifunc_begin(), ifunc_end());
0762   }
0763   iterator_range<const_ifunc_iterator> ifuncs() const {
0764     return make_range(ifunc_begin(), ifunc_end());
0765   }
0766 
0767   /// @}
0768   /// @name Convenience iterators
0769   /// @{
0770 
0771   using global_object_iterator =
0772       concat_iterator<GlobalObject, iterator, global_iterator>;
0773   using const_global_object_iterator =
0774       concat_iterator<const GlobalObject, const_iterator,
0775                       const_global_iterator>;
0776 
0777   iterator_range<global_object_iterator> global_objects();
0778   iterator_range<const_global_object_iterator> global_objects() const;
0779 
0780   using global_value_iterator =
0781       concat_iterator<GlobalValue, iterator, global_iterator, alias_iterator,
0782                       ifunc_iterator>;
0783   using const_global_value_iterator =
0784       concat_iterator<const GlobalValue, const_iterator, const_global_iterator,
0785                       const_alias_iterator, const_ifunc_iterator>;
0786 
0787   iterator_range<global_value_iterator> global_values();
0788   iterator_range<const_global_value_iterator> global_values() const;
0789 
0790   /// @}
0791   /// @name Named Metadata Iteration
0792   /// @{
0793 
0794   named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
0795   const_named_metadata_iterator named_metadata_begin() const {
0796     return NamedMDList.begin();
0797   }
0798 
0799   named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
0800   const_named_metadata_iterator named_metadata_end() const {
0801     return NamedMDList.end();
0802   }
0803 
0804   size_t named_metadata_size() const { return NamedMDList.size();  }
0805   bool named_metadata_empty() const { return NamedMDList.empty(); }
0806 
0807   iterator_range<named_metadata_iterator> named_metadata() {
0808     return make_range(named_metadata_begin(), named_metadata_end());
0809   }
0810   iterator_range<const_named_metadata_iterator> named_metadata() const {
0811     return make_range(named_metadata_begin(), named_metadata_end());
0812   }
0813 
0814   /// An iterator for DICompileUnits that skips those marked NoDebug.
0815   class debug_compile_units_iterator {
0816     NamedMDNode *CUs;
0817     unsigned Idx;
0818 
0819     void SkipNoDebugCUs();
0820 
0821   public:
0822     using iterator_category = std::input_iterator_tag;
0823     using value_type = DICompileUnit *;
0824     using difference_type = std::ptrdiff_t;
0825     using pointer = value_type *;
0826     using reference = value_type &;
0827 
0828     explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
0829         : CUs(CUs), Idx(Idx) {
0830       SkipNoDebugCUs();
0831     }
0832 
0833     debug_compile_units_iterator &operator++() {
0834       ++Idx;
0835       SkipNoDebugCUs();
0836       return *this;
0837     }
0838 
0839     debug_compile_units_iterator operator++(int) {
0840       debug_compile_units_iterator T(*this);
0841       ++Idx;
0842       return T;
0843     }
0844 
0845     bool operator==(const debug_compile_units_iterator &I) const {
0846       return Idx == I.Idx;
0847     }
0848 
0849     bool operator!=(const debug_compile_units_iterator &I) const {
0850       return Idx != I.Idx;
0851     }
0852 
0853     DICompileUnit *operator*() const;
0854     DICompileUnit *operator->() const;
0855   };
0856 
0857   debug_compile_units_iterator debug_compile_units_begin() const {
0858     auto *CUs = getNamedMetadata("llvm.dbg.cu");
0859     return debug_compile_units_iterator(CUs, 0);
0860   }
0861 
0862   debug_compile_units_iterator debug_compile_units_end() const {
0863     auto *CUs = getNamedMetadata("llvm.dbg.cu");
0864     return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
0865   }
0866 
0867   /// Return an iterator for all DICompileUnits listed in this Module's
0868   /// llvm.dbg.cu named metadata node and aren't explicitly marked as
0869   /// NoDebug.
0870   iterator_range<debug_compile_units_iterator> debug_compile_units() const {
0871     auto *CUs = getNamedMetadata("llvm.dbg.cu");
0872     return make_range(
0873         debug_compile_units_iterator(CUs, 0),
0874         debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
0875   }
0876 /// @}
0877 
0878   /// Destroy ConstantArrays in LLVMContext if they are not used.
0879   /// ConstantArrays constructed during linking can cause quadratic memory
0880   /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
0881   /// slowdown for a large application.
0882   ///
0883   /// NOTE: Constants are currently owned by LLVMContext. This can then only
0884   /// be called where all uses of the LLVMContext are understood.
0885   void dropTriviallyDeadConstantArrays();
0886 
0887 /// @name Utility functions for printing and dumping Module objects
0888 /// @{
0889 
0890   /// Print the module to an output stream with an optional
0891   /// AssemblyAnnotationWriter.  If \c ShouldPreserveUseListOrder, then include
0892   /// uselistorder directives so that use-lists can be recreated when reading
0893   /// the assembly.
0894   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
0895              bool ShouldPreserveUseListOrder = false,
0896              bool IsForDebug = false) const;
0897 
0898   /// Dump the module to stderr (for debugging).
0899   void dump() const;
0900 
0901   /// This function causes all the subinstructions to "let go" of all references
0902   /// that they are maintaining.  This allows one to 'delete' a whole class at
0903   /// a time, even though there may be circular references... first all
0904   /// references are dropped, and all use counts go to zero.  Then everything
0905   /// is delete'd for real.  Note that no operations are valid on an object
0906   /// that has "dropped all references", except operator delete.
0907   void dropAllReferences();
0908 
0909 /// @}
0910 /// @name Utility functions for querying Debug information.
0911 /// @{
0912 
0913   /// Returns the Number of Register ParametersDwarf Version by checking
0914   /// module flags.
0915   unsigned getNumberRegisterParameters() const;
0916 
0917   /// Returns the Dwarf Version by checking module flags.
0918   unsigned getDwarfVersion() const;
0919 
0920   /// Returns the DWARF format by checking module flags.
0921   bool isDwarf64() const;
0922 
0923   /// Returns the CodeView Version by checking module flags.
0924   /// Returns zero if not present in module.
0925   unsigned getCodeViewFlag() const;
0926 
0927 /// @}
0928 /// @name Utility functions for querying and setting PIC level
0929 /// @{
0930 
0931   /// Returns the PIC level (small or large model)
0932   PICLevel::Level getPICLevel() const;
0933 
0934   /// Set the PIC level (small or large model)
0935   void setPICLevel(PICLevel::Level PL);
0936 /// @}
0937 
0938 /// @}
0939 /// @name Utility functions for querying and setting PIE level
0940 /// @{
0941 
0942   /// Returns the PIE level (small or large model)
0943   PIELevel::Level getPIELevel() const;
0944 
0945   /// Set the PIE level (small or large model)
0946   void setPIELevel(PIELevel::Level PL);
0947 /// @}
0948 
0949   /// @}
0950   /// @name Utility function for querying and setting code model
0951   /// @{
0952 
0953   /// Returns the code model (tiny, small, kernel, medium or large model)
0954   std::optional<CodeModel::Model> getCodeModel() const;
0955 
0956   /// Set the code model (tiny, small, kernel, medium or large)
0957   void setCodeModel(CodeModel::Model CL);
0958   /// @}
0959 
0960   /// @}
0961   /// @name Utility function for querying and setting the large data threshold
0962   /// @{
0963 
0964   /// Returns the code model (tiny, small, kernel, medium or large model)
0965   std::optional<uint64_t> getLargeDataThreshold() const;
0966 
0967   /// Set the code model (tiny, small, kernel, medium or large)
0968   void setLargeDataThreshold(uint64_t Threshold);
0969   /// @}
0970 
0971   /// @name Utility functions for querying and setting PGO summary
0972   /// @{
0973 
0974   /// Attach profile summary metadata to this module.
0975   void setProfileSummary(Metadata *M, ProfileSummary::Kind Kind);
0976 
0977   /// Returns profile summary metadata. When IsCS is true, use the context
0978   /// sensitive profile summary.
0979   Metadata *getProfileSummary(bool IsCS) const;
0980   /// @}
0981 
0982   /// Returns whether semantic interposition is to be respected.
0983   bool getSemanticInterposition() const;
0984 
0985   /// Set whether semantic interposition is to be respected.
0986   void setSemanticInterposition(bool);
0987 
0988   /// Returns true if PLT should be avoided for RTLib calls.
0989   bool getRtLibUseGOT() const;
0990 
0991   /// Set that PLT should be avoid for RTLib calls.
0992   void setRtLibUseGOT();
0993 
0994   /// Get/set whether referencing global variables can use direct access
0995   /// relocations on ELF targets.
0996   bool getDirectAccessExternalData() const;
0997   void setDirectAccessExternalData(bool Value);
0998 
0999   /// Get/set whether synthesized functions should get the uwtable attribute.
1000   UWTableKind getUwtable() const;
1001   void setUwtable(UWTableKind Kind);
1002 
1003   /// Get/set whether synthesized functions should get the "frame-pointer"
1004   /// attribute.
1005   FramePointerKind getFramePointer() const;
1006   void setFramePointer(FramePointerKind Kind);
1007 
1008   /// Get/set what kind of stack protector guard to use.
1009   StringRef getStackProtectorGuard() const;
1010   void setStackProtectorGuard(StringRef Kind);
1011 
1012   /// Get/set which register to use as the stack protector guard register. The
1013   /// empty string is equivalent to "global". Other values may be "tls" or
1014   /// "sysreg".
1015   StringRef getStackProtectorGuardReg() const;
1016   void setStackProtectorGuardReg(StringRef Reg);
1017 
1018   /// Get/set a symbol to use as the stack protector guard.
1019   StringRef getStackProtectorGuardSymbol() const;
1020   void setStackProtectorGuardSymbol(StringRef Symbol);
1021 
1022   /// Get/set what offset from the stack protector to use.
1023   int getStackProtectorGuardOffset() const;
1024   void setStackProtectorGuardOffset(int Offset);
1025 
1026   /// Get/set the stack alignment overridden from the default.
1027   unsigned getOverrideStackAlignment() const;
1028   void setOverrideStackAlignment(unsigned Align);
1029 
1030   unsigned getMaxTLSAlignment() const;
1031 
1032   /// @name Utility functions for querying and setting the build SDK version
1033   /// @{
1034 
1035   /// Attach a build SDK version metadata to this module.
1036   void setSDKVersion(const VersionTuple &V);
1037 
1038   /// Get the build SDK version metadata.
1039   ///
1040   /// An empty version is returned if no such metadata is attached.
1041   VersionTuple getSDKVersion() const;
1042   /// @}
1043 
1044   /// Take ownership of the given memory buffer.
1045   void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
1046 
1047   /// Set the partial sample profile ratio in the profile summary module flag,
1048   /// if applicable.
1049   void setPartialSampleProfileRatio(const ModuleSummaryIndex &Index);
1050 
1051   /// Get the target variant triple which is a string describing a variant of
1052   /// the target host platform. For example, Mac Catalyst can be a variant
1053   /// target triple for a macOS target.
1054   /// @returns a string containing the target variant triple.
1055   StringRef getDarwinTargetVariantTriple() const;
1056 
1057   /// Set the target variant triple which is a string describing a variant of
1058   /// the target host platform.
1059   void setDarwinTargetVariantTriple(StringRef T);
1060 
1061   /// Get the target variant version build SDK version metadata.
1062   ///
1063   /// An empty version is returned if no such metadata is attached.
1064   VersionTuple getDarwinTargetVariantSDKVersion() const;
1065 
1066   /// Set the target variant version build SDK version metadata.
1067   void setDarwinTargetVariantSDKVersion(VersionTuple Version);
1068 };
1069 
1070 /// Given "llvm.used" or "llvm.compiler.used" as a global name, collect the
1071 /// initializer elements of that global in a SmallVector and return the global
1072 /// itself.
1073 GlobalVariable *collectUsedGlobalVariables(const Module &M,
1074                                            SmallVectorImpl<GlobalValue *> &Vec,
1075                                            bool CompilerUsed);
1076 
1077 /// An raw_ostream inserter for modules.
1078 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
1079   M.print(O, nullptr);
1080   return O;
1081 }
1082 
1083 // Create wrappers for C Binding types (see CBindingWrapping.h).
1084 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
1085 
1086 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
1087  * Module.
1088  */
1089 inline Module *unwrap(LLVMModuleProviderRef MP) {
1090   return reinterpret_cast<Module*>(MP);
1091 }
1092 
1093 } // end namespace llvm
1094 
1095 #endif // LLVM_IR_MODULE_H