Home | History | Annotate | Download | only in IR
      1 //===-- llvm/Module.h - C++ class to represent a VM module ------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 /// @file
     11 /// Module.h This file contains the declarations for the Module class.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_IR_MODULE_H
     16 #define LLVM_IR_MODULE_H
     17 
     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 
     30 namespace llvm {
     31 template <typename T> class Optional;
     32 class Error;
     33 class FunctionType;
     34 class GVMaterializer;
     35 class LLVMContext;
     36 class MemoryBuffer;
     37 class RandomNumberGenerator;
     38 class StructType;
     39 template <class PtrType> class SmallPtrSetImpl;
     40 
     41 /// A Module instance is used to store all the information related to an
     42 /// LLVM module. Modules are the top level container of all other LLVM
     43 /// Intermediate Representation (IR) objects. Each module directly contains a
     44 /// list of globals variables, a list of functions, a list of libraries (or
     45 /// other modules) this module depends on, a symbol table, and various data
     46 /// about the target's characteristics.
     47 ///
     48 /// A module maintains a GlobalValRefMap object that is used to hold all
     49 /// constant references to global variables in the module.  When a global
     50 /// variable is destroyed, it should have no entries in the GlobalValueRefMap.
     51 /// @brief The main container class for the LLVM Intermediate Representation.
     52 class Module {
     53 /// @name Types And Enumerations
     54 /// @{
     55 public:
     56   /// The type for the list of global variables.
     57   typedef SymbolTableList<GlobalVariable> GlobalListType;
     58   /// The type for the list of functions.
     59   typedef SymbolTableList<Function> FunctionListType;
     60   /// The type for the list of aliases.
     61   typedef SymbolTableList<GlobalAlias> AliasListType;
     62   /// The type for the list of ifuncs.
     63   typedef SymbolTableList<GlobalIFunc> IFuncListType;
     64   /// The type for the list of named metadata.
     65   typedef ilist<NamedMDNode> NamedMDListType;
     66   /// The type of the comdat "symbol" table.
     67   typedef StringMap<Comdat> ComdatSymTabType;
     68 
     69   /// The Global Variable iterator.
     70   typedef GlobalListType::iterator                      global_iterator;
     71   /// The Global Variable constant iterator.
     72   typedef GlobalListType::const_iterator          const_global_iterator;
     73 
     74   /// The Function iterators.
     75   typedef FunctionListType::iterator                           iterator;
     76   /// The Function constant iterator
     77   typedef FunctionListType::const_iterator               const_iterator;
     78 
     79   /// The Function reverse iterator.
     80   typedef FunctionListType::reverse_iterator             reverse_iterator;
     81   /// The Function constant reverse iterator.
     82   typedef FunctionListType::const_reverse_iterator const_reverse_iterator;
     83 
     84   /// The Global Alias iterators.
     85   typedef AliasListType::iterator                        alias_iterator;
     86   /// The Global Alias constant iterator
     87   typedef AliasListType::const_iterator            const_alias_iterator;
     88 
     89   /// The Global IFunc iterators.
     90   typedef IFuncListType::iterator                        ifunc_iterator;
     91   /// The Global IFunc constant iterator
     92   typedef IFuncListType::const_iterator            const_ifunc_iterator;
     93 
     94   /// The named metadata iterators.
     95   typedef NamedMDListType::iterator             named_metadata_iterator;
     96   /// The named metadata constant iterators.
     97   typedef NamedMDListType::const_iterator const_named_metadata_iterator;
     98 
     99   /// This enumeration defines the supported behaviors of module flags.
    100   enum ModFlagBehavior {
    101     /// Emits an error if two values disagree, otherwise the resulting value is
    102     /// that of the operands.
    103     Error = 1,
    104 
    105     /// Emits a warning if two values disagree. The result value will be the
    106     /// operand for the flag from the first module being linked.
    107     Warning = 2,
    108 
    109     /// Adds a requirement that another module flag be present and have a
    110     /// specified value after linking is performed. The value must be a metadata
    111     /// pair, where the first element of the pair is the ID of the module flag
    112     /// to be restricted, and the second element of the pair is the value the
    113     /// module flag should be restricted to. This behavior can be used to
    114     /// restrict the allowable results (via triggering of an error) of linking
    115     /// IDs with the **Override** behavior.
    116     Require = 3,
    117 
    118     /// Uses the specified value, regardless of the behavior or value of the
    119     /// other module. If both modules specify **Override**, but the values
    120     /// differ, an error will be emitted.
    121     Override = 4,
    122 
    123     /// Appends the two values, which are required to be metadata nodes.
    124     Append = 5,
    125 
    126     /// Appends the two values, which are required to be metadata
    127     /// nodes. However, duplicate entries in the second list are dropped
    128     /// during the append operation.
    129     AppendUnique = 6,
    130 
    131     // Markers:
    132     ModFlagBehaviorFirstVal = Error,
    133     ModFlagBehaviorLastVal = AppendUnique
    134   };
    135 
    136   /// Checks if Metadata represents a valid ModFlagBehavior, and stores the
    137   /// converted result in MFB.
    138   static bool isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB);
    139 
    140   struct ModuleFlagEntry {
    141     ModFlagBehavior Behavior;
    142     MDString *Key;
    143     Metadata *Val;
    144     ModuleFlagEntry(ModFlagBehavior B, MDString *K, Metadata *V)
    145         : Behavior(B), Key(K), Val(V) {}
    146   };
    147 
    148 /// @}
    149 /// @name Member Variables
    150 /// @{
    151 private:
    152   LLVMContext &Context;           ///< The LLVMContext from which types and
    153                                   ///< constants are allocated.
    154   GlobalListType GlobalList;      ///< The Global Variables in the module
    155   FunctionListType FunctionList;  ///< The Functions in the module
    156   AliasListType AliasList;        ///< The Aliases in the module
    157   IFuncListType IFuncList;        ///< The IFuncs in the module
    158   NamedMDListType NamedMDList;    ///< The named metadata in the module
    159   std::string GlobalScopeAsm;     ///< Inline Asm at global scope.
    160   ValueSymbolTable *ValSymTab;    ///< Symbol table for values
    161   ComdatSymTabType ComdatSymTab;  ///< Symbol table for COMDATs
    162   std::unique_ptr<MemoryBuffer>
    163   OwnedMemoryBuffer;              ///< Memory buffer directly owned by this
    164                                   ///< module, for legacy clients only.
    165   std::unique_ptr<GVMaterializer>
    166   Materializer;                   ///< Used to materialize GlobalValues
    167   std::string ModuleID;           ///< Human readable identifier for the module
    168   std::string SourceFileName;     ///< Original source file name for module,
    169                                   ///< recorded in bitcode.
    170   std::string TargetTriple;       ///< Platform target triple Module compiled on
    171                                   ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
    172   void *NamedMDSymTab;            ///< NamedMDNode names.
    173   DataLayout DL;                  ///< DataLayout associated with the module
    174 
    175   friend class Constant;
    176 
    177 /// @}
    178 /// @name Constructors
    179 /// @{
    180 public:
    181   /// The Module constructor. Note that there is no default constructor. You
    182   /// must provide a name for the module upon construction.
    183   explicit Module(StringRef ModuleID, LLVMContext& C);
    184   /// The module destructor. This will dropAllReferences.
    185   ~Module();
    186 
    187 /// @}
    188 /// @name Module Level Accessors
    189 /// @{
    190 
    191   /// Get the module identifier which is, essentially, the name of the module.
    192   /// @returns the module identifier as a string
    193   const std::string &getModuleIdentifier() const { return ModuleID; }
    194 
    195   /// Get the module's original source file name. When compiling from
    196   /// bitcode, this is taken from a bitcode record where it was recorded.
    197   /// For other compiles it is the same as the ModuleID, which would
    198   /// contain the source file name.
    199   const std::string &getSourceFileName() const { return SourceFileName; }
    200 
    201   /// \brief Get a short "name" for the module.
    202   ///
    203   /// This is useful for debugging or logging. It is essentially a convenience
    204   /// wrapper around getModuleIdentifier().
    205   StringRef getName() const { return ModuleID; }
    206 
    207   /// Get the data layout string for the module's target platform. This is
    208   /// equivalent to getDataLayout()->getStringRepresentation().
    209   const std::string &getDataLayoutStr() const {
    210     return DL.getStringRepresentation();
    211   }
    212 
    213   /// Get the data layout for the module's target platform.
    214   const DataLayout &getDataLayout() const;
    215 
    216   /// Get the target triple which is a string describing the target host.
    217   /// @returns a string containing the target triple.
    218   const std::string &getTargetTriple() const { return TargetTriple; }
    219 
    220   /// Get the global data context.
    221   /// @returns LLVMContext - a container for LLVM's global information
    222   LLVMContext &getContext() const { return Context; }
    223 
    224   /// Get any module-scope inline assembly blocks.
    225   /// @returns a string containing the module-scope inline assembly blocks.
    226   const std::string &getModuleInlineAsm() const { return GlobalScopeAsm; }
    227 
    228   /// Get a RandomNumberGenerator salted for use with this module. The
    229   /// RNG can be seeded via -rng-seed=<uint64> and is salted with the
    230   /// ModuleID and the provided pass salt. The returned RNG should not
    231   /// be shared across threads or passes.
    232   ///
    233   /// A unique RNG per pass ensures a reproducible random stream even
    234   /// when other randomness consuming passes are added or removed. In
    235   /// addition, the random stream will be reproducible across LLVM
    236   /// versions when the pass does not change.
    237   RandomNumberGenerator *createRNG(const Pass* P) const;
    238 
    239 /// @}
    240 /// @name Module Level Mutators
    241 /// @{
    242 
    243   /// Set the module identifier.
    244   void setModuleIdentifier(StringRef ID) { ModuleID = ID; }
    245 
    246   /// Set the module's original source file name.
    247   void setSourceFileName(StringRef Name) { SourceFileName = Name; }
    248 
    249   /// Set the data layout
    250   void setDataLayout(StringRef Desc);
    251   void setDataLayout(const DataLayout &Other);
    252 
    253   /// Set the target triple.
    254   void setTargetTriple(StringRef T) { TargetTriple = T; }
    255 
    256   /// Set the module-scope inline assembly blocks.
    257   /// A trailing newline is added if the input doesn't have one.
    258   void setModuleInlineAsm(StringRef Asm) {
    259     GlobalScopeAsm = Asm;
    260     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
    261       GlobalScopeAsm += '\n';
    262   }
    263 
    264   /// Append to the module-scope inline assembly blocks.
    265   /// A trailing newline is added if the input doesn't have one.
    266   void appendModuleInlineAsm(StringRef Asm) {
    267     GlobalScopeAsm += Asm;
    268     if (!GlobalScopeAsm.empty() && GlobalScopeAsm.back() != '\n')
    269       GlobalScopeAsm += '\n';
    270   }
    271 
    272 /// @}
    273 /// @name Generic Value Accessors
    274 /// @{
    275 
    276   /// Return the global value in the module with the specified name, of
    277   /// arbitrary type. This method returns null if a global with the specified
    278   /// name is not found.
    279   GlobalValue *getNamedValue(StringRef Name) const;
    280 
    281   /// Return a unique non-zero ID for the specified metadata kind. This ID is
    282   /// uniqued across modules in the current LLVMContext.
    283   unsigned getMDKindID(StringRef Name) const;
    284 
    285   /// Populate client supplied SmallVector with the name for custom metadata IDs
    286   /// registered in this LLVMContext.
    287   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
    288 
    289   /// Populate client supplied SmallVector with the bundle tags registered in
    290   /// this LLVMContext.  The bundle tags are ordered by increasing bundle IDs.
    291   /// \see LLVMContext::getOperandBundleTagID
    292   void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
    293 
    294   /// Return the type with the specified name, or null if there is none by that
    295   /// name.
    296   StructType *getTypeByName(StringRef Name) const;
    297 
    298   std::vector<StructType *> getIdentifiedStructTypes() const;
    299 
    300 /// @}
    301 /// @name Function Accessors
    302 /// @{
    303 
    304   /// Look up the specified function in the module symbol table. Four
    305   /// possibilities:
    306   ///   1. If it does not exist, add a prototype for the function and return it.
    307   ///   2. If it exists, and has a local linkage, the existing function is
    308   ///      renamed and a new one is inserted.
    309   ///   3. Otherwise, if the existing function has the correct prototype, return
    310   ///      the existing function.
    311   ///   4. Finally, the function exists but has the wrong prototype: return the
    312   ///      function with a constantexpr cast to the right prototype.
    313   Constant *getOrInsertFunction(StringRef Name, FunctionType *T,
    314                                 AttributeList AttributeList);
    315 
    316   Constant *getOrInsertFunction(StringRef Name, FunctionType *T);
    317 
    318   /// Look up the specified function in the module symbol table. If it does not
    319   /// exist, add a prototype for the function and return it. This function
    320   /// guarantees to return a constant of pointer to the specified function type
    321   /// or a ConstantExpr BitCast of that type if the named function has a
    322   /// different type. This version of the method takes a null terminated list of
    323   /// function arguments, which makes it easier for clients to use.
    324   template<typename... ArgsTy>
    325   Constant *getOrInsertFunction(StringRef Name,
    326                                 AttributeList AttributeList,
    327                                 Type *RetTy, ArgsTy... Args)
    328   {
    329     SmallVector<Type*, sizeof...(ArgsTy)> ArgTys{Args...};
    330     return getOrInsertFunction(Name,
    331                                FunctionType::get(RetTy, ArgTys, false),
    332                                AttributeList);
    333   }
    334 
    335   /// Same as above, but without the attributes.
    336   template<typename... ArgsTy>
    337   Constant *getOrInsertFunction(StringRef Name, Type *RetTy, ArgsTy... Args) {
    338     return getOrInsertFunction(Name, AttributeList{}, RetTy, Args...);
    339   }
    340 
    341   /// Look up the specified function in the module symbol table. If it does not
    342   /// exist, return null.
    343   Function *getFunction(StringRef Name) const;
    344 
    345 /// @}
    346 /// @name Global Variable Accessors
    347 /// @{
    348 
    349   /// Look up the specified global variable in the module symbol table. If it
    350   /// does not exist, return null. If AllowInternal is set to true, this
    351   /// function will return types that have InternalLinkage. By default, these
    352   /// types are not returned.
    353   GlobalVariable *getGlobalVariable(StringRef Name) const {
    354     return getGlobalVariable(Name, false);
    355   }
    356 
    357   GlobalVariable *getGlobalVariable(StringRef Name, bool AllowInternal) const;
    358 
    359   GlobalVariable *getGlobalVariable(StringRef Name,
    360                                     bool AllowInternal = false) {
    361     return static_cast<const Module *>(this)->getGlobalVariable(Name,
    362                                                                 AllowInternal);
    363   }
    364 
    365   /// Return the global variable in the module with the specified name, of
    366   /// arbitrary type. This method returns null if a global with the specified
    367   /// name is not found.
    368   const GlobalVariable *getNamedGlobal(StringRef Name) const {
    369     return getGlobalVariable(Name, true);
    370   }
    371   GlobalVariable *getNamedGlobal(StringRef Name) {
    372     return const_cast<GlobalVariable *>(
    373                        static_cast<const Module *>(this)->getNamedGlobal(Name));
    374   }
    375 
    376   /// Look up the specified global in the module symbol table.
    377   ///   1. If it does not exist, add a declaration of the global and return it.
    378   ///   2. Else, the global exists but has the wrong type: return the function
    379   ///      with a constantexpr cast to the right type.
    380   ///   3. Finally, if the existing global is the correct declaration, return
    381   ///      the existing global.
    382   Constant *getOrInsertGlobal(StringRef Name, Type *Ty);
    383 
    384 /// @}
    385 /// @name Global Alias Accessors
    386 /// @{
    387 
    388   /// Return the global alias in the module with the specified name, of
    389   /// arbitrary type. This method returns null if a global with the specified
    390   /// name is not found.
    391   GlobalAlias *getNamedAlias(StringRef Name) const;
    392 
    393 /// @}
    394 /// @name Global IFunc Accessors
    395 /// @{
    396 
    397   /// Return the global ifunc in the module with the specified name, of
    398   /// arbitrary type. This method returns null if a global with the specified
    399   /// name is not found.
    400   GlobalIFunc *getNamedIFunc(StringRef Name) const;
    401 
    402 /// @}
    403 /// @name Named Metadata Accessors
    404 /// @{
    405 
    406   /// Return the first NamedMDNode in the module with the specified name. This
    407   /// method returns null if a NamedMDNode with the specified name is not found.
    408   NamedMDNode *getNamedMetadata(const Twine &Name) const;
    409 
    410   /// Return the named MDNode in the module with the specified name. This method
    411   /// returns a new NamedMDNode if a NamedMDNode with the specified name is not
    412   /// found.
    413   NamedMDNode *getOrInsertNamedMetadata(StringRef Name);
    414 
    415   /// Remove the given NamedMDNode from this module and delete it.
    416   void eraseNamedMetadata(NamedMDNode *NMD);
    417 
    418 /// @}
    419 /// @name Comdat Accessors
    420 /// @{
    421 
    422   /// Return the Comdat in the module with the specified name. It is created
    423   /// if it didn't already exist.
    424   Comdat *getOrInsertComdat(StringRef Name);
    425 
    426 /// @}
    427 /// @name Module Flags Accessors
    428 /// @{
    429 
    430   /// Returns the module flags in the provided vector.
    431   void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const;
    432 
    433   /// Return the corresponding value if Key appears in module flags, otherwise
    434   /// return null.
    435   Metadata *getModuleFlag(StringRef Key) const;
    436 
    437   /// Returns the NamedMDNode in the module that represents module-level flags.
    438   /// This method returns null if there are no module-level flags.
    439   NamedMDNode *getModuleFlagsMetadata() const;
    440 
    441   /// Returns the NamedMDNode in the module that represents module-level flags.
    442   /// If module-level flags aren't found, it creates the named metadata that
    443   /// contains them.
    444   NamedMDNode *getOrInsertModuleFlagsMetadata();
    445 
    446   /// Add a module-level flag to the module-level flags metadata. It will create
    447   /// the module-level flags named metadata if it doesn't already exist.
    448   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Metadata *Val);
    449   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Constant *Val);
    450   void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val);
    451   void addModuleFlag(MDNode *Node);
    452 
    453 /// @}
    454 /// @name Materialization
    455 /// @{
    456 
    457   /// Sets the GVMaterializer to GVM. This module must not yet have a
    458   /// Materializer. To reset the materializer for a module that already has one,
    459   /// call materializeAll first. Destroying this module will destroy
    460   /// its materializer without materializing any more GlobalValues. Without
    461   /// destroying the Module, there is no way to detach or destroy a materializer
    462   /// without materializing all the GVs it controls, to avoid leaving orphan
    463   /// unmaterialized GVs.
    464   void setMaterializer(GVMaterializer *GVM);
    465   /// Retrieves the GVMaterializer, if any, for this Module.
    466   GVMaterializer *getMaterializer() const { return Materializer.get(); }
    467   bool isMaterialized() const { return !getMaterializer(); }
    468 
    469   /// Make sure the GlobalValue is fully read.
    470   llvm::Error materialize(GlobalValue *GV);
    471 
    472   /// Make sure all GlobalValues in this Module are fully read and clear the
    473   /// Materializer.
    474   llvm::Error materializeAll();
    475 
    476   llvm::Error materializeMetadata();
    477 
    478 /// @}
    479 /// @name Direct access to the globals list, functions list, and symbol table
    480 /// @{
    481 
    482   /// Get the Module's list of global variables (constant).
    483   const GlobalListType   &getGlobalList() const       { return GlobalList; }
    484   /// Get the Module's list of global variables.
    485   GlobalListType         &getGlobalList()             { return GlobalList; }
    486   static GlobalListType Module::*getSublistAccess(GlobalVariable*) {
    487     return &Module::GlobalList;
    488   }
    489   /// Get the Module's list of functions (constant).
    490   const FunctionListType &getFunctionList() const     { return FunctionList; }
    491   /// Get the Module's list of functions.
    492   FunctionListType       &getFunctionList()           { return FunctionList; }
    493   static FunctionListType Module::*getSublistAccess(Function*) {
    494     return &Module::FunctionList;
    495   }
    496   /// Get the Module's list of aliases (constant).
    497   const AliasListType    &getAliasList() const        { return AliasList; }
    498   /// Get the Module's list of aliases.
    499   AliasListType          &getAliasList()              { return AliasList; }
    500   static AliasListType Module::*getSublistAccess(GlobalAlias*) {
    501     return &Module::AliasList;
    502   }
    503   /// Get the Module's list of ifuncs (constant).
    504   const IFuncListType    &getIFuncList() const        { return IFuncList; }
    505   /// Get the Module's list of ifuncs.
    506   IFuncListType          &getIFuncList()              { return IFuncList; }
    507   static IFuncListType Module::*getSublistAccess(GlobalIFunc*) {
    508     return &Module::IFuncList;
    509   }
    510   /// Get the Module's list of named metadata (constant).
    511   const NamedMDListType  &getNamedMDList() const      { return NamedMDList; }
    512   /// Get the Module's list of named metadata.
    513   NamedMDListType        &getNamedMDList()            { return NamedMDList; }
    514   static NamedMDListType Module::*getSublistAccess(NamedMDNode*) {
    515     return &Module::NamedMDList;
    516   }
    517   /// Get the symbol table of global variable and function identifiers
    518   const ValueSymbolTable &getValueSymbolTable() const { return *ValSymTab; }
    519   /// Get the Module's symbol table of global variable and function identifiers.
    520   ValueSymbolTable       &getValueSymbolTable()       { return *ValSymTab; }
    521   /// Get the Module's symbol table for COMDATs (constant).
    522   const ComdatSymTabType &getComdatSymbolTable() const { return ComdatSymTab; }
    523   /// Get the Module's symbol table for COMDATs.
    524   ComdatSymTabType &getComdatSymbolTable() { return ComdatSymTab; }
    525 
    526 /// @}
    527 /// @name Global Variable Iteration
    528 /// @{
    529 
    530   global_iterator       global_begin()       { return GlobalList.begin(); }
    531   const_global_iterator global_begin() const { return GlobalList.begin(); }
    532   global_iterator       global_end  ()       { return GlobalList.end(); }
    533   const_global_iterator global_end  () const { return GlobalList.end(); }
    534   bool                  global_empty() const { return GlobalList.empty(); }
    535 
    536   iterator_range<global_iterator> globals() {
    537     return make_range(global_begin(), global_end());
    538   }
    539   iterator_range<const_global_iterator> globals() const {
    540     return make_range(global_begin(), global_end());
    541   }
    542 
    543 /// @}
    544 /// @name Function Iteration
    545 /// @{
    546 
    547   iterator                begin()       { return FunctionList.begin(); }
    548   const_iterator          begin() const { return FunctionList.begin(); }
    549   iterator                end  ()       { return FunctionList.end();   }
    550   const_iterator          end  () const { return FunctionList.end();   }
    551   reverse_iterator        rbegin()      { return FunctionList.rbegin(); }
    552   const_reverse_iterator  rbegin() const{ return FunctionList.rbegin(); }
    553   reverse_iterator        rend()        { return FunctionList.rend(); }
    554   const_reverse_iterator  rend() const  { return FunctionList.rend(); }
    555   size_t                  size() const  { return FunctionList.size(); }
    556   bool                    empty() const { return FunctionList.empty(); }
    557 
    558   iterator_range<iterator> functions() {
    559     return make_range(begin(), end());
    560   }
    561   iterator_range<const_iterator> functions() const {
    562     return make_range(begin(), end());
    563   }
    564 
    565 /// @}
    566 /// @name Alias Iteration
    567 /// @{
    568 
    569   alias_iterator       alias_begin()            { return AliasList.begin(); }
    570   const_alias_iterator alias_begin() const      { return AliasList.begin(); }
    571   alias_iterator       alias_end  ()            { return AliasList.end();   }
    572   const_alias_iterator alias_end  () const      { return AliasList.end();   }
    573   size_t               alias_size () const      { return AliasList.size();  }
    574   bool                 alias_empty() const      { return AliasList.empty(); }
    575 
    576   iterator_range<alias_iterator> aliases() {
    577     return make_range(alias_begin(), alias_end());
    578   }
    579   iterator_range<const_alias_iterator> aliases() const {
    580     return make_range(alias_begin(), alias_end());
    581   }
    582 
    583 /// @}
    584 /// @name IFunc Iteration
    585 /// @{
    586 
    587   ifunc_iterator       ifunc_begin()            { return IFuncList.begin(); }
    588   const_ifunc_iterator ifunc_begin() const      { return IFuncList.begin(); }
    589   ifunc_iterator       ifunc_end  ()            { return IFuncList.end();   }
    590   const_ifunc_iterator ifunc_end  () const      { return IFuncList.end();   }
    591   size_t               ifunc_size () const      { return IFuncList.size();  }
    592   bool                 ifunc_empty() const      { return IFuncList.empty(); }
    593 
    594   iterator_range<ifunc_iterator> ifuncs() {
    595     return make_range(ifunc_begin(), ifunc_end());
    596   }
    597   iterator_range<const_ifunc_iterator> ifuncs() const {
    598     return make_range(ifunc_begin(), ifunc_end());
    599   }
    600 
    601   /// @}
    602   /// @name Convenience iterators
    603   /// @{
    604 
    605   typedef concat_iterator<GlobalObject, iterator, global_iterator>
    606       global_object_iterator;
    607   typedef concat_iterator<const GlobalObject, const_iterator,
    608                           const_global_iterator>
    609       const_global_object_iterator;
    610 
    611   iterator_range<global_object_iterator> global_objects() {
    612     return concat<GlobalObject>(functions(), globals());
    613   }
    614   iterator_range<const_global_object_iterator> global_objects() const {
    615     return concat<const GlobalObject>(functions(), globals());
    616   }
    617 
    618   global_object_iterator global_object_begin() {
    619     return global_objects().begin();
    620   }
    621   global_object_iterator global_object_end() { return global_objects().end(); }
    622 
    623   const_global_object_iterator global_object_begin() const {
    624     return global_objects().begin();
    625   }
    626   const_global_object_iterator global_object_end() const {
    627     return global_objects().end();
    628   }
    629 
    630   typedef concat_iterator<GlobalValue, iterator, global_iterator,
    631                           alias_iterator, ifunc_iterator>
    632       global_value_iterator;
    633   typedef concat_iterator<const GlobalValue, const_iterator,
    634                           const_global_iterator, const_alias_iterator,
    635                           const_ifunc_iterator>
    636       const_global_value_iterator;
    637 
    638   iterator_range<global_value_iterator> global_values() {
    639     return concat<GlobalValue>(functions(), globals(), aliases(), ifuncs());
    640   }
    641   iterator_range<const_global_value_iterator> global_values() const {
    642     return concat<const GlobalValue>(functions(), globals(), aliases(),
    643                                      ifuncs());
    644   }
    645 
    646   global_value_iterator global_value_begin() { return global_values().begin(); }
    647   global_value_iterator global_value_end() { return global_values().end(); }
    648 
    649   const_global_value_iterator global_value_begin() const {
    650     return global_values().begin();
    651   }
    652   const_global_value_iterator global_value_end() const {
    653     return global_values().end();
    654   }
    655 
    656   /// @}
    657   /// @name Named Metadata Iteration
    658   /// @{
    659 
    660   named_metadata_iterator named_metadata_begin() { return NamedMDList.begin(); }
    661   const_named_metadata_iterator named_metadata_begin() const {
    662     return NamedMDList.begin();
    663   }
    664 
    665   named_metadata_iterator named_metadata_end() { return NamedMDList.end(); }
    666   const_named_metadata_iterator named_metadata_end() const {
    667     return NamedMDList.end();
    668   }
    669 
    670   size_t named_metadata_size() const { return NamedMDList.size();  }
    671   bool named_metadata_empty() const { return NamedMDList.empty(); }
    672 
    673   iterator_range<named_metadata_iterator> named_metadata() {
    674     return make_range(named_metadata_begin(), named_metadata_end());
    675   }
    676   iterator_range<const_named_metadata_iterator> named_metadata() const {
    677     return make_range(named_metadata_begin(), named_metadata_end());
    678   }
    679 
    680   /// An iterator for DICompileUnits that skips those marked NoDebug.
    681   class debug_compile_units_iterator
    682       : public std::iterator<std::input_iterator_tag, DICompileUnit *> {
    683     NamedMDNode *CUs;
    684     unsigned Idx;
    685     void SkipNoDebugCUs();
    686   public:
    687     explicit debug_compile_units_iterator(NamedMDNode *CUs, unsigned Idx)
    688         : CUs(CUs), Idx(Idx) {
    689       SkipNoDebugCUs();
    690     }
    691     debug_compile_units_iterator &operator++() {
    692       ++Idx;
    693       SkipNoDebugCUs();
    694       return *this;
    695     }
    696     debug_compile_units_iterator operator++(int) {
    697       debug_compile_units_iterator T(*this);
    698       ++Idx;
    699       return T;
    700     }
    701     bool operator==(const debug_compile_units_iterator &I) const {
    702       return Idx == I.Idx;
    703     }
    704     bool operator!=(const debug_compile_units_iterator &I) const {
    705       return Idx != I.Idx;
    706     }
    707     DICompileUnit *operator*() const;
    708     DICompileUnit *operator->() const;
    709   };
    710 
    711   debug_compile_units_iterator debug_compile_units_begin() const {
    712     auto *CUs = getNamedMetadata("llvm.dbg.cu");
    713     return debug_compile_units_iterator(CUs, 0);
    714   }
    715 
    716   debug_compile_units_iterator debug_compile_units_end() const {
    717     auto *CUs = getNamedMetadata("llvm.dbg.cu");
    718     return debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0);
    719   }
    720 
    721   /// Return an iterator for all DICompileUnits listed in this Module's
    722   /// llvm.dbg.cu named metadata node and aren't explicitly marked as
    723   /// NoDebug.
    724   iterator_range<debug_compile_units_iterator> debug_compile_units() const {
    725     auto *CUs = getNamedMetadata("llvm.dbg.cu");
    726     return make_range(
    727         debug_compile_units_iterator(CUs, 0),
    728         debug_compile_units_iterator(CUs, CUs ? CUs->getNumOperands() : 0));
    729   }
    730 /// @}
    731 
    732   /// Destroy ConstantArrays in LLVMContext if they are not used.
    733   /// ConstantArrays constructed during linking can cause quadratic memory
    734   /// explosion. Releasing all unused constants can cause a 20% LTO compile-time
    735   /// slowdown for a large application.
    736   ///
    737   /// NOTE: Constants are currently owned by LLVMContext. This can then only
    738   /// be called where all uses of the LLVMContext are understood.
    739   void dropTriviallyDeadConstantArrays();
    740 
    741 /// @name Utility functions for printing and dumping Module objects
    742 /// @{
    743 
    744   /// Print the module to an output stream with an optional
    745   /// AssemblyAnnotationWriter.  If \c ShouldPreserveUseListOrder, then include
    746   /// uselistorder directives so that use-lists can be recreated when reading
    747   /// the assembly.
    748   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW,
    749              bool ShouldPreserveUseListOrder = false,
    750              bool IsForDebug = false) const;
    751 
    752   /// Dump the module to stderr (for debugging).
    753   void dump() const;
    754 
    755   /// This function causes all the subinstructions to "let go" of all references
    756   /// that they are maintaining.  This allows one to 'delete' a whole class at
    757   /// a time, even though there may be circular references... first all
    758   /// references are dropped, and all use counts go to zero.  Then everything
    759   /// is delete'd for real.  Note that no operations are valid on an object
    760   /// that has "dropped all references", except operator delete.
    761   void dropAllReferences();
    762 
    763 /// @}
    764 /// @name Utility functions for querying Debug information.
    765 /// @{
    766 
    767   /// \brief Returns the Number of Register ParametersDwarf Version by checking
    768   /// module flags.
    769   unsigned getNumberRegisterParameters() const;
    770 
    771   /// \brief Returns the Dwarf Version by checking module flags.
    772   unsigned getDwarfVersion() const;
    773 
    774   /// \brief Returns the CodeView Version by checking module flags.
    775   /// Returns zero if not present in module.
    776   unsigned getCodeViewFlag() const;
    777 
    778 /// @}
    779 /// @name Utility functions for querying and setting PIC level
    780 /// @{
    781 
    782   /// \brief Returns the PIC level (small or large model)
    783   PICLevel::Level getPICLevel() const;
    784 
    785   /// \brief Set the PIC level (small or large model)
    786   void setPICLevel(PICLevel::Level PL);
    787 /// @}
    788 
    789 /// @}
    790 /// @name Utility functions for querying and setting PIE level
    791 /// @{
    792 
    793   /// \brief Returns the PIE level (small or large model)
    794   PIELevel::Level getPIELevel() const;
    795 
    796   /// \brief Set the PIE level (small or large model)
    797   void setPIELevel(PIELevel::Level PL);
    798 /// @}
    799 
    800   /// @name Utility functions for querying and setting PGO summary
    801   /// @{
    802 
    803   /// \brief Attach profile summary metadata to this module.
    804   void setProfileSummary(Metadata *M);
    805 
    806   /// \brief Returns profile summary metadata
    807   Metadata *getProfileSummary();
    808   /// @}
    809 
    810   /// Take ownership of the given memory buffer.
    811   void setOwnedMemoryBuffer(std::unique_ptr<MemoryBuffer> MB);
    812 };
    813 
    814 /// \brief Given "llvm.used" or "llvm.compiler.used" as a global name, collect
    815 /// the initializer elements of that global in Set and return the global itself.
    816 GlobalVariable *collectUsedGlobalVariables(const Module &M,
    817                                            SmallPtrSetImpl<GlobalValue *> &Set,
    818                                            bool CompilerUsed);
    819 
    820 /// An raw_ostream inserter for modules.
    821 inline raw_ostream &operator<<(raw_ostream &O, const Module &M) {
    822   M.print(O, nullptr);
    823   return O;
    824 }
    825 
    826 // Create wrappers for C Binding types (see CBindingWrapping.h).
    827 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Module, LLVMModuleRef)
    828 
    829 /* LLVMModuleProviderRef exists for historical reasons, but now just holds a
    830  * Module.
    831  */
    832 inline Module *unwrap(LLVMModuleProviderRef MP) {
    833   return reinterpret_cast<Module*>(MP);
    834 }
    835 
    836 } // End llvm namespace
    837 
    838 #endif
    839