Home | History | Annotate | Download | only in IR
      1 //===- llvm/ModuleSummaryIndex.h - Module Summary Index ---------*- 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 /// ModuleSummaryIndex.h This file contains the declarations the classes that
     12 ///  hold the module index and summary for function importing.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #ifndef LLVM_IR_MODULESUMMARYINDEX_H
     17 #define LLVM_IR_MODULESUMMARYINDEX_H
     18 
     19 #include "llvm/ADT/ArrayRef.h"
     20 #include "llvm/ADT/DenseMap.h"
     21 #include "llvm/ADT/STLExtras.h"
     22 #include "llvm/ADT/SmallString.h"
     23 #include "llvm/ADT/StringExtras.h"
     24 #include "llvm/ADT/StringMap.h"
     25 #include "llvm/ADT/StringRef.h"
     26 #include "llvm/IR/GlobalValue.h"
     27 #include "llvm/IR/Module.h"
     28 #include <algorithm>
     29 #include <array>
     30 #include <cassert>
     31 #include <cstddef>
     32 #include <cstdint>
     33 #include <map>
     34 #include <memory>
     35 #include <set>
     36 #include <string>
     37 #include <utility>
     38 #include <vector>
     39 
     40 namespace llvm {
     41 
     42 namespace yaml {
     43 
     44 template <typename T> struct MappingTraits;
     45 
     46 } // end namespace yaml
     47 
     48 /// \brief Class to accumulate and hold information about a callee.
     49 struct CalleeInfo {
     50   enum class HotnessType : uint8_t { Unknown = 0, Cold = 1, None = 2, Hot = 3 };
     51   HotnessType Hotness = HotnessType::Unknown;
     52 
     53   CalleeInfo() = default;
     54   explicit CalleeInfo(HotnessType Hotness) : Hotness(Hotness) {}
     55 
     56   void updateHotness(const HotnessType OtherHotness) {
     57     Hotness = std::max(Hotness, OtherHotness);
     58   }
     59 };
     60 
     61 class GlobalValueSummary;
     62 
     63 using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
     64 
     65 struct GlobalValueSummaryInfo {
     66   /// The GlobalValue corresponding to this summary. This is only used in
     67   /// per-module summaries.
     68   const GlobalValue *GV = nullptr;
     69 
     70   /// List of global value summary structures for a particular value held
     71   /// in the GlobalValueMap. Requires a vector in the case of multiple
     72   /// COMDAT values of the same name.
     73   GlobalValueSummaryList SummaryList;
     74 };
     75 
     76 /// Map from global value GUID to corresponding summary structures. Use a
     77 /// std::map rather than a DenseMap so that pointers to the map's value_type
     78 /// (which are used by ValueInfo) are not invalidated by insertion. Also it will
     79 /// likely incur less overhead, as the value type is not very small and the size
     80 /// of the map is unknown, resulting in inefficiencies due to repeated
     81 /// insertions and resizing.
     82 using GlobalValueSummaryMapTy =
     83     std::map<GlobalValue::GUID, GlobalValueSummaryInfo>;
     84 
     85 /// Struct that holds a reference to a particular GUID in a global value
     86 /// summary.
     87 struct ValueInfo {
     88   const GlobalValueSummaryMapTy::value_type *Ref = nullptr;
     89 
     90   ValueInfo() = default;
     91   ValueInfo(const GlobalValueSummaryMapTy::value_type *Ref) : Ref(Ref) {}
     92 
     93   operator bool() const { return Ref; }
     94 
     95   GlobalValue::GUID getGUID() const { return Ref->first; }
     96   const GlobalValue *getValue() const { return Ref->second.GV; }
     97 
     98   ArrayRef<std::unique_ptr<GlobalValueSummary>> getSummaryList() const {
     99     return Ref->second.SummaryList;
    100   }
    101 };
    102 
    103 template <> struct DenseMapInfo<ValueInfo> {
    104   static inline ValueInfo getEmptyKey() {
    105     return ValueInfo((GlobalValueSummaryMapTy::value_type *)-1);
    106   }
    107 
    108   static inline ValueInfo getTombstoneKey() {
    109     return ValueInfo((GlobalValueSummaryMapTy::value_type *)-2);
    110   }
    111 
    112   static bool isEqual(ValueInfo L, ValueInfo R) { return L.Ref == R.Ref; }
    113   static unsigned getHashValue(ValueInfo I) { return (uintptr_t)I.Ref; }
    114 };
    115 
    116 /// \brief Function and variable summary information to aid decisions and
    117 /// implementation of importing.
    118 class GlobalValueSummary {
    119 public:
    120   /// \brief Sububclass discriminator (for dyn_cast<> et al.)
    121   enum SummaryKind : unsigned { AliasKind, FunctionKind, GlobalVarKind };
    122 
    123   /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
    124   struct GVFlags {
    125     /// \brief The linkage type of the associated global value.
    126     ///
    127     /// One use is to flag values that have local linkage types and need to
    128     /// have module identifier appended before placing into the combined
    129     /// index, to disambiguate from other values with the same name.
    130     /// In the future this will be used to update and optimize linkage
    131     /// types based on global summary-based analysis.
    132     unsigned Linkage : 4;
    133 
    134     /// Indicate if the global value cannot be imported (e.g. it cannot
    135     /// be renamed or references something that can't be renamed).
    136     unsigned NotEligibleToImport : 1;
    137 
    138     /// In per-module summary, indicate that the global value must be considered
    139     /// a live root for index-based liveness analysis. Used for special LLVM
    140     /// values such as llvm.global_ctors that the linker does not know about.
    141     ///
    142     /// In combined summary, indicate that the global value is live.
    143     unsigned Live : 1;
    144 
    145     /// Convenience Constructors
    146     explicit GVFlags(GlobalValue::LinkageTypes Linkage,
    147                      bool NotEligibleToImport, bool Live)
    148         : Linkage(Linkage), NotEligibleToImport(NotEligibleToImport),
    149           Live(Live) {}
    150   };
    151 
    152 private:
    153   /// Kind of summary for use in dyn_cast<> et al.
    154   SummaryKind Kind;
    155 
    156   GVFlags Flags;
    157 
    158   /// This is the hash of the name of the symbol in the original file. It is
    159   /// identical to the GUID for global symbols, but differs for local since the
    160   /// GUID includes the module level id in the hash.
    161   GlobalValue::GUID OriginalName = 0;
    162 
    163   /// \brief Path of module IR containing value's definition, used to locate
    164   /// module during importing.
    165   ///
    166   /// This is only used during parsing of the combined index, or when
    167   /// parsing the per-module index for creation of the combined summary index,
    168   /// not during writing of the per-module index which doesn't contain a
    169   /// module path string table.
    170   StringRef ModulePath;
    171 
    172   /// List of values referenced by this global value's definition
    173   /// (either by the initializer of a global variable, or referenced
    174   /// from within a function). This does not include functions called, which
    175   /// are listed in the derived FunctionSummary object.
    176   std::vector<ValueInfo> RefEdgeList;
    177 
    178   bool isLive() const { return Flags.Live; }
    179 
    180 protected:
    181   GlobalValueSummary(SummaryKind K, GVFlags Flags, std::vector<ValueInfo> Refs)
    182       : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {}
    183 
    184 public:
    185   virtual ~GlobalValueSummary() = default;
    186 
    187   /// Returns the hash of the original name, it is identical to the GUID for
    188   /// externally visible symbols, but not for local ones.
    189   GlobalValue::GUID getOriginalName() { return OriginalName; }
    190 
    191   /// Initialize the original name hash in this summary.
    192   void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
    193 
    194   /// Which kind of summary subclass this is.
    195   SummaryKind getSummaryKind() const { return Kind; }
    196 
    197   /// Set the path to the module containing this function, for use in
    198   /// the combined index.
    199   void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
    200 
    201   /// Get the path to the module containing this function.
    202   StringRef modulePath() const { return ModulePath; }
    203 
    204   /// Get the flags for this GlobalValue (see \p struct GVFlags).
    205   GVFlags flags() { return Flags; }
    206 
    207   /// Return linkage type recorded for this global value.
    208   GlobalValue::LinkageTypes linkage() const {
    209     return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
    210   }
    211 
    212   /// Sets the linkage to the value determined by global summary-based
    213   /// optimization. Will be applied in the ThinLTO backends.
    214   void setLinkage(GlobalValue::LinkageTypes Linkage) {
    215     Flags.Linkage = Linkage;
    216   }
    217 
    218   /// Return true if this global value can't be imported.
    219   bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
    220 
    221   void setLive(bool Live) { Flags.Live = Live; }
    222 
    223   /// Flag that this global value cannot be imported.
    224   void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
    225 
    226   /// Return the list of values referenced by this global value definition.
    227   ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
    228 
    229   friend class ModuleSummaryIndex;
    230   friend void computeDeadSymbols(class ModuleSummaryIndex &,
    231                                  const DenseSet<GlobalValue::GUID> &);
    232 };
    233 
    234 /// \brief Alias summary information.
    235 class AliasSummary : public GlobalValueSummary {
    236   GlobalValueSummary *AliaseeSummary;
    237 
    238 public:
    239   AliasSummary(GVFlags Flags, std::vector<ValueInfo> Refs)
    240       : GlobalValueSummary(AliasKind, Flags, std::move(Refs)) {}
    241 
    242   /// Check if this is an alias summary.
    243   static bool classof(const GlobalValueSummary *GVS) {
    244     return GVS->getSummaryKind() == AliasKind;
    245   }
    246 
    247   void setAliasee(GlobalValueSummary *Aliasee) { AliaseeSummary = Aliasee; }
    248 
    249   const GlobalValueSummary &getAliasee() const {
    250     assert(AliaseeSummary && "Unexpected missing aliasee summary");
    251     return *AliaseeSummary;
    252   }
    253 
    254   GlobalValueSummary &getAliasee() {
    255     return const_cast<GlobalValueSummary &>(
    256                          static_cast<const AliasSummary *>(this)->getAliasee());
    257   }
    258 };
    259 
    260 /// \brief Function summary information to aid decisions and implementation of
    261 /// importing.
    262 class FunctionSummary : public GlobalValueSummary {
    263 public:
    264   /// <CalleeValueInfo, CalleeInfo> call edge pair.
    265   using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
    266 
    267   /// An "identifier" for a virtual function. This contains the type identifier
    268   /// represented as a GUID and the offset from the address point to the virtual
    269   /// function pointer, where "address point" is as defined in the Itanium ABI:
    270   /// https://mentorembedded.github.io/cxx-abi/abi.html#vtable-general
    271   struct VFuncId {
    272     GlobalValue::GUID GUID;
    273     uint64_t Offset;
    274   };
    275 
    276   /// A specification for a virtual function call with all constant integer
    277   /// arguments. This is used to perform virtual constant propagation on the
    278   /// summary.
    279   struct ConstVCall {
    280     VFuncId VFunc;
    281     std::vector<uint64_t> Args;
    282   };
    283 
    284 private:
    285   /// Number of instructions (ignoring debug instructions, e.g.) computed
    286   /// during the initial compile step when the summary index is first built.
    287   unsigned InstCount;
    288 
    289   /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
    290   std::vector<EdgeTy> CallGraphEdgeList;
    291 
    292   /// All type identifier related information. Because these fields are
    293   /// relatively uncommon we only allocate space for them if necessary.
    294   struct TypeIdInfo {
    295     /// List of type identifiers used by this function in llvm.type.test
    296     /// intrinsics other than by an llvm.assume intrinsic, represented as GUIDs.
    297     std::vector<GlobalValue::GUID> TypeTests;
    298 
    299     /// List of virtual calls made by this function using (respectively)
    300     /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
    301     /// not have all constant integer arguments.
    302     std::vector<VFuncId> TypeTestAssumeVCalls, TypeCheckedLoadVCalls;
    303 
    304     /// List of virtual calls made by this function using (respectively)
    305     /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
    306     /// all constant integer arguments.
    307     std::vector<ConstVCall> TypeTestAssumeConstVCalls,
    308         TypeCheckedLoadConstVCalls;
    309   };
    310 
    311   std::unique_ptr<TypeIdInfo> TIdInfo;
    312 
    313 public:
    314   FunctionSummary(GVFlags Flags, unsigned NumInsts, std::vector<ValueInfo> Refs,
    315                   std::vector<EdgeTy> CGEdges,
    316                   std::vector<GlobalValue::GUID> TypeTests,
    317                   std::vector<VFuncId> TypeTestAssumeVCalls,
    318                   std::vector<VFuncId> TypeCheckedLoadVCalls,
    319                   std::vector<ConstVCall> TypeTestAssumeConstVCalls,
    320                   std::vector<ConstVCall> TypeCheckedLoadConstVCalls)
    321       : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
    322         InstCount(NumInsts), CallGraphEdgeList(std::move(CGEdges)) {
    323     if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
    324         !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
    325         !TypeCheckedLoadConstVCalls.empty())
    326       TIdInfo = llvm::make_unique<TypeIdInfo>(TypeIdInfo{
    327           std::move(TypeTests), std::move(TypeTestAssumeVCalls),
    328           std::move(TypeCheckedLoadVCalls),
    329           std::move(TypeTestAssumeConstVCalls),
    330           std::move(TypeCheckedLoadConstVCalls)});
    331   }
    332 
    333   /// Check if this is a function summary.
    334   static bool classof(const GlobalValueSummary *GVS) {
    335     return GVS->getSummaryKind() == FunctionKind;
    336   }
    337 
    338   /// Get the instruction count recorded for this function.
    339   unsigned instCount() const { return InstCount; }
    340 
    341   /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
    342   ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
    343 
    344   /// Returns the list of type identifiers used by this function in
    345   /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
    346   /// represented as GUIDs.
    347   ArrayRef<GlobalValue::GUID> type_tests() const {
    348     if (TIdInfo)
    349       return TIdInfo->TypeTests;
    350     return {};
    351   }
    352 
    353   /// Returns the list of virtual calls made by this function using
    354   /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
    355   /// integer arguments.
    356   ArrayRef<VFuncId> type_test_assume_vcalls() const {
    357     if (TIdInfo)
    358       return TIdInfo->TypeTestAssumeVCalls;
    359     return {};
    360   }
    361 
    362   /// Returns the list of virtual calls made by this function using
    363   /// llvm.type.checked.load intrinsics that do not have all constant integer
    364   /// arguments.
    365   ArrayRef<VFuncId> type_checked_load_vcalls() const {
    366     if (TIdInfo)
    367       return TIdInfo->TypeCheckedLoadVCalls;
    368     return {};
    369   }
    370 
    371   /// Returns the list of virtual calls made by this function using
    372   /// llvm.assume(llvm.type.test) intrinsics with all constant integer
    373   /// arguments.
    374   ArrayRef<ConstVCall> type_test_assume_const_vcalls() const {
    375     if (TIdInfo)
    376       return TIdInfo->TypeTestAssumeConstVCalls;
    377     return {};
    378   }
    379 
    380   /// Returns the list of virtual calls made by this function using
    381   /// llvm.type.checked.load intrinsics with all constant integer arguments.
    382   ArrayRef<ConstVCall> type_checked_load_const_vcalls() const {
    383     if (TIdInfo)
    384       return TIdInfo->TypeCheckedLoadConstVCalls;
    385     return {};
    386   }
    387 
    388   /// Add a type test to the summary. This is used by WholeProgramDevirt if we
    389   /// were unable to devirtualize a checked call.
    390   void addTypeTest(GlobalValue::GUID Guid) {
    391     if (!TIdInfo)
    392       TIdInfo = llvm::make_unique<TypeIdInfo>();
    393     TIdInfo->TypeTests.push_back(Guid);
    394   }
    395 };
    396 
    397 template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
    398   static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
    399 
    400   static FunctionSummary::VFuncId getTombstoneKey() {
    401     return {0, uint64_t(-2)};
    402   }
    403 
    404   static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R) {
    405     return L.GUID == R.GUID && L.Offset == R.Offset;
    406   }
    407 
    408   static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
    409 };
    410 
    411 template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
    412   static FunctionSummary::ConstVCall getEmptyKey() {
    413     return {{0, uint64_t(-1)}, {}};
    414   }
    415 
    416   static FunctionSummary::ConstVCall getTombstoneKey() {
    417     return {{0, uint64_t(-2)}, {}};
    418   }
    419 
    420   static bool isEqual(FunctionSummary::ConstVCall L,
    421                       FunctionSummary::ConstVCall R) {
    422     return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
    423            L.Args == R.Args;
    424   }
    425 
    426   static unsigned getHashValue(FunctionSummary::ConstVCall I) {
    427     return I.VFunc.GUID;
    428   }
    429 };
    430 
    431 /// \brief Global variable summary information to aid decisions and
    432 /// implementation of importing.
    433 ///
    434 /// Currently this doesn't add anything to the base \p GlobalValueSummary,
    435 /// but is a placeholder as additional info may be added to the summary
    436 /// for variables.
    437 class GlobalVarSummary : public GlobalValueSummary {
    438 
    439 public:
    440   GlobalVarSummary(GVFlags Flags, std::vector<ValueInfo> Refs)
    441       : GlobalValueSummary(GlobalVarKind, Flags, std::move(Refs)) {}
    442 
    443   /// Check if this is a global variable summary.
    444   static bool classof(const GlobalValueSummary *GVS) {
    445     return GVS->getSummaryKind() == GlobalVarKind;
    446   }
    447 };
    448 
    449 struct TypeTestResolution {
    450   /// Specifies which kind of type check we should emit for this byte array.
    451   /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
    452   /// details on each kind of check; the enumerators are described with
    453   /// reference to that document.
    454   enum Kind {
    455     Unsat,     ///< Unsatisfiable type (i.e. no global has this type metadata)
    456     ByteArray, ///< Test a byte array (first example)
    457     Inline,    ///< Inlined bit vector ("Short Inline Bit Vectors")
    458     Single,    ///< Single element (last example in "Short Inline Bit Vectors")
    459     AllOnes,   ///< All-ones bit vector ("Eliminating Bit Vector Checks for
    460                ///  All-Ones Bit Vectors")
    461   } TheKind = Unsat;
    462 
    463   /// Range of size-1 expressed as a bit width. For example, if the size is in
    464   /// range [1,256], this number will be 8. This helps generate the most compact
    465   /// instruction sequences.
    466   unsigned SizeM1BitWidth = 0;
    467 };
    468 
    469 struct WholeProgramDevirtResolution {
    470   enum Kind {
    471     Indir,      ///< Just do a regular virtual call
    472     SingleImpl, ///< Single implementation devirtualization
    473   } TheKind = Indir;
    474 
    475   std::string SingleImplName;
    476 
    477   struct ByArg {
    478     enum Kind {
    479       Indir,            ///< Just do a regular virtual call
    480       UniformRetVal,    ///< Uniform return value optimization
    481       UniqueRetVal,     ///< Unique return value optimization
    482       VirtualConstProp, ///< Virtual constant propagation
    483     } TheKind = Indir;
    484 
    485     /// Additional information for the resolution:
    486     /// - UniformRetVal: the uniform return value.
    487     /// - UniqueRetVal: the return value associated with the unique vtable (0 or
    488     ///   1).
    489     uint64_t Info = 0;
    490   };
    491 
    492   /// Resolutions for calls with all constant integer arguments (excluding the
    493   /// first argument, "this"), where the key is the argument vector.
    494   std::map<std::vector<uint64_t>, ByArg> ResByArg;
    495 };
    496 
    497 struct TypeIdSummary {
    498   TypeTestResolution TTRes;
    499 
    500   /// Mapping from byte offset to whole-program devirt resolution for that
    501   /// (typeid, byte offset) pair.
    502   std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
    503 };
    504 
    505 /// 160 bits SHA1
    506 using ModuleHash = std::array<uint32_t, 5>;
    507 
    508 /// Type used for iterating through the global value summary map.
    509 using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
    510 using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
    511 
    512 /// String table to hold/own module path strings, which additionally holds the
    513 /// module ID assigned to each module during the plugin step, as well as a hash
    514 /// of the module. The StringMap makes a copy of and owns inserted strings.
    515 using ModulePathStringTableTy = StringMap<std::pair<uint64_t, ModuleHash>>;
    516 
    517 /// Map of global value GUID to its summary, used to identify values defined in
    518 /// a particular module, and provide efficient access to their summary.
    519 using GVSummaryMapTy = std::map<GlobalValue::GUID, GlobalValueSummary *>;
    520 
    521 /// Class to hold module path string table and global value map,
    522 /// and encapsulate methods for operating on them.
    523 class ModuleSummaryIndex {
    524 private:
    525   /// Map from value name to list of summary instances for values of that
    526   /// name (may be duplicates in the COMDAT case, e.g.).
    527   GlobalValueSummaryMapTy GlobalValueMap;
    528 
    529   /// Holds strings for combined index, mapping to the corresponding module ID.
    530   ModulePathStringTableTy ModulePathStringTable;
    531 
    532   /// Mapping from type identifiers to summary information for that type
    533   /// identifier.
    534   // FIXME: Add bitcode read/write support for this field.
    535   std::map<std::string, TypeIdSummary> TypeIdMap;
    536 
    537   /// Mapping from original ID to GUID. If original ID can map to multiple
    538   /// GUIDs, it will be mapped to 0.
    539   std::map<GlobalValue::GUID, GlobalValue::GUID> OidGuidMap;
    540 
    541   /// Indicates that summary-based GlobalValue GC has run, and values with
    542   /// GVFlags::Live==false are really dead. Otherwise, all values must be
    543   /// considered live.
    544   bool WithGlobalValueDeadStripping = false;
    545 
    546   std::set<std::string> CfiFunctionDefs;
    547   std::set<std::string> CfiFunctionDecls;
    548 
    549   // YAML I/O support.
    550   friend yaml::MappingTraits<ModuleSummaryIndex>;
    551 
    552   GlobalValueSummaryMapTy::value_type *
    553   getOrInsertValuePtr(GlobalValue::GUID GUID) {
    554     return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo{}).first;
    555   }
    556 
    557 public:
    558   gvsummary_iterator begin() { return GlobalValueMap.begin(); }
    559   const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
    560   gvsummary_iterator end() { return GlobalValueMap.end(); }
    561   const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
    562   size_t size() const { return GlobalValueMap.size(); }
    563 
    564   bool withGlobalValueDeadStripping() const {
    565     return WithGlobalValueDeadStripping;
    566   }
    567   void setWithGlobalValueDeadStripping() {
    568     WithGlobalValueDeadStripping = true;
    569   }
    570 
    571   bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
    572     return !WithGlobalValueDeadStripping || GVS->isLive();
    573   }
    574   bool isGUIDLive(GlobalValue::GUID GUID) const;
    575 
    576   /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
    577   ValueInfo getValueInfo(GlobalValue::GUID GUID) const {
    578     auto I = GlobalValueMap.find(GUID);
    579     return ValueInfo(I == GlobalValueMap.end() ? nullptr : &*I);
    580   }
    581 
    582   /// Return a ValueInfo for \p GUID.
    583   ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID) {
    584     return ValueInfo(getOrInsertValuePtr(GUID));
    585   }
    586 
    587   /// Return a ValueInfo for \p GV and mark it as belonging to GV.
    588   ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
    589     auto VP = getOrInsertValuePtr(GV->getGUID());
    590     VP->second.GV = GV;
    591     return ValueInfo(VP);
    592   }
    593 
    594   /// Return the GUID for \p OriginalId in the OidGuidMap.
    595   GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const {
    596     const auto I = OidGuidMap.find(OriginalID);
    597     return I == OidGuidMap.end() ? 0 : I->second;
    598   }
    599 
    600   std::set<std::string> &cfiFunctionDefs() { return CfiFunctionDefs; }
    601   const std::set<std::string> &cfiFunctionDefs() const { return CfiFunctionDefs; }
    602 
    603   std::set<std::string> &cfiFunctionDecls() { return CfiFunctionDecls; }
    604   const std::set<std::string> &cfiFunctionDecls() const { return CfiFunctionDecls; }
    605 
    606   /// Add a global value summary for a value of the given name.
    607   void addGlobalValueSummary(StringRef ValueName,
    608                              std::unique_ptr<GlobalValueSummary> Summary) {
    609     addGlobalValueSummary(getOrInsertValueInfo(GlobalValue::getGUID(ValueName)),
    610                           std::move(Summary));
    611   }
    612 
    613   /// Add a global value summary for the given ValueInfo.
    614   void addGlobalValueSummary(ValueInfo VI,
    615                              std::unique_ptr<GlobalValueSummary> Summary) {
    616     addOriginalName(VI.getGUID(), Summary->getOriginalName());
    617     // Here we have a notionally const VI, but the value it points to is owned
    618     // by the non-const *this.
    619     const_cast<GlobalValueSummaryMapTy::value_type *>(VI.Ref)
    620         ->second.SummaryList.push_back(std::move(Summary));
    621   }
    622 
    623   /// Add an original name for the value of the given GUID.
    624   void addOriginalName(GlobalValue::GUID ValueGUID,
    625                        GlobalValue::GUID OrigGUID) {
    626     if (OrigGUID == 0 || ValueGUID == OrigGUID)
    627       return;
    628     if (OidGuidMap.count(OrigGUID) && OidGuidMap[OrigGUID] != ValueGUID)
    629       OidGuidMap[OrigGUID] = 0;
    630     else
    631       OidGuidMap[OrigGUID] = ValueGUID;
    632   }
    633 
    634   /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
    635   /// not found.
    636   GlobalValueSummary *findSummaryInModule(GlobalValue::GUID ValueGUID,
    637                                           StringRef ModuleId) const {
    638     auto CalleeInfo = getValueInfo(ValueGUID);
    639     if (!CalleeInfo) {
    640       return nullptr; // This function does not have a summary
    641     }
    642     auto Summary =
    643         llvm::find_if(CalleeInfo.getSummaryList(),
    644                       [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
    645                         return Summary->modulePath() == ModuleId;
    646                       });
    647     if (Summary == CalleeInfo.getSummaryList().end())
    648       return nullptr;
    649     return Summary->get();
    650   }
    651 
    652   /// Returns the first GlobalValueSummary for \p GV, asserting that there
    653   /// is only one if \p PerModuleIndex.
    654   GlobalValueSummary *getGlobalValueSummary(const GlobalValue &GV,
    655                                             bool PerModuleIndex = true) const {
    656     assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
    657     return getGlobalValueSummary(GlobalValue::getGUID(GV.getName()),
    658                                  PerModuleIndex);
    659   }
    660 
    661   /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
    662   /// there
    663   /// is only one if \p PerModuleIndex.
    664   GlobalValueSummary *getGlobalValueSummary(GlobalValue::GUID ValueGUID,
    665                                             bool PerModuleIndex = true) const;
    666 
    667   /// Table of modules, containing module hash and id.
    668   const StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() const {
    669     return ModulePathStringTable;
    670   }
    671 
    672   /// Table of modules, containing hash and id.
    673   StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() {
    674     return ModulePathStringTable;
    675   }
    676 
    677   /// Get the module ID recorded for the given module path.
    678   uint64_t getModuleId(const StringRef ModPath) const {
    679     return ModulePathStringTable.lookup(ModPath).first;
    680   }
    681 
    682   /// Get the module SHA1 hash recorded for the given module path.
    683   const ModuleHash &getModuleHash(const StringRef ModPath) const {
    684     auto It = ModulePathStringTable.find(ModPath);
    685     assert(It != ModulePathStringTable.end() && "Module not registered");
    686     return It->second.second;
    687   }
    688 
    689   /// Convenience method for creating a promoted global name
    690   /// for the given value name of a local, and its original module's ID.
    691   static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
    692     SmallString<256> NewName(Name);
    693     NewName += ".llvm.";
    694     NewName += utohexstr(ModHash[0]); // Take the first 32 bits
    695     return NewName.str();
    696   }
    697 
    698   /// Helper to obtain the unpromoted name for a global value (or the original
    699   /// name if not promoted).
    700   static StringRef getOriginalNameBeforePromote(StringRef Name) {
    701     std::pair<StringRef, StringRef> Pair = Name.split(".llvm.");
    702     return Pair.first;
    703   }
    704 
    705   typedef ModulePathStringTableTy::value_type ModuleInfo;
    706 
    707   /// Add a new module with the given \p Hash, mapped to the given \p
    708   /// ModID, and return a reference to the module.
    709   ModuleInfo *addModule(StringRef ModPath, uint64_t ModId,
    710                         ModuleHash Hash = ModuleHash{{0}}) {
    711     return &*ModulePathStringTable.insert({ModPath, {ModId, Hash}}).first;
    712   }
    713 
    714   /// Check if the given Module has any functions available for exporting
    715   /// in the index. We consider any module present in the ModulePathStringTable
    716   /// to have exported functions.
    717   bool hasExportedFunctions(const Module &M) const {
    718     return ModulePathStringTable.count(M.getModuleIdentifier());
    719   }
    720 
    721   const std::map<std::string, TypeIdSummary> &typeIds() const {
    722     return TypeIdMap;
    723   }
    724 
    725   /// This accessor should only be used when exporting because it can mutate the
    726   /// map.
    727   TypeIdSummary &getOrInsertTypeIdSummary(StringRef TypeId) {
    728     return TypeIdMap[TypeId];
    729   }
    730 
    731   /// This returns either a pointer to the type id summary (if present in the
    732   /// summary map) or null (if not present). This may be used when importing.
    733   const TypeIdSummary *getTypeIdSummary(StringRef TypeId) const {
    734     auto I = TypeIdMap.find(TypeId);
    735     if (I == TypeIdMap.end())
    736       return nullptr;
    737     return &I->second;
    738   }
    739 
    740   /// Collect for the given module the list of function it defines
    741   /// (GUID -> Summary).
    742   void collectDefinedFunctionsForModule(StringRef ModulePath,
    743                                         GVSummaryMapTy &GVSummaryMap) const;
    744 
    745   /// Collect for each module the list of Summaries it defines (GUID ->
    746   /// Summary).
    747   void collectDefinedGVSummariesPerModule(
    748       StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) const;
    749 };
    750 
    751 } // end namespace llvm
    752 
    753 #endif // LLVM_IR_MODULESUMMARYINDEX_H
    754