LLVM 23.0.0git
ModuleSummaryIndex.h
Go to the documentation of this file.
1//===- llvm/ModuleSummaryIndex.h - Module Summary Index ---------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// @file
10/// ModuleSummaryIndex.h This file contains the declarations the classes that
11/// hold the module index and summary for function importing.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_MODULESUMMARYINDEX_H
16#define LLVM_IR_MODULESUMMARYINDEX_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/Module.h"
32#include "llvm/Support/Debug.h"
37#include <algorithm>
38#include <array>
39#include <cassert>
40#include <cstddef>
41#include <cstdint>
42#include <map>
43#include <memory>
44#include <optional>
45#include <set>
46#include <string>
47#include <unordered_set>
48#include <utility>
49#include <vector>
50
51namespace llvm {
52
53template <class GraphType> struct GraphTraits;
54
55namespace yaml {
56
57template <typename T> struct MappingTraits;
58
59} // end namespace yaml
60
61/// Class to accumulate and hold information about a callee.
62struct CalleeInfo {
63 enum class HotnessType : uint8_t {
65 Cold = 1,
66 None = 2,
67 Hot = 3,
69 };
70
71 // The size of the bit-field might need to be adjusted if more values are
72 // added to HotnessType enum.
74
75 // True if at least one of the calls to the callee is a tail call.
78
82 explicit CalleeInfo(HotnessType Hotness, bool HasTC)
83 : Hotness(static_cast<uint32_t>(Hotness)), HasTailCall(HasTC) {}
84
85 void updateHotness(const HotnessType OtherHotness) {
86 Hotness = std::max(Hotness, static_cast<uint32_t>(OtherHotness));
87 }
88
89 bool hasTailCall() const { return HasTailCall; }
90
91 void setHasTailCall(const bool HasTC) { HasTailCall = HasTC; }
92
94};
95
97 switch (HT) {
99 return "unknown";
101 return "cold";
103 return "none";
105 return "hot";
107 return "critical";
108 }
109 llvm_unreachable("invalid hotness");
110}
111
112class GlobalValueSummary;
113
114using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
115
116struct alignas(8) GlobalValueSummaryInfo {
117 union NameOrGV {
118 NameOrGV(bool HaveGVs) {
119 if (HaveGVs)
120 GV = nullptr;
121 else
122 Name = "";
123 }
124
125 /// The GlobalValue corresponding to this summary. This is only used in
126 /// per-module summaries and when the IR is available. E.g. when module
127 /// analysis is being run, or when parsing both the IR and the summary
128 /// from assembly.
130
131 /// Summary string representation. This StringRef points to BC module
132 /// string table and is valid until module data is stored in memory.
133 /// This is guaranteed to happen until runThinLTOBackend function is
134 /// called, so it is safe to use this field during thin link. This field
135 /// is only valid if summary index was loaded from BC file.
137 } U;
138
139 inline GlobalValueSummaryInfo(bool HaveGVs);
140
141 /// Access a read-only list of global value summary structures for a
142 /// particular value held in the GlobalValueMap.
144 return SummaryList;
145 }
146
147 /// Add a summary corresponding to a global value definition in a module with
148 /// the corresponding GUID.
149 inline void addSummary(std::unique_ptr<GlobalValueSummary> Summary);
150
151 /// Verify that the HasLocal flag is consistent with the SummaryList. Should
152 /// only be called prior to index-based internalization and promotion.
153 inline void verifyLocal() const;
154
155 bool hasLocal() const { return HasLocal; }
156
157private:
158 /// List of global value summary structures for a particular value held
159 /// in the GlobalValueMap. Requires a vector in the case of multiple
160 /// COMDAT values of the same name, weak symbols, locals of the same name when
161 /// compiling without sufficient distinguishing path, or (theoretically) hash
162 /// collisions. Each summary is from a different module.
163 GlobalValueSummaryList SummaryList;
164
165 /// True if the SummaryList contains at least one summary with local linkage.
166 /// In most cases there should be only one, unless translation units with
167 /// same-named locals were compiled without distinguishing path. And generally
168 /// there should not be a mix of local and non-local summaries, because the
169 /// GUID for a local is computed with the path prepended and a ';' delimiter.
170 /// In extremely rare cases there could be a GUID hash collision. Having the
171 /// flag saves having to walk through all summaries to prove the existence or
172 /// not of any locals.
173 /// NOTE: this flag is set when the index is built. It does not reflect
174 /// index-based internalization and promotion decisions. Generally most
175 /// index-based analysis occurs before then, but any users should assert that
176 /// the withInternalizeAndPromote() flag is not set on the index.
177 /// TODO: Replace checks in various ThinLTO analyses that loop through all
178 /// summaries to handle the local case with a check of the flag.
179 bool HasLocal : 1;
180};
181
182/// Map from global value GUID to corresponding summary structures. Use a
183/// std::map rather than a DenseMap so that pointers to the map's value_type
184/// (which are used by ValueInfo) are not invalidated by insertion. Also it will
185/// likely incur less overhead, as the value type is not very small and the size
186/// of the map is unknown, resulting in inefficiencies due to repeated
187/// insertions and resizing.
189 std::map<GlobalValue::GUID, GlobalValueSummaryInfo>;
190
191/// Struct that holds a reference to a particular GUID in a global value
192/// summary.
193struct ValueInfo {
194 enum Flags { HaveGV = 1, ReadOnly = 2, WriteOnly = 4 };
197
198 ValueInfo() = default;
199 ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R) {
200 RefAndFlags.setPointer(R);
201 RefAndFlags.setInt(HaveGVs);
202 }
203
204 explicit operator bool() const { return getRef(); }
205
206 GlobalValue::GUID getGUID() const { return getRef()->first; }
207 const GlobalValue *getValue() const {
208 assert(haveGVs());
209 return getRef()->second.U.GV;
210 }
211
213 return getRef()->second.getSummaryList();
214 }
215
216 void verifyLocal() const { getRef()->second.verifyLocal(); }
217
218 bool hasLocal() const { return getRef()->second.hasLocal(); }
219
220 // Even if the index is built with GVs available, we may not have one for
221 // summary entries synthesized for profiled indirect call targets.
222 bool hasName() const { return !haveGVs() || getValue(); }
223
224 StringRef name() const {
225 assert(!haveGVs() || getRef()->second.U.GV);
226 return haveGVs() ? getRef()->second.U.GV->getName()
227 : getRef()->second.U.Name;
228 }
229
230 bool haveGVs() const { return RefAndFlags.getInt() & HaveGV; }
231 bool isReadOnly() const {
233 return RefAndFlags.getInt() & ReadOnly;
234 }
235 bool isWriteOnly() const {
237 return RefAndFlags.getInt() & WriteOnly;
238 }
239 unsigned getAccessSpecifier() const {
241 return RefAndFlags.getInt() & (ReadOnly | WriteOnly);
242 }
244 unsigned BadAccessMask = ReadOnly | WriteOnly;
245 return (RefAndFlags.getInt() & BadAccessMask) != BadAccessMask;
246 }
247 void setReadOnly() {
248 // We expect ro/wo attribute to set only once during
249 // ValueInfo lifetime.
251 RefAndFlags.setInt(RefAndFlags.getInt() | ReadOnly);
252 }
255 RefAndFlags.setInt(RefAndFlags.getInt() | WriteOnly);
256 }
257
258 const GlobalValueSummaryMapTy::value_type *getRef() const {
259 return RefAndFlags.getPointer();
260 }
261
262 /// Returns the most constraining visibility among summaries. The
263 /// visibilities, ordered from least to most constraining, are: default,
264 /// protected and hidden.
266
267 /// Checks if all summaries are DSO local (have the flag set). When DSOLocal
268 /// propagation has been done, set the parameter to enable fast check.
269 LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation = false) const;
270
271 /// Checks if all copies are eligible for auto-hiding (have flag set).
272 LLVM_ABI bool canAutoHide() const;
273
275};
276
278 OS << VI.getGUID();
279 if (!VI.name().empty())
280 OS << " (" << VI.name() << ")";
281 return OS;
282}
283
284inline bool operator==(const ValueInfo &A, const ValueInfo &B) {
285 assert(A.getRef() && B.getRef() &&
286 "Need ValueInfo with non-null Ref for comparison");
287 return A.getRef() == B.getRef();
288}
289
290inline bool operator!=(const ValueInfo &A, const ValueInfo &B) {
291 assert(A.getRef() && B.getRef() &&
292 "Need ValueInfo with non-null Ref for comparison");
293 return A.getRef() != B.getRef();
294}
295
296inline bool operator<(const ValueInfo &A, const ValueInfo &B) {
297 assert(A.getRef() && B.getRef() &&
298 "Need ValueInfo with non-null Ref to compare GUIDs");
299 return A.getGUID() < B.getGUID();
300}
301
302template <> struct DenseMapInfo<ValueInfo> {
303 static inline ValueInfo getEmptyKey() {
304 return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
305 }
306
307 static inline ValueInfo getTombstoneKey() {
308 return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-16);
309 }
310
311 static inline bool isSpecialKey(ValueInfo V) {
312 return V == getTombstoneKey() || V == getEmptyKey();
313 }
314
315 static bool isEqual(ValueInfo L, ValueInfo R) {
316 // We are not supposed to mix ValueInfo(s) with different HaveGVs flag
317 // in a same container.
318 assert(isSpecialKey(L) || isSpecialKey(R) || (L.haveGVs() == R.haveGVs()));
319 return L.getRef() == R.getRef();
320 }
321 static unsigned getHashValue(ValueInfo I) { return hash_value(I.getRef()); }
322};
323
324// For optional hinted size reporting, holds a pair of the full stack id
325// (pre-trimming, from the full context in the profile), and the associated
326// total profiled size.
331
332/// Summary of memprof callsite metadata.
334 // Actual callee function.
336
337 // Used to record whole program analysis cloning decisions.
338 // The ThinLTO backend will need to create as many clones as there are entries
339 // in the vector (it is expected and should be confirmed that all such
340 // summaries in the same FunctionSummary have the same number of entries).
341 // Each index records version info for the corresponding clone of this
342 // function. The value is the callee clone it calls (becomes the appended
343 // suffix id). Index 0 is the original version, and a value of 0 calls the
344 // original callee.
346
347 // Represents stack ids in this context, recorded as indices into the
348 // StackIds vector in the summary index, which in turn holds the full 64-bit
349 // stack ids. This reduces memory as there are in practice far fewer unique
350 // stack ids than stack id references.
352
359};
360
362 OS << "Callee: " << SNI.Callee;
363 OS << " Clones: " << llvm::interleaved(SNI.Clones);
364 OS << " StackIds: " << llvm::interleaved(SNI.StackIdIndices);
365 return OS;
366}
367
368// Allocation type assigned to an allocation reached by a given context.
369// More can be added, now this is cold, notcold and hot.
370// Values should be powers of two so that they can be ORed, in particular to
371// track allocations that have different behavior with different calling
372// contexts.
374 None = 0,
376 Cold = 2,
377 Hot = 4,
378 All = 7 // This should always be set to the OR of all values.
379};
380
381/// Summary of a single MIB in a memprof metadata on allocations.
382struct MIBInfo {
383 // The allocation type for this profiled context.
385
386 // Represents stack ids in this context, recorded as indices into the
387 // StackIds vector in the summary index, which in turn holds the full 64-bit
388 // stack ids. This reduces memory as there are in practice far fewer unique
389 // stack ids than stack id references.
391
394};
395
396inline raw_ostream &operator<<(raw_ostream &OS, const MIBInfo &MIB) {
397 OS << "AllocType " << (unsigned)MIB.AllocType;
398 OS << " StackIds: " << llvm::interleaved(MIB.StackIdIndices);
399 return OS;
400}
401
402/// Summary of memprof metadata on allocations.
403struct AllocInfo {
404 // Used to record whole program analysis cloning decisions.
405 // The ThinLTO backend will need to create as many clones as there are entries
406 // in the vector (it is expected and should be confirmed that all such
407 // summaries in the same FunctionSummary have the same number of entries).
408 // Each index records version info for the corresponding clone of this
409 // function. The value is the allocation type of the corresponding allocation.
410 // Index 0 is the original version. Before cloning, index 0 may have more than
411 // one allocation type.
413
414 // Vector of MIBs in this memprof metadata.
415 std::vector<MIBInfo> MIBs;
416
417 // If requested, keep track of full stack contexts and total profiled sizes
418 // for each MIB. This will be a vector of the same length and order as the
419 // MIBs vector, if non-empty. Note that each MIB in the summary can have
420 // multiple of these as we trim the contexts when possible during matching.
421 // For hinted size reporting we, however, want the original pre-trimmed full
422 // stack context id for better correlation with the profile.
423 std::vector<std::vector<ContextTotalSize>> ContextSizeInfos;
424
425 AllocInfo(std::vector<MIBInfo> MIBs) : MIBs(std::move(MIBs)) {
426 Versions.push_back(0);
427 }
430};
431
433 OS << "Versions: "
435
436 OS << " MIB:\n";
437 for (auto &M : AE.MIBs)
438 OS << "\t\t" << M << "\n";
439 if (!AE.ContextSizeInfos.empty()) {
440 OS << "\tContextSizeInfo per MIB:\n";
441 for (auto Infos : AE.ContextSizeInfos) {
442 OS << "\t\t";
443 ListSeparator InfoLS;
444 for (auto [FullStackId, TotalSize] : Infos)
445 OS << InfoLS << "{ " << FullStackId << ", " << TotalSize << " }";
446 OS << "\n";
447 }
448 }
449 return OS;
450}
451
452/// Function and variable summary information to aid decisions and
453/// implementation of importing.
455public:
456 /// Sububclass discriminator (for dyn_cast<> et al.)
458
459 enum ImportKind : unsigned {
460 // The global value definition corresponding to the summary should be
461 // imported from source module
463
464 // When its definition doesn't exist in the destination module and not
465 // imported (e.g., function is too large to be inlined), the global value
466 // declaration corresponding to the summary should be imported, or the
467 // attributes from summary should be annotated on the function declaration.
469 };
470
471 /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
472 struct GVFlags {
473 /// The linkage type of the associated global value.
474 ///
475 /// One use is to flag values that have local linkage types and need to
476 /// have module identifier appended before placing into the combined
477 /// index, to disambiguate from other values with the same name.
478 /// In the future this will be used to update and optimize linkage
479 /// types based on global summary-based analysis.
480 unsigned Linkage : 4;
481
482 /// Indicates the visibility.
483 unsigned Visibility : 2;
484
485 /// Indicate if the global value cannot be imported (e.g. it cannot
486 /// be renamed or references something that can't be renamed).
488
489 /// In per-module summary, indicate that the global value must be considered
490 /// a live root for index-based liveness analysis. Used for special LLVM
491 /// values such as llvm.global_ctors that the linker does not know about.
492 ///
493 /// In combined summary, indicate that the global value is live.
494 unsigned Live : 1;
495
496 /// Indicates that the linker resolved the symbol to a definition from
497 /// within the same linkage unit.
498 unsigned DSOLocal : 1;
499
500 /// In the per-module summary, indicates that the global value is
501 /// linkonce_odr and global unnamed addr (so eligible for auto-hiding
502 /// via hidden visibility). In the combined summary, indicates that the
503 /// prevailing linkonce_odr copy can be auto-hidden via hidden visibility
504 /// when it is upgraded to weak_odr in the backend. This is legal when
505 /// all copies are eligible for auto-hiding (i.e. all copies were
506 /// linkonce_odr global unnamed addr. If any copy is not (e.g. it was
507 /// originally weak_odr, we cannot auto-hide the prevailing copy as it
508 /// means the symbol was externally visible.
509 unsigned CanAutoHide : 1;
510
511 /// This field is written by the ThinLTO indexing step to postlink combined
512 /// summary. The value is interpreted as 'ImportKind' enum defined above.
513 unsigned ImportType : 1;
514
515 /// This symbol was promoted. Thinlink stages need to be aware of this
516 /// transition
517 unsigned Promoted : 1;
518
519 /// This field is written by the ThinLTO prelink stage to decide whether
520 /// a particular static global value should be promoted or not.
522
523 /// Convenience Constructors
534 };
535
536private:
537 /// Kind of summary for use in dyn_cast<> et al.
538 SummaryKind Kind;
539
540 GVFlags Flags;
541
542 /// This is the hash of the name of the symbol in the original file. It is
543 /// identical to the GUID for global symbols, but differs for local since the
544 /// GUID includes the module level id in the hash.
545 GlobalValue::GUID OriginalName = 0;
546
547 /// Path of module IR containing value's definition, used to locate
548 /// module during importing.
549 ///
550 /// This is only used during parsing of the combined index, or when
551 /// parsing the per-module index for creation of the combined summary index,
552 /// not during writing of the per-module index which doesn't contain a
553 /// module path string table.
554 StringRef ModulePath;
555
556 /// List of values referenced by this global value's definition
557 /// (either by the initializer of a global variable, or referenced
558 /// from within a function). This does not include functions called, which
559 /// are listed in the derived FunctionSummary object.
560 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
561 /// smaller memory footprint.
562 SmallVector<ValueInfo, 0> RefEdgeList;
563
564protected:
567 : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {
568 assert((K != AliasKind || Refs.empty()) &&
569 "Expect no references for AliasSummary");
570 }
571
572public:
573 virtual ~GlobalValueSummary() = default;
574
575 /// Returns the hash of the original name, it is identical to the GUID for
576 /// externally visible symbols, but not for local ones.
577 GlobalValue::GUID getOriginalName() const { return OriginalName; }
578
579 /// Initialize the original name hash in this summary.
580 void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
581
582 /// Which kind of summary subclass this is.
583 SummaryKind getSummaryKind() const { return Kind; }
584
585 /// Set the path to the module containing this function, for use in
586 /// the combined index.
587 void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
588
589 /// Get the path to the module containing this function.
590 StringRef modulePath() const { return ModulePath; }
591
592 /// Get the flags for this GlobalValue (see \p struct GVFlags).
593 GVFlags flags() const { return Flags; }
594
595 /// Return linkage type recorded for this global value.
597 return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
598 }
599
600 bool wasPromoted() const { return Flags.Promoted; }
601
602 void promote() {
604 "unexpected (re-)promotion of non-local symbol");
605 assert(!Flags.Promoted);
606 Flags.Promoted = true;
608 }
609
610 /// Sets the linkage to the value determined by global summary-based
611 /// optimization. Will be applied in the ThinLTO backends.
614 assert(!GlobalValue::isExternalLinkage(Linkage) && "use `promote` instead");
615 Flags.Linkage = Linkage;
616 }
617
621
622 /// Return true if this global value can't be imported.
623 bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
624
625 bool isLive() const { return Flags.Live; }
626
627 void setLive(bool Live) { Flags.Live = Live; }
628
629 void setDSOLocal(bool Local) { Flags.DSOLocal = Local; }
630
631 bool isDSOLocal() const { return Flags.DSOLocal; }
632
633 void setCanAutoHide(bool CanAutoHide) { Flags.CanAutoHide = CanAutoHide; }
634
635 bool canAutoHide() const { return Flags.CanAutoHide; }
636
637 bool shouldImportAsDecl() const {
638 return Flags.ImportType == GlobalValueSummary::ImportKind::Declaration;
639 }
640
641 void setImportKind(ImportKind IK) { Flags.ImportType = IK; }
642
643 void setNoRenameOnPromotion(bool NoRenameOnPromotion) {
644 Flags.NoRenameOnPromotion = NoRenameOnPromotion;
645 }
646
647 bool noRenameOnPromotion() const { return Flags.NoRenameOnPromotion; }
648
650 return static_cast<ImportKind>(Flags.ImportType);
651 }
652
654 return (GlobalValue::VisibilityTypes)Flags.Visibility;
655 }
657 Flags.Visibility = (unsigned)Vis;
658 }
659
660 /// Flag that this global value cannot be imported.
661 void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
662
663 /// Return the list of values referenced by this global value definition.
664 ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
665
666 /// If this is an alias summary, returns the summary of the aliased object (a
667 /// global variable or function), otherwise returns itself.
669 const GlobalValueSummary *getBaseObject() const;
670
671 friend class ModuleSummaryIndex;
672};
673
675 : U(HaveGVs), HasLocal(false) {}
676
678 std::unique_ptr<GlobalValueSummary> Summary) {
679 if (GlobalValue::isLocalLinkage(Summary->linkage()))
680 HasLocal = true;
681 return SummaryList.push_back(std::move(Summary));
682}
683
685 assert(HasLocal ==
686 llvm::any_of(SummaryList,
687 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
688 return GlobalValue::isLocalLinkage(Summary->linkage());
689 }));
690}
691
692/// Alias summary information.
694 ValueInfo AliaseeValueInfo;
695
696 /// This is the Aliasee in the same module as alias (could get from VI, trades
697 /// memory for time). Note that this pointer may be null (and the value info
698 /// empty) when we have a distributed index where the alias is being imported
699 /// (as a copy of the aliasee), but the aliasee is not.
700 GlobalValueSummary *AliaseeSummary = nullptr;
701
702public:
705
706 /// Check if this is an alias summary.
707 static bool classof(const GlobalValueSummary *GVS) {
708 return GVS->getSummaryKind() == AliasKind;
709 }
710
711 void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee) {
712 AliaseeValueInfo = AliaseeVI;
713 AliaseeSummary = Aliasee;
714 }
715
716 bool hasAliasee() const {
717 assert(!!AliaseeSummary == (AliaseeValueInfo &&
718 !AliaseeValueInfo.getSummaryList().empty()) &&
719 "Expect to have both aliasee summary and summary list or neither");
720 return !!AliaseeSummary;
721 }
722
724 assert(AliaseeSummary && "Unexpected missing aliasee summary");
725 return *AliaseeSummary;
726 }
727
729 return const_cast<GlobalValueSummary &>(
730 static_cast<const AliasSummary *>(this)->getAliasee());
731 }
733 assert(AliaseeValueInfo && "Unexpected missing aliasee");
734 return AliaseeValueInfo;
735 }
737 assert(AliaseeValueInfo && "Unexpected missing aliasee");
738 return AliaseeValueInfo.getGUID();
739 }
740};
741
743 if (auto *AS = dyn_cast<AliasSummary>(this))
744 return &AS->getAliasee();
745 return this;
746}
747
749 if (auto *AS = dyn_cast<AliasSummary>(this))
750 return &AS->getAliasee();
751 return this;
752}
753
754/// Function summary information to aid decisions and implementation of
755/// importing.
757public:
758 /// <CalleeValueInfo, CalleeInfo> call edge pair.
759 using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
760
761 /// Types for -force-summary-edges-cold debugging option.
767
768 /// An "identifier" for a virtual function. This contains the type identifier
769 /// represented as a GUID and the offset from the address point to the virtual
770 /// function pointer, where "address point" is as defined in the Itanium ABI:
771 /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
776
777 /// A specification for a virtual function call with all constant integer
778 /// arguments. This is used to perform virtual constant propagation on the
779 /// summary.
780 struct ConstVCall {
782 std::vector<uint64_t> Args;
783 };
784
785 /// All type identifier related information. Because these fields are
786 /// relatively uncommon we only allocate space for them if necessary.
787 struct TypeIdInfo {
788 /// List of type identifiers used by this function in llvm.type.test
789 /// intrinsics referenced by something other than an llvm.assume intrinsic,
790 /// represented as GUIDs.
791 std::vector<GlobalValue::GUID> TypeTests;
792
793 /// List of virtual calls made by this function using (respectively)
794 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
795 /// not have all constant integer arguments.
797
798 /// List of virtual calls made by this function using (respectively)
799 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
800 /// all constant integer arguments.
801 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
803 };
804
805 /// Flags specific to function summaries.
806 struct FFlags {
807 // Function attribute flags. Used to track if a function accesses memory,
808 // recurses or aliases.
809 unsigned ReadNone : 1;
810 unsigned ReadOnly : 1;
811 unsigned NoRecurse : 1;
812 unsigned ReturnDoesNotAlias : 1;
813
814 // Indicate if the global value cannot be inlined.
815 unsigned NoInline : 1;
816 // Indicate if function should be always inlined.
817 unsigned AlwaysInline : 1;
818 // Indicate if function never raises an exception. Can be modified during
819 // thinlink function attribute propagation
820 unsigned NoUnwind : 1;
821 // Indicate if function contains instructions that mayThrow
822 unsigned MayThrow : 1;
823
824 // If there are calls to unknown targets (e.g. indirect)
825 unsigned HasUnknownCall : 1;
826
827 // Indicate if a function must be an unreachable function.
828 //
829 // This bit is sufficient but not necessary;
830 // if this bit is on, the function must be regarded as unreachable;
831 // if this bit is off, the function might be reachable or unreachable.
832 unsigned MustBeUnreachable : 1;
833
835 this->ReadNone &= RHS.ReadNone;
836 this->ReadOnly &= RHS.ReadOnly;
837 this->NoRecurse &= RHS.NoRecurse;
838 this->ReturnDoesNotAlias &= RHS.ReturnDoesNotAlias;
839 this->NoInline &= RHS.NoInline;
840 this->AlwaysInline &= RHS.AlwaysInline;
841 this->NoUnwind &= RHS.NoUnwind;
842 this->MayThrow &= RHS.MayThrow;
843 this->HasUnknownCall &= RHS.HasUnknownCall;
844 this->MustBeUnreachable &= RHS.MustBeUnreachable;
845 return *this;
846 }
847
848 bool anyFlagSet() {
849 return this->ReadNone | this->ReadOnly | this->NoRecurse |
850 this->ReturnDoesNotAlias | this->NoInline | this->AlwaysInline |
851 this->NoUnwind | this->MayThrow | this->HasUnknownCall |
852 this->MustBeUnreachable;
853 }
854
855 operator std::string() {
856 std::string Output;
857 raw_string_ostream OS(Output);
858 OS << "funcFlags: (";
859 OS << "readNone: " << this->ReadNone;
860 OS << ", readOnly: " << this->ReadOnly;
861 OS << ", noRecurse: " << this->NoRecurse;
862 OS << ", returnDoesNotAlias: " << this->ReturnDoesNotAlias;
863 OS << ", noInline: " << this->NoInline;
864 OS << ", alwaysInline: " << this->AlwaysInline;
865 OS << ", noUnwind: " << this->NoUnwind;
866 OS << ", mayThrow: " << this->MayThrow;
867 OS << ", hasUnknownCall: " << this->HasUnknownCall;
868 OS << ", mustBeUnreachable: " << this->MustBeUnreachable;
869 OS << ")";
870 return Output;
871 }
872 };
873
874 /// Describes the uses of a parameter by the function.
875 struct ParamAccess {
876 static constexpr uint32_t RangeWidth = 64;
877
878 /// Describes the use of a value in a call instruction, specifying the
879 /// call's target, the value's parameter number, and the possible range of
880 /// offsets from the beginning of the value that are passed.
890
892 /// The range contains byte offsets from the parameter pointer which
893 /// accessed by the function. In the per-module summary, it only includes
894 /// accesses made by the function instructions. In the combined summary, it
895 /// also includes accesses by nested function calls.
896 ConstantRange Use{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
897 /// In the per-module summary, it summarizes the byte offset applied to each
898 /// pointer parameter before passing to each corresponding callee.
899 /// In the combined summary, it's empty and information is propagated by
900 /// inter-procedural analysis and applied to the Use field.
901 std::vector<Call> Calls;
902
903 ParamAccess() = default;
906 };
907
908 /// Create an empty FunctionSummary (with specified call edges).
909 /// Used to represent external nodes and the dummy root node.
910 static FunctionSummary
912 return FunctionSummary(
916 /*NotEligibleToImport=*/true, /*Live=*/true, /*IsLocal=*/false,
917 /*CanAutoHide=*/false, GlobalValueSummary::ImportKind::Definition,
918 /*NoRenameOnPromotion=*/false),
920 std::move(Edges), std::vector<GlobalValue::GUID>(),
921 std::vector<FunctionSummary::VFuncId>(),
922 std::vector<FunctionSummary::VFuncId>(),
923 std::vector<FunctionSummary::ConstVCall>(),
924 std::vector<FunctionSummary::ConstVCall>(),
925 std::vector<FunctionSummary::ParamAccess>(),
926 std::vector<CallsiteInfo>(), std::vector<AllocInfo>());
927 }
928
929 /// A dummy node to reference external functions that aren't in the index
931
932private:
933 /// Number of instructions (ignoring debug instructions, e.g.) computed
934 /// during the initial compile step when the summary index is first built.
935 unsigned InstCount;
936
937 /// Function summary specific flags.
938 FFlags FunFlags;
939
940 /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
941 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
942 /// smaller memory footprint.
943 SmallVector<EdgeTy, 0> CallGraphEdgeList;
944
945 std::unique_ptr<TypeIdInfo> TIdInfo;
946
947 /// Uses for every parameter to this function.
948 using ParamAccessesTy = std::vector<ParamAccess>;
949 std::unique_ptr<ParamAccessesTy> ParamAccesses;
950
951 /// Optional list of memprof callsite metadata summaries. The correspondence
952 /// between the callsite summary and the callsites in the function is implied
953 /// by the order in the vector (and can be validated by comparing the stack
954 /// ids in the CallsiteInfo to those in the instruction callsite metadata).
955 /// As a memory savings optimization, we only create these for the prevailing
956 /// copy of a symbol when creating the combined index during LTO.
957 using CallsitesTy = std::vector<CallsiteInfo>;
958 std::unique_ptr<CallsitesTy> Callsites;
959
960 /// Optional list of allocation memprof metadata summaries. The correspondence
961 /// between the alloc memprof summary and the allocation callsites in the
962 /// function is implied by the order in the vector (and can be validated by
963 /// comparing the stack ids in the AllocInfo to those in the instruction
964 /// memprof metadata).
965 /// As a memory savings optimization, we only create these for the prevailing
966 /// copy of a symbol when creating the combined index during LTO.
967 using AllocsTy = std::vector<AllocInfo>;
968 std::unique_ptr<AllocsTy> Allocs;
969
970public:
971 FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
973 SmallVectorImpl<EdgeTy> &&CGEdges,
974 std::vector<GlobalValue::GUID> TypeTests,
975 std::vector<VFuncId> TypeTestAssumeVCalls,
976 std::vector<VFuncId> TypeCheckedLoadVCalls,
977 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
978 std::vector<ConstVCall> TypeCheckedLoadConstVCalls,
979 std::vector<ParamAccess> Params, CallsitesTy CallsiteList,
980 AllocsTy AllocList)
981 : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
982 InstCount(NumInsts), FunFlags(FunFlags),
983 CallGraphEdgeList(std::move(CGEdges)) {
984 if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
985 !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
986 !TypeCheckedLoadConstVCalls.empty())
987 TIdInfo = std::make_unique<TypeIdInfo>(
988 TypeIdInfo{std::move(TypeTests), std::move(TypeTestAssumeVCalls),
989 std::move(TypeCheckedLoadVCalls),
990 std::move(TypeTestAssumeConstVCalls),
991 std::move(TypeCheckedLoadConstVCalls)});
992 if (!Params.empty())
993 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(Params));
994 if (!CallsiteList.empty())
995 Callsites = std::make_unique<CallsitesTy>(std::move(CallsiteList));
996 if (!AllocList.empty())
997 Allocs = std::make_unique<AllocsTy>(std::move(AllocList));
998 }
999 // Gets the number of readonly and writeonly refs in RefEdgeList
1000 LLVM_ABI std::pair<unsigned, unsigned> specialRefCounts() const;
1001
1002 /// Check if this is a function summary.
1003 static bool classof(const GlobalValueSummary *GVS) {
1004 return GVS->getSummaryKind() == FunctionKind;
1005 }
1006
1007 /// Get function summary flags.
1008 FFlags fflags() const { return FunFlags; }
1009
1010 void setNoRecurse() { FunFlags.NoRecurse = true; }
1011
1012 void setNoUnwind() { FunFlags.NoUnwind = true; }
1013
1014 /// Get the instruction count recorded for this function.
1015 unsigned instCount() const { return InstCount; }
1016
1017 /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
1018 ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
1019
1020 SmallVector<EdgeTy, 0> &mutableCalls() { return CallGraphEdgeList; }
1021
1022 void addCall(EdgeTy E) { CallGraphEdgeList.push_back(E); }
1023
1024 /// Returns the list of type identifiers used by this function in
1025 /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
1026 /// represented as GUIDs.
1028 if (TIdInfo)
1029 return TIdInfo->TypeTests;
1030 return {};
1031 }
1032
1033 /// Returns the list of virtual calls made by this function using
1034 /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
1035 /// integer arguments.
1037 if (TIdInfo)
1038 return TIdInfo->TypeTestAssumeVCalls;
1039 return {};
1040 }
1041
1042 /// Returns the list of virtual calls made by this function using
1043 /// llvm.type.checked.load intrinsics that do not have all constant integer
1044 /// arguments.
1046 if (TIdInfo)
1047 return TIdInfo->TypeCheckedLoadVCalls;
1048 return {};
1049 }
1050
1051 /// Returns the list of virtual calls made by this function using
1052 /// llvm.assume(llvm.type.test) intrinsics with all constant integer
1053 /// arguments.
1055 if (TIdInfo)
1056 return TIdInfo->TypeTestAssumeConstVCalls;
1057 return {};
1058 }
1059
1060 /// Returns the list of virtual calls made by this function using
1061 /// llvm.type.checked.load intrinsics with all constant integer arguments.
1063 if (TIdInfo)
1064 return TIdInfo->TypeCheckedLoadConstVCalls;
1065 return {};
1066 }
1067
1068 /// Returns the list of known uses of pointer parameters.
1070 if (ParamAccesses)
1071 return *ParamAccesses;
1072 return {};
1073 }
1074
1075 /// Sets the list of known uses of pointer parameters.
1076 void setParamAccesses(std::vector<ParamAccess> NewParams) {
1077 if (NewParams.empty())
1078 ParamAccesses.reset();
1079 else if (ParamAccesses)
1080 *ParamAccesses = std::move(NewParams);
1081 else
1082 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(NewParams));
1083 }
1084
1085 /// Add a type test to the summary. This is used by WholeProgramDevirt if we
1086 /// were unable to devirtualize a checked call.
1088 if (!TIdInfo)
1089 TIdInfo = std::make_unique<TypeIdInfo>();
1090 TIdInfo->TypeTests.push_back(Guid);
1091 }
1092
1093 const TypeIdInfo *getTypeIdInfo() const { return TIdInfo.get(); };
1094
1096 if (Callsites)
1097 return *Callsites;
1098 return {};
1099 }
1100
1101 CallsitesTy &mutableCallsites() {
1102 assert(Callsites);
1103 return *Callsites;
1104 }
1105
1106 void addCallsite(CallsiteInfo &&Callsite) {
1107 if (!Callsites)
1108 Callsites = std::make_unique<CallsitesTy>();
1109 Callsites->push_back(std::move(Callsite));
1110 }
1111
1113 if (Allocs)
1114 return *Allocs;
1115 return {};
1116 }
1117
1119 if (!Allocs)
1120 Allocs = std::make_unique<AllocsTy>();
1121 Allocs->push_back(std::move(Alloc));
1122 }
1123
1124 AllocsTy &mutableAllocs() {
1125 assert(Allocs);
1126 return *Allocs;
1127 }
1128
1129 friend struct GraphTraits<ValueInfo>;
1130};
1131
1132template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
1133 static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
1134
1136 return {0, uint64_t(-2)};
1137 }
1138
1140 return L.GUID == R.GUID && L.Offset == R.Offset;
1141 }
1142
1143 static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
1144};
1145
1146template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
1148 return {{0, uint64_t(-1)}, {}};
1149 }
1150
1152 return {{0, uint64_t(-2)}, {}};
1153 }
1154
1157 return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
1158 L.Args == R.Args;
1159 }
1160
1162 return I.VFunc.GUID;
1163 }
1164};
1165
1166/// The ValueInfo and offset for a function within a vtable definition
1167/// initializer array.
1175/// List of functions referenced by a particular vtable definition.
1176using VTableFuncList = std::vector<VirtFuncOffset>;
1177
1178/// Global variable summary information to aid decisions and
1179/// implementation of importing.
1180///
1181/// Global variable summary has two extra flag, telling if it is
1182/// readonly or writeonly. Both readonly and writeonly variables
1183/// can be optimized in the backed: readonly variables can be
1184/// const-folded, while writeonly vars can be completely eliminated
1185/// together with corresponding stores. We let both things happen
1186/// by means of internalizing such variables after ThinLTO import.
1188private:
1189 /// For vtable definitions this holds the list of functions and
1190 /// their corresponding offsets within the initializer array.
1191 std::unique_ptr<VTableFuncList> VTableFuncs;
1192
1193public:
1194 struct GVarFlags {
1195 GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant,
1197 : MaybeReadOnly(ReadOnly), MaybeWriteOnly(WriteOnly),
1199
1200 // If true indicates that this global variable might be accessed
1201 // purely by non-volatile load instructions. This in turn means
1202 // it can be internalized in source and destination modules during
1203 // thin LTO import because it neither modified nor its address
1204 // is taken.
1205 unsigned MaybeReadOnly : 1;
1206 // If true indicates that variable is possibly only written to, so
1207 // its value isn't loaded and its address isn't taken anywhere.
1208 // False, when 'Constant' attribute is set.
1209 unsigned MaybeWriteOnly : 1;
1210 // Indicates that value is a compile-time constant. Global variable
1211 // can be 'Constant' while not being 'ReadOnly' on several occasions:
1212 // - it is volatile, (e.g mapped device address)
1213 // - its address is taken, meaning that unlike 'ReadOnly' vars we can't
1214 // internalize it.
1215 // Constant variables are always imported thus giving compiler an
1216 // opportunity to make some extra optimizations. Readonly constants
1217 // are also internalized.
1218 unsigned Constant : 1;
1219 // Set from metadata on vtable definitions during the module summary
1220 // analysis.
1221 unsigned VCallVisibility : 2;
1223
1228
1229 /// Check if this is a global variable summary.
1230 static bool classof(const GlobalValueSummary *GVS) {
1231 return GVS->getSummaryKind() == GlobalVarKind;
1232 }
1233
1234 GVarFlags varflags() const { return VarFlags; }
1235 void setReadOnly(bool RO) { VarFlags.MaybeReadOnly = RO; }
1236 void setWriteOnly(bool WO) { VarFlags.MaybeWriteOnly = WO; }
1237 bool maybeReadOnly() const { return VarFlags.MaybeReadOnly; }
1238 bool maybeWriteOnly() const { return VarFlags.MaybeWriteOnly; }
1239 bool isConstant() const { return VarFlags.Constant; }
1241 VarFlags.VCallVisibility = Vis;
1242 }
1246
1248 assert(!VTableFuncs);
1249 VTableFuncs = std::make_unique<VTableFuncList>(std::move(Funcs));
1250 }
1251
1253 if (VTableFuncs)
1254 return *VTableFuncs;
1255 return {};
1256 }
1257};
1258
1260 /// Specifies which kind of type check we should emit for this byte array.
1261 /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
1262 /// details on each kind of check; the enumerators are described with
1263 /// reference to that document.
1264 enum Kind {
1265 Unsat, ///< Unsatisfiable type (i.e. no global has this type metadata)
1266 ByteArray, ///< Test a byte array (first example)
1267 Inline, ///< Inlined bit vector ("Short Inline Bit Vectors")
1268 Single, ///< Single element (last example in "Short Inline Bit Vectors")
1269 AllOnes, ///< All-ones bit vector ("Eliminating Bit Vector Checks for
1270 /// All-Ones Bit Vectors")
1271 Unknown, ///< Unknown (analysis not performed, don't lower)
1273
1274 /// Range of size-1 expressed as a bit width. For example, if the size is in
1275 /// range [1,256], this number will be 8. This helps generate the most compact
1276 /// instruction sequences.
1277 unsigned SizeM1BitWidth = 0;
1278
1279 // The following fields are only used if the target does not support the use
1280 // of absolute symbols to store constants. Their meanings are the same as the
1281 // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
1282 // LowerTypeTests.cpp.
1283
1288};
1289
1291 enum Kind {
1292 Indir, ///< Just do a regular virtual call
1293 SingleImpl, ///< Single implementation devirtualization
1294 BranchFunnel, ///< When retpoline mitigation is enabled, use a branch funnel
1295 ///< that is defined in the merged module. Otherwise same as
1296 ///< Indir.
1298
1299 std::string SingleImplName;
1300
1301 struct ByArg {
1302 enum Kind {
1303 Indir, ///< Just do a regular virtual call
1304 UniformRetVal, ///< Uniform return value optimization
1305 UniqueRetVal, ///< Unique return value optimization
1306 VirtualConstProp, ///< Virtual constant propagation
1308
1309 /// Additional information for the resolution:
1310 /// - UniformRetVal: the uniform return value.
1311 /// - UniqueRetVal: the return value associated with the unique vtable (0 or
1312 /// 1).
1314
1315 // The following fields are only used if the target does not support the use
1316 // of absolute symbols to store constants.
1317
1320 };
1321
1322 /// Resolutions for calls with all constant integer arguments (excluding the
1323 /// first argument, "this"), where the key is the argument vector.
1324 std::map<std::vector<uint64_t>, ByArg> ResByArg;
1325};
1326
1329
1330 /// Mapping from byte offset to whole-program devirt resolution for that
1331 /// (typeid, byte offset) pair.
1332 std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
1333};
1334
1337 using IndexIterator =
1339 std::set<std::string, std::less<>>>::const_iterator;
1340 using NestedIterator = std::set<std::string, std::less<>>::const_iterator;
1341
1342public:
1343 // Iterates keys of the DenseMap.
1344 class GUIDIterator : public iterator_adaptor_base<GUIDIterator, IndexIterator,
1345 std::forward_iterator_tag,
1346 GlobalValue::GUID> {
1348
1349 public:
1350 GUIDIterator() = default;
1351 explicit GUIDIterator(IndexIterator I) : base(I) {}
1352
1353 GlobalValue::GUID operator*() const { return this->wrapped()->first; }
1354 };
1355
1356 CfiFunctionIndex() = default;
1357 template <typename It> CfiFunctionIndex(It B, It E) {
1358 for (; B != E; ++B)
1359 emplace(*B);
1360 }
1361
1362 std::vector<StringRef> symbols() const {
1363 std::vector<StringRef> Symbols;
1364 for (auto &[GUID, Syms] : Index) {
1365 (void)GUID;
1366 llvm::append_range(Symbols, Syms);
1367 }
1368 return Symbols;
1369 }
1370
1371 GUIDIterator guid_begin() const { return GUIDIterator(Index.begin()); }
1372 GUIDIterator guid_end() const { return GUIDIterator(Index.end()); }
1376
1378 auto I = Index.find(GUID);
1379 if (I == Index.end())
1380 return make_range(NestedIterator{}, NestedIterator{});
1381 return make_range(I->second.begin(), I->second.end());
1382 }
1383
1384 template <typename... Args> void emplace(Args &&...A) {
1385 StringRef S(std::forward<Args>(A)...);
1388 Index[GUID].emplace(S);
1389 }
1390
1391 size_t count(StringRef S) const {
1394 auto I = Index.find(GUID);
1395 if (I == Index.end())
1396 return 0;
1397 return I->second.count(S);
1398 }
1399
1400 bool empty() const { return Index.empty(); }
1401};
1402
1403/// 160 bits SHA1
1404using ModuleHash = std::array<uint32_t, 5>;
1405
1406/// Type used for iterating through the global value summary map.
1407using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
1408using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
1409
1410/// String table to hold/own module path strings, as well as a hash
1411/// of the module. The StringMap makes a copy of and owns inserted strings.
1413
1414/// Map of global value GUID to its summary, used to identify values defined in
1415/// a particular module, and provide efficient access to their summary.
1417
1418/// Map of a module name to the GUIDs and summaries we will import from that
1419/// module.
1421 std::map<std::string, GVSummaryMapTy, std::less<>>;
1422
1423/// A set of global value summary pointers.
1424using GVSummaryPtrSet = std::unordered_set<GlobalValueSummary *>;
1425
1426/// Map of a type GUID to type id string and summary (multimap used
1427/// in case of GUID conflicts).
1429 std::multimap<GlobalValue::GUID, std::pair<StringRef, TypeIdSummary>>;
1430
1431/// The following data structures summarize type metadata information.
1432/// For type metadata overview see https://llvm.org/docs/TypeMetadata.html.
1433/// Each type metadata includes both the type identifier and the offset of
1434/// the address point of the type (the address held by objects of that type
1435/// which may not be the beginning of the virtual table). Vtable definitions
1436/// are decorated with type metadata for the types they are compatible with.
1437///
1438/// Holds information about vtable definitions decorated with type metadata:
1439/// the vtable definition value and its address point offset in a type
1440/// identifier metadata it is decorated (compatible) with.
1448/// List of vtable definitions decorated by a particular type identifier,
1449/// and their corresponding offsets in that type identifier's metadata.
1450/// Note that each type identifier may be compatible with multiple vtables, due
1451/// to inheritance, which is why this is a vector.
1452using TypeIdCompatibleVtableInfo = std::vector<TypeIdOffsetVtableInfo>;
1453
1454/// Class to hold module path string table and global value map,
1455/// and encapsulate methods for operating on them.
1457private:
1458 /// Map from value name to list of summary instances for values of that
1459 /// name (may be duplicates in the COMDAT case, e.g.).
1460 GlobalValueSummaryMapTy GlobalValueMap;
1461
1462 /// Holds strings for combined index, mapping to the corresponding module ID.
1463 ModulePathStringTableTy ModulePathStringTable;
1464
1465 BumpPtrAllocator TypeIdSaverAlloc;
1466 UniqueStringSaver TypeIdSaver;
1467
1468 /// Mapping from type identifier GUIDs to type identifier and its summary
1469 /// information. Produced by thin link.
1470 TypeIdSummaryMapTy TypeIdMap;
1471
1472 /// Mapping from type identifier to information about vtables decorated
1473 /// with that type identifier's metadata. Produced by per module summary
1474 /// analysis and consumed by thin link. For more information, see description
1475 /// above where TypeIdCompatibleVtableInfo is defined.
1476 std::map<StringRef, TypeIdCompatibleVtableInfo, std::less<>>
1477 TypeIdCompatibleVtableMap;
1478
1479 /// Mapping from original ID to GUID. If original ID can map to multiple
1480 /// GUIDs, it will be mapped to 0.
1482
1483 /// Indicates that summary-based GlobalValue GC has run, and values with
1484 /// GVFlags::Live==false are really dead. Otherwise, all values must be
1485 /// considered live.
1486 bool WithGlobalValueDeadStripping = false;
1487
1488 /// Indicates that summary-based attribute propagation has run and
1489 /// GVarFlags::MaybeReadonly / GVarFlags::MaybeWriteonly are really
1490 /// read/write only.
1491 bool WithAttributePropagation = false;
1492
1493 /// Indicates that summary-based DSOLocal propagation has run and the flag in
1494 /// every summary of a GV is synchronized.
1495 bool WithDSOLocalPropagation = false;
1496
1497 /// Indicates that summary-based internalization and promotion has run.
1498 bool WithInternalizeAndPromote = false;
1499
1500 /// Indicates that we have whole program visibility.
1501 bool WithWholeProgramVisibility = false;
1502
1503 /// Indicates that summary-based synthetic entry count propagation has run
1504 bool HasSyntheticEntryCounts = false;
1505
1506 /// Indicates that we linked with allocator supporting hot/cold new operators.
1507 bool WithSupportsHotColdNew = false;
1508
1509 /// Indicates that distributed backend should skip compilation of the
1510 /// module. Flag is suppose to be set by distributed ThinLTO indexing
1511 /// when it detected that the module is not needed during the final
1512 /// linking. As result distributed backend should just output a minimal
1513 /// valid object file.
1514 bool SkipModuleByDistributedBackend = false;
1515
1516 /// If true then we're performing analysis of IR module, or parsing along with
1517 /// the IR from assembly. The value of 'false' means we're reading summary
1518 /// from BC or YAML source. Affects the type of value stored in NameOrGV
1519 /// union.
1520 bool HaveGVs;
1521
1522 // True if the index was created for a module compiled with -fsplit-lto-unit.
1523 bool EnableSplitLTOUnit;
1524
1525 // True if the index was created for a module compiled with -funified-lto
1526 bool UnifiedLTO;
1527
1528 // True if some of the modules were compiled with -fsplit-lto-unit and
1529 // some were not. Set when the combined index is created during the thin link.
1530 bool PartiallySplitLTOUnits = false;
1531
1532 /// True if some of the FunctionSummary contains a ParamAccess.
1533 bool HasParamAccess = false;
1534
1535 CfiFunctionIndex CfiFunctionDefs;
1536 CfiFunctionIndex CfiFunctionDecls;
1537
1538 // Used in cases where we want to record the name of a global, but
1539 // don't have the string owned elsewhere (e.g. the Strtab on a module).
1540 BumpPtrAllocator Alloc;
1541 StringSaver Saver;
1542
1543 // The total number of basic blocks in the module in the per-module summary or
1544 // the total number of basic blocks in the LTO unit in the combined index.
1545 // FIXME: Putting this in the distributed ThinLTO index files breaks LTO
1546 // backend caching on any BB change to any linked file. It is currently not
1547 // used except in the case of a SamplePGO partial profile, and should be
1548 // reevaluated/redesigned to allow more effective incremental builds in that
1549 // case.
1550 uint64_t BlockCount = 0;
1551
1552 // List of unique stack ids (hashes). We use a 4B index of the id in the
1553 // stack id lists on the alloc and callsite summaries for memory savings,
1554 // since the number of unique ids is in practice much smaller than the
1555 // number of stack id references in the summaries.
1556 std::vector<uint64_t> StackIds;
1557
1558 // Temporary map while building StackIds list. Clear when index is completely
1559 // built via releaseTemporaryMemory.
1560 DenseMap<uint64_t, unsigned> StackIdToIndex;
1561
1562 // YAML I/O support.
1564
1565 GlobalValueSummaryMapTy::value_type *
1566 getOrInsertValuePtr(GlobalValue::GUID GUID) {
1567 return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo(HaveGVs))
1568 .first;
1569 }
1570
1571public:
1572 // See HaveGVs variable comment.
1573 ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit = false,
1574 bool UnifiedLTO = false)
1575 : TypeIdSaver(TypeIdSaverAlloc), HaveGVs(HaveGVs),
1576 EnableSplitLTOUnit(EnableSplitLTOUnit), UnifiedLTO(UnifiedLTO),
1577 Saver(Alloc) {}
1578
1579 // Current version for the module summary in bitcode files.
1580 // The BitcodeSummaryVersion should be bumped whenever we introduce changes
1581 // in the way some record are interpreted, like flags for instance.
1582 // Note that incrementing this may require changes in both BitcodeReader.cpp
1583 // and BitcodeWriter.cpp.
1584 static constexpr uint64_t BitcodeSummaryVersion = 13;
1585
1586 // Regular LTO module name for ASM writer
1587 static constexpr const char *getRegularLTOModuleName() {
1588 return "[Regular LTO]";
1589 }
1590
1591 bool haveGVs() const { return HaveGVs; }
1592
1593 LLVM_ABI uint64_t getFlags() const;
1594 LLVM_ABI void setFlags(uint64_t Flags);
1595
1596 uint64_t getBlockCount() const { return BlockCount; }
1597 void addBlockCount(uint64_t C) { BlockCount += C; }
1598 void setBlockCount(uint64_t C) { BlockCount = C; }
1599
1600 gvsummary_iterator begin() { return GlobalValueMap.begin(); }
1601 const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
1602 gvsummary_iterator end() { return GlobalValueMap.end(); }
1603 const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
1604 size_t size() const { return GlobalValueMap.size(); }
1605
1606 const std::vector<uint64_t> &stackIds() const { return StackIds; }
1607
1608 unsigned addOrGetStackIdIndex(uint64_t StackId) {
1609 auto Inserted = StackIdToIndex.insert({StackId, StackIds.size()});
1610 if (Inserted.second)
1611 StackIds.push_back(StackId);
1612 return Inserted.first->second;
1613 }
1614
1615 uint64_t getStackIdAtIndex(unsigned Index) const {
1616 assert(StackIds.size() > Index);
1617 return StackIds[Index];
1618 }
1619
1620 // Facility to release memory from data structures only needed during index
1621 // construction (including while building combined index). Currently this only
1622 // releases the temporary map used while constructing a correspondence between
1623 // stack ids and their index in the StackIds vector. Mostly impactful when
1624 // building a large combined index.
1626 assert(StackIdToIndex.size() == StackIds.size());
1627 StackIdToIndex.clear();
1628 StackIds.shrink_to_fit();
1629 }
1630
1631 /// Convenience function for doing a DFS on a ValueInfo. Marks the function in
1632 /// the FunctionHasParent map.
1634 std::map<ValueInfo, bool> &FunctionHasParent) {
1635 if (!V.getSummaryList().size())
1636 return; // skip external functions that don't have summaries
1637
1638 // Mark discovered if we haven't yet
1639 auto S = FunctionHasParent.emplace(V, false);
1640
1641 // Stop if we've already discovered this node
1642 if (!S.second)
1643 return;
1644
1646 dyn_cast<FunctionSummary>(V.getSummaryList().front().get());
1647 assert(F != nullptr && "Expected FunctionSummary node");
1648
1649 for (const auto &C : F->calls()) {
1650 // Insert node if necessary
1651 auto S = FunctionHasParent.emplace(C.first, true);
1652
1653 // Skip nodes that we're sure have parents
1654 if (!S.second && S.first->second)
1655 continue;
1656
1657 if (S.second)
1658 discoverNodes(C.first, FunctionHasParent);
1659 else
1660 S.first->second = true;
1661 }
1662 }
1663
1664 // Calculate the callgraph root
1666 // Functions that have a parent will be marked in FunctionHasParent pair.
1667 // Once we've marked all functions, the functions in the map that are false
1668 // have no parent (so they're the roots)
1669 std::map<ValueInfo, bool> FunctionHasParent;
1670
1671 for (auto &S : *this) {
1672 // Skip external functions
1673 if (!S.second.getSummaryList().size() ||
1674 !isa<FunctionSummary>(S.second.getSummaryList().front().get()))
1675 continue;
1676 discoverNodes(ValueInfo(HaveGVs, &S), FunctionHasParent);
1677 }
1678
1680 // create edges to all roots in the Index
1681 for (auto &P : FunctionHasParent) {
1682 if (P.second)
1683 continue; // skip over non-root nodes
1684 Edges.push_back(std::make_pair(P.first, CalleeInfo{}));
1685 }
1686 return FunctionSummary::makeDummyFunctionSummary(std::move(Edges));
1687 }
1688
1690 return WithGlobalValueDeadStripping;
1691 }
1693 WithGlobalValueDeadStripping = true;
1694 }
1695
1696 bool withAttributePropagation() const { return WithAttributePropagation; }
1698 WithAttributePropagation = true;
1699 }
1700
1701 bool withDSOLocalPropagation() const { return WithDSOLocalPropagation; }
1702 void setWithDSOLocalPropagation() { WithDSOLocalPropagation = true; }
1703
1704 bool withInternalizeAndPromote() const { return WithInternalizeAndPromote; }
1705 void setWithInternalizeAndPromote() { WithInternalizeAndPromote = true; }
1706
1707 bool withWholeProgramVisibility() const { return WithWholeProgramVisibility; }
1708 void setWithWholeProgramVisibility() { WithWholeProgramVisibility = true; }
1709
1710 bool isReadOnly(const GlobalVarSummary *GVS) const {
1711 return WithAttributePropagation && GVS->maybeReadOnly();
1712 }
1713 bool isWriteOnly(const GlobalVarSummary *GVS) const {
1714 return WithAttributePropagation && GVS->maybeWriteOnly();
1715 }
1716
1717 bool withSupportsHotColdNew() const { return WithSupportsHotColdNew; }
1718 void setWithSupportsHotColdNew() { WithSupportsHotColdNew = true; }
1719
1721 return SkipModuleByDistributedBackend;
1722 }
1724 SkipModuleByDistributedBackend = true;
1725 }
1726
1727 bool enableSplitLTOUnit() const { return EnableSplitLTOUnit; }
1728 void setEnableSplitLTOUnit() { EnableSplitLTOUnit = true; }
1729
1730 bool hasUnifiedLTO() const { return UnifiedLTO; }
1731 void setUnifiedLTO() { UnifiedLTO = true; }
1732
1733 bool partiallySplitLTOUnits() const { return PartiallySplitLTOUnits; }
1734 void setPartiallySplitLTOUnits() { PartiallySplitLTOUnits = true; }
1735
1736 bool hasParamAccess() const { return HasParamAccess; }
1737
1738 bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
1739 return !WithGlobalValueDeadStripping || GVS->isLive();
1740 }
1741 LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const;
1742
1743 /// Return a ValueInfo for the index value_type (convenient when iterating
1744 /// index).
1745 ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const {
1746 return ValueInfo(HaveGVs, &R);
1747 }
1748
1749 /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
1751 auto I = GlobalValueMap.find(GUID);
1752 return ValueInfo(HaveGVs, I == GlobalValueMap.end() ? nullptr : &*I);
1753 }
1754
1755 /// Return a ValueInfo for \p GUID.
1757 return ValueInfo(HaveGVs, getOrInsertValuePtr(GUID));
1758 }
1759
1760 // Save a string in the Index. Use before passing Name to
1761 // getOrInsertValueInfo when the string isn't owned elsewhere (e.g. on the
1762 // module's Strtab).
1763 StringRef saveString(StringRef String) { return Saver.save(String); }
1764
1765 /// Return a ValueInfo for \p GUID setting value \p Name.
1767 assert(!HaveGVs);
1768 auto VP = getOrInsertValuePtr(GUID);
1769 VP->second.U.Name = Name;
1770 return ValueInfo(HaveGVs, VP);
1771 }
1772
1773 /// Return a ValueInfo for \p GV with GUID \p GUID and mark it as belonging to
1774 /// GV.
1776 GlobalValue::GUID GUID) {
1777 assert(HaveGVs);
1778 auto VP = getOrInsertValuePtr(GUID);
1779 VP->second.U.GV = GV;
1780 return ValueInfo(HaveGVs, VP);
1781 }
1782
1783 /// Return a ValueInfo for \p GV and mark it as belonging to GV.
1785 return getOrInsertValueInfo(GV, GV->getGUID());
1786 }
1787
1788 /// Return the GUID for \p OriginalId in the OidGuidMap.
1790 const auto I = OidGuidMap.find(OriginalID);
1791 return I == OidGuidMap.end() ? 0 : I->second;
1792 }
1793
1794 CfiFunctionIndex &cfiFunctionDefs() { return CfiFunctionDefs; }
1795 const CfiFunctionIndex &cfiFunctionDefs() const { return CfiFunctionDefs; }
1796
1797 CfiFunctionIndex &cfiFunctionDecls() { return CfiFunctionDecls; }
1798 const CfiFunctionIndex &cfiFunctionDecls() const { return CfiFunctionDecls; }
1799
1800 /// Add a global value summary for a value.
1802 std::unique_ptr<GlobalValueSummary> Summary) {
1803 addGlobalValueSummary(getOrInsertValueInfo(&GV), std::move(Summary));
1804 }
1805
1806 /// Add a global value summary for a value of the given name.
1808 std::unique_ptr<GlobalValueSummary> Summary) {
1812 std::move(Summary));
1813 }
1814
1815 /// Add a global value summary for the given ValueInfo.
1817 std::unique_ptr<GlobalValueSummary> Summary) {
1818 if (const FunctionSummary *FS = dyn_cast<FunctionSummary>(Summary.get()))
1819 HasParamAccess |= !FS->paramAccesses().empty();
1820 addOriginalName(VI.getGUID(), Summary->getOriginalName());
1821 // Here we have a notionally const VI, but the value it points to is owned
1822 // by the non-const *this.
1823 const_cast<GlobalValueSummaryMapTy::value_type *>(VI.getRef())
1824 ->second.addSummary(std::move(Summary));
1825 }
1826
1827 /// Add an original name for the value of the given GUID.
1829 GlobalValue::GUID OrigGUID) {
1830 if (OrigGUID == 0 || ValueGUID == OrigGUID)
1831 return;
1832 auto [It, Inserted] = OidGuidMap.try_emplace(OrigGUID, ValueGUID);
1833 if (!Inserted && It->second != ValueGUID)
1834 It->second = 0;
1835 }
1836
1837 /// Find the summary for ValueInfo \p VI in module \p ModuleId, or nullptr if
1838 /// not found.
1840 auto SummaryList = VI.getSummaryList();
1841 auto Summary =
1842 llvm::find_if(SummaryList,
1843 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
1844 return Summary->modulePath() == ModuleId;
1845 });
1846 if (Summary == SummaryList.end())
1847 return nullptr;
1848 return Summary->get();
1849 }
1850
1851 /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
1852 /// not found.
1854 StringRef ModuleId) const {
1855 auto CalleeInfo = getValueInfo(ValueGUID);
1856 if (!CalleeInfo)
1857 return nullptr; // This function does not have a summary
1858 return findSummaryInModule(CalleeInfo, ModuleId);
1859 }
1860
1861 /// Returns the first GlobalValueSummary for \p GV, asserting that there
1862 /// is only one if \p PerModuleIndex.
1864 bool PerModuleIndex = true) const {
1865 assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
1866 return getGlobalValueSummary(GV.getGUID(), PerModuleIndex);
1867 }
1868
1869 /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
1870 /// there
1871 /// is only one if \p PerModuleIndex.
1874 bool PerModuleIndex = true) const;
1875
1876 /// Table of modules, containing module hash and id.
1878 return ModulePathStringTable;
1879 }
1880
1881 /// Table of modules, containing hash and id.
1882 StringMap<ModuleHash> &modulePaths() { return ModulePathStringTable; }
1883
1884 /// Get the module SHA1 hash recorded for the given module path.
1885 const ModuleHash &getModuleHash(const StringRef ModPath) const {
1886 auto It = ModulePathStringTable.find(ModPath);
1887 assert(It != ModulePathStringTable.end() && "Module not registered");
1888 return It->second;
1889 }
1890
1891 /// Convenience method for creating a promoted global name
1892 /// for the given value name of a local, and its original module's ID.
1893 static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
1894 std::string Suffix = utostr((uint64_t(ModHash[0]) << 32) |
1895 ModHash[1]); // Take the first 64 bits
1896 return getGlobalNameForLocal(Name, Suffix);
1897 }
1898
1899 static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix) {
1900 SmallString<256> NewName(Name);
1901 NewName += ".llvm.";
1902 NewName += Suffix;
1903 return std::string(NewName);
1904 }
1905
1906 /// Helper to obtain the unpromoted name for a global value (or the original
1907 /// name if not promoted). Split off the rightmost ".llvm.${hash}" suffix,
1908 /// because it is possible in certain clients (not clang at the moment) for
1909 /// two rounds of ThinLTO optimization and therefore promotion to occur.
1911 std::pair<StringRef, StringRef> Pair = Name.rsplit(".llvm.");
1912 return Pair.first;
1913 }
1914
1916
1917 /// Add a new module with the given \p Hash, mapped to the given \p
1918 /// ModID, and return a reference to the module.
1920 return &*ModulePathStringTable.insert({ModPath, Hash}).first;
1921 }
1922
1923 /// Return module entry for module with the given \p ModPath.
1925 auto It = ModulePathStringTable.find(ModPath);
1926 assert(It != ModulePathStringTable.end() && "Module not registered");
1927 return &*It;
1928 }
1929
1930 /// Return module entry for module with the given \p ModPath.
1931 const ModuleInfo *getModule(StringRef ModPath) const {
1932 auto It = ModulePathStringTable.find(ModPath);
1933 assert(It != ModulePathStringTable.end() && "Module not registered");
1934 return &*It;
1935 }
1936
1937 /// Check if the given Module has any functions available for exporting
1938 /// in the index. We consider any module present in the ModulePathStringTable
1939 /// to have exported functions.
1940 bool hasExportedFunctions(const Module &M) const {
1941 return ModulePathStringTable.count(M.getModuleIdentifier());
1942 }
1943
1944 const TypeIdSummaryMapTy &typeIds() const { return TypeIdMap; }
1945
1946 /// Return an existing or new TypeIdSummary entry for \p TypeId.
1947 /// This accessor can mutate the map and therefore should not be used in
1948 /// the ThinLTO backends.
1950 auto TidIter = TypeIdMap.equal_range(
1952 for (auto &[GUID, TypeIdPair] : make_range(TidIter))
1953 if (TypeIdPair.first == TypeId)
1954 return TypeIdPair.second;
1955 auto It =
1956 TypeIdMap.insert({GlobalValue::getGUIDAssumingExternalLinkage(TypeId),
1957 {TypeIdSaver.save(TypeId), TypeIdSummary()}});
1958 return It->second.second;
1959 }
1960
1961 /// This returns either a pointer to the type id summary (if present in the
1962 /// summary map) or null (if not present). This may be used when importing.
1964 auto TidIter = TypeIdMap.equal_range(
1966 for (const auto &[GUID, TypeIdPair] : make_range(TidIter))
1967 if (TypeIdPair.first == TypeId)
1968 return &TypeIdPair.second;
1969 return nullptr;
1970 }
1971
1973 return const_cast<TypeIdSummary *>(
1974 static_cast<const ModuleSummaryIndex *>(this)->getTypeIdSummary(
1975 TypeId));
1976 }
1977
1978 const auto &typeIdCompatibleVtableMap() const {
1979 return TypeIdCompatibleVtableMap;
1980 }
1981
1982 /// Return an existing or new TypeIdCompatibleVtableMap entry for \p TypeId.
1983 /// This accessor can mutate the map and therefore should not be used in
1984 /// the ThinLTO backends.
1987 return TypeIdCompatibleVtableMap[TypeIdSaver.save(TypeId)];
1988 }
1989
1990 /// For the given \p TypeId, this returns the TypeIdCompatibleVtableMap
1991 /// entry if present in the summary map. This may be used when importing.
1992 std::optional<TypeIdCompatibleVtableInfo>
1994 auto I = TypeIdCompatibleVtableMap.find(TypeId);
1995 if (I == TypeIdCompatibleVtableMap.end())
1996 return std::nullopt;
1997 return I->second;
1998 }
1999
2000 /// Collect for the given module the list of functions it defines
2001 /// (GUID -> Summary).
2002 LLVM_ABI void
2004 GVSummaryMapTy &GVSummaryMap) const;
2005
2006 /// Collect for each module the list of Summaries it defines (GUID ->
2007 /// Summary).
2008 template <class Map>
2009 void
2010 collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const {
2011 for (const auto &GlobalList : *this) {
2012 auto GUID = GlobalList.first;
2013 for (const auto &Summary : GlobalList.second.getSummaryList()) {
2014 ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
2015 }
2016 }
2017 }
2018
2019 /// Print to an output stream.
2020 LLVM_ABI void print(raw_ostream &OS, bool IsForDebug = false) const;
2021
2022 /// Dump to stderr (for debugging).
2023 LLVM_ABI void dump() const;
2024
2025 /// Export summary to dot file for GraphViz.
2026 LLVM_ABI void
2028 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const;
2029
2030 /// Print out strongly connected components for debugging.
2031 LLVM_ABI void dumpSCCs(raw_ostream &OS);
2032
2033 /// Do the access attribute and DSOLocal propagation in combined index.
2034 LLVM_ABI void
2035 propagateAttributes(const DenseSet<GlobalValue::GUID> &PreservedSymbols);
2036
2037 /// Checks if we can import global variable from another module.
2039 bool AnalyzeRefs) const;
2040
2041 /// Same as above but checks whether the global var is importable as a
2042 /// declaration.
2044 bool AnalyzeRefs, bool &CanImportDecl) const;
2045};
2046
2047/// GraphTraits definition to build SCC for the index
2048template <> struct GraphTraits<ValueInfo> {
2051
2053 return P.first;
2054 }
2057 decltype(&valueInfoFromEdge)>;
2058
2061
2062 static NodeRef getEntryNode(ValueInfo V) { return V; }
2063
2065 if (!N.getSummaryList().size()) // handle external function
2066 return ChildIteratorType(
2067 FunctionSummary::ExternalNode.CallGraphEdgeList.begin(),
2070 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2071 return ChildIteratorType(F->CallGraphEdgeList.begin(), &valueInfoFromEdge);
2072 }
2073
2075 if (!N.getSummaryList().size()) // handle external function
2076 return ChildIteratorType(
2077 FunctionSummary::ExternalNode.CallGraphEdgeList.end(),
2080 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2081 return ChildIteratorType(F->CallGraphEdgeList.end(), &valueInfoFromEdge);
2082 }
2083
2085 if (!N.getSummaryList().size()) // handle external function
2086 return FunctionSummary::ExternalNode.CallGraphEdgeList.begin();
2087
2089 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2090 return F->CallGraphEdgeList.begin();
2091 }
2092
2094 if (!N.getSummaryList().size()) // handle external function
2095 return FunctionSummary::ExternalNode.CallGraphEdgeList.end();
2096
2098 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2099 return F->CallGraphEdgeList.end();
2100 }
2101
2102 static NodeRef edge_dest(EdgeRef E) { return E.first; }
2103};
2104
2105template <>
2108 std::unique_ptr<GlobalValueSummary> Root =
2109 std::make_unique<FunctionSummary>(I->calculateCallGraphRoot());
2110 GlobalValueSummaryInfo G(I->haveGVs());
2111 G.addSummary(std::move(Root));
2112 static auto P =
2113 GlobalValueSummaryMapTy::value_type(GlobalValue::GUID(0), std::move(G));
2114 return ValueInfo(I->haveGVs(), &P);
2115 }
2116};
2117} // end namespace llvm
2118
2119#endif // LLVM_IR_MODULESUMMARYINDEX_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:729
#define LLVM_ABI
Definition Compiler.h:213
DXIL Finalize Linkage
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
Value * RHS
GlobalValue::GUID getAliaseeGUID() const
const GlobalValueSummary & getAliasee() const
ValueInfo getAliaseeVI() const
static bool classof(const GlobalValueSummary *GVS)
Check if this is an alias summary.
AliasSummary(GVFlags Flags)
GlobalValueSummary & getAliasee()
void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
GUIDIterator guid_end() const
size_t count(StringRef S) const
std::vector< StringRef > symbols() const
iterator_range< GUIDIterator > guids() const
iterator_range< NestedIterator > forGuid(GlobalValue::GUID GUID) const
GUIDIterator guid_begin() const
This class represents a range of values.
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
Function summary information to aid decisions and implementation of importing.
static LLVM_ABI FunctionSummary ExternalNode
A dummy node to reference external functions that aren't in the index.
static FunctionSummary makeDummyFunctionSummary(SmallVectorImpl< FunctionSummary::EdgeTy > &&Edges)
Create an empty FunctionSummary (with specified call edges).
FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags, SmallVectorImpl< ValueInfo > &&Refs, SmallVectorImpl< EdgeTy > &&CGEdges, std::vector< GlobalValue::GUID > TypeTests, std::vector< VFuncId > TypeTestAssumeVCalls, std::vector< VFuncId > TypeCheckedLoadVCalls, std::vector< ConstVCall > TypeTestAssumeConstVCalls, std::vector< ConstVCall > TypeCheckedLoadConstVCalls, std::vector< ParamAccess > Params, CallsitesTy CallsiteList, AllocsTy AllocList)
ArrayRef< VFuncId > type_test_assume_vcalls() const
Returns the list of virtual calls made by this function using llvm.assume(llvm.type....
void addCallsite(CallsiteInfo &&Callsite)
ArrayRef< ConstVCall > type_test_assume_const_vcalls() const
Returns the list of virtual calls made by this function using llvm.assume(llvm.type....
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
LLVM_ABI std::pair< unsigned, unsigned > specialRefCounts() const
SmallVector< EdgeTy, 0 > & mutableCalls()
ArrayRef< AllocInfo > allocs() const
ArrayRef< CallsiteInfo > callsites() const
void addAlloc(AllocInfo &&Alloc)
void addTypeTest(GlobalValue::GUID Guid)
Add a type test to the summary.
ArrayRef< VFuncId > type_checked_load_vcalls() const
Returns the list of virtual calls made by this function using llvm.type.checked.load intrinsics that ...
void setParamAccesses(std::vector< ParamAccess > NewParams)
Sets the list of known uses of pointer parameters.
unsigned instCount() const
Get the instruction count recorded for this function.
const TypeIdInfo * getTypeIdInfo() const
ArrayRef< ConstVCall > type_checked_load_const_vcalls() const
Returns the list of virtual calls made by this function using llvm.type.checked.load intrinsics with ...
ArrayRef< EdgeTy > calls() const
Return the list of <CalleeValueInfo, CalleeInfo> pairs.
ArrayRef< ParamAccess > paramAccesses() const
Returns the list of known uses of pointer parameters.
CallsitesTy & mutableCallsites()
ForceSummaryHotnessType
Types for -force-summary-edges-cold debugging option.
FFlags fflags() const
Get function summary flags.
ArrayRef< GlobalValue::GUID > type_tests() const
Returns the list of type identifiers used by this function in llvm.type.test intrinsics other than by...
static bool classof(const GlobalValueSummary *GVS)
Check if this is a function summary.
Function and variable summary information to aid decisions and implementation of importing.
SummaryKind
Sububclass discriminator (for dyn_cast<> et al.)
GVFlags flags() const
Get the flags for this GlobalValue (see struct GVFlags).
StringRef modulePath() const
Get the path to the module containing this function.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
SummaryKind getSummaryKind() const
Which kind of summary subclass this is.
GlobalValue::GUID getOriginalName() const
Returns the hash of the original name, it is identical to the GUID for externally visible symbols,...
GlobalValue::VisibilityTypes getVisibility() const
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
void setLinkage(GlobalValue::LinkageTypes Linkage)
Sets the linkage to the value determined by global summary-based optimization.
void setVisibility(GlobalValue::VisibilityTypes Vis)
virtual ~GlobalValueSummary()=default
GlobalValueSummary::ImportKind importType() const
void setNoRenameOnPromotion(bool NoRenameOnPromotion)
void setModulePath(StringRef ModPath)
Set the path to the module containing this function, for use in the combined index.
void setNotEligibleToImport()
Flag that this global value cannot be imported.
void setCanAutoHide(bool CanAutoHide)
GlobalValueSummary(SummaryKind K, GVFlags Flags, SmallVectorImpl< ValueInfo > &&Refs)
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
bool notEligibleToImport() const
Return true if this global value can't be imported.
void setImportKind(ImportKind IK)
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
GUID getGUID() const
Return a 64-bit global unique ID for this value.
Definition Globals.cpp:96
static bool isExternalLinkage(LinkageTypes Linkage)
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
Global variable summary information to aid decisions and implementation of importing.
void setVCallVisibility(GlobalObject::VCallVisibility Vis)
struct llvm::GlobalVarSummary::GVarFlags VarFlags
ArrayRef< VirtFuncOffset > vTableFuncs() const
GlobalVarSummary(GVFlags Flags, GVarFlags VarFlags, SmallVectorImpl< ValueInfo > &&Refs)
GlobalObject::VCallVisibility getVCallVisibility() const
static bool classof(const GlobalValueSummary *GVS)
Check if this is a global variable summary.
void setVTableFuncs(VTableFuncList Funcs)
A helper class to return the specified delimiter string after the first invocation of operator String...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
std::optional< TypeIdCompatibleVtableInfo > getTypeIdCompatibleVtableSummary(StringRef TypeId) const
For the given TypeId, this returns the TypeIdCompatibleVtableMap entry if present in the summary map.
void addGlobalValueSummary(ValueInfo VI, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for the given ValueInfo.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
static void discoverNodes(ValueInfo V, std::map< ValueInfo, bool > &FunctionHasParent)
Convenience function for doing a DFS on a ValueInfo.
StringRef saveString(StringRef String)
const TypeIdSummaryMapTy & typeIds() const
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const
const_gvsummary_iterator end() const
bool isReadOnly(const GlobalVarSummary *GVS) const
LLVM_ABI void setFlags(uint64_t Flags)
const_gvsummary_iterator begin() const
CfiFunctionIndex & cfiFunctionDecls()
bool isWriteOnly(const GlobalVarSummary *GVS) const
const std::vector< uint64_t > & stackIds() const
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
static constexpr const char * getRegularLTOModuleName()
const CfiFunctionIndex & cfiFunctionDefs() const
void addGlobalValueSummary(StringRef ValueName, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value of the given name.
ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit=false, bool UnifiedLTO=false)
LLVM_ABI void collectDefinedFunctionsForModule(StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const
Collect for the given module the list of functions it defines (GUID -> Summary).
const auto & typeIdCompatibleVtableMap() const
LLVM_ABI void dumpSCCs(raw_ostream &OS)
Print out strongly connected components for debugging.
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
const ModuleInfo * getModule(StringRef ModPath) const
Return module entry for module with the given ModPath.
LLVM_ABI void propagateAttributes(const DenseSet< GlobalValue::GUID > &PreservedSymbols)
Do the access attribute and DSOLocal propagation in combined index.
ValueInfo getOrInsertValueInfo(const GlobalValue *GV, GlobalValue::GUID GUID)
Return a ValueInfo for GV with GUID GUID and mark it as belonging to GV.
const StringMap< ModuleHash > & modulePaths() const
Table of modules, containing module hash and id.
LLVM_ABI void dump() const
Dump to stderr (for debugging).
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
bool hasExportedFunctions(const Module &M) const
Check if the given Module has any functions available for exporting in the index.
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
LLVM_ABI void exportToDot(raw_ostream &OS, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols) const
Export summary to dot file for GraphViz.
uint64_t getStackIdAtIndex(unsigned Index) const
StringMap< ModuleHash > & modulePaths()
Table of modules, containing hash and id.
LLVM_ABI void print(raw_ostream &OS, bool IsForDebug=false) const
Print to an output stream.
bool skipModuleByDistributedBackend() const
CfiFunctionIndex & cfiFunctionDefs()
ValueInfo getOrInsertValueInfo(const GlobalValue *GV)
Return a ValueInfo for GV and mark it as belonging to GV.
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
ValueInfo getValueInfo(GlobalValue::GUID GUID) const
Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
LLVM_ABI uint64_t getFlags() const
unsigned addOrGetStackIdIndex(uint64_t StackId)
GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const
Return the GUID for OriginalId in the OidGuidMap.
GlobalValueSummary * getGlobalValueSummary(const GlobalValue &GV, bool PerModuleIndex=true) const
Returns the first GlobalValueSummary for GV, asserting that there is only one if PerModuleIndex.
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID, StringRef Name)
Return a ValueInfo for GUID setting value Name.
LLVM_ABI bool canImportGlobalVar(const GlobalValueSummary *S, bool AnalyzeRefs) const
Checks if we can import global variable from another module.
static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix)
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
FunctionSummary calculateCallGraphRoot()
const CfiFunctionIndex & cfiFunctionDecls() const
TypeIdSummary * getTypeIdSummary(StringRef TypeId)
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PointerIntPair - This class implements a pair of a pointer and small integer.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringMapEntry< ModuleHash > value_type
Definition StringMap.h:217
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition StringMap.h:321
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:45
bool hasName() const
Definition Value.h:261
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
StringMapEntry< Value * > ValueName
Definition Value.h:56
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
hash_code hash_value(const FixedPointSemantics &Val)
std::unordered_set< GlobalValueSummary * > GVSummaryPtrSet
A set of global value summary pointers.
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
const char * getHotnessName(CalleeInfo::HotnessType HT)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::multimap< GlobalValue::GUID, std::pair< StringRef, TypeIdSummary > > TypeIdSummaryMapTy
Map of a type GUID to type id string and summary (multimap used in case of GUID conflicts).
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2142
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2207
std::string utostr(uint64_t X, bool isNeg=false)
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:365
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1745
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
GlobalValueSummaryMapTy::iterator gvsummary_iterator
std::map< GlobalValue::GUID, GlobalValueSummaryInfo > GlobalValueSummaryMapTy
Map from global value GUID to corresponding summary structures.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
StringMap< ModuleHash > ModulePathStringTableTy
String table to hold/own module path strings, as well as a hash of the module.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1771
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
GlobalValueSummaryMapTy::const_iterator const_gvsummary_iterator
Type used for iterating through the global value summary map.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:874
#define N
Summary of memprof metadata on allocations.
AllocInfo(std::vector< MIBInfo > MIBs)
AllocInfo(SmallVector< uint8_t > Versions, std::vector< MIBInfo > MIBs)
std::vector< std::vector< ContextTotalSize > > ContextSizeInfos
SmallVector< uint8_t > Versions
std::vector< MIBInfo > MIBs
Class to accumulate and hold information about a callee.
bool hasTailCall() const
CalleeInfo(HotnessType Hotness, bool HasTC)
void updateHotness(const HotnessType OtherHotness)
HotnessType getHotness() const
void setHasTailCall(const bool HasTC)
Summary of memprof callsite metadata.
SmallVector< unsigned > StackIdIndices
SmallVector< unsigned > Clones
CallsiteInfo(ValueInfo Callee, SmallVector< unsigned > StackIdIndices)
CallsiteInfo(ValueInfo Callee, SmallVector< unsigned > Clones, SmallVector< unsigned > StackIdIndices)
static FunctionSummary::ConstVCall getEmptyKey()
static FunctionSummary::ConstVCall getTombstoneKey()
static unsigned getHashValue(FunctionSummary::ConstVCall I)
static bool isEqual(FunctionSummary::ConstVCall L, FunctionSummary::ConstVCall R)
static FunctionSummary::VFuncId getEmptyKey()
static bool isEqual(FunctionSummary::VFuncId L, FunctionSummary::VFuncId R)
static FunctionSummary::VFuncId getTombstoneKey()
static unsigned getHashValue(FunctionSummary::VFuncId I)
static bool isEqual(ValueInfo L, ValueInfo R)
static bool isSpecialKey(ValueInfo V)
static unsigned getHashValue(ValueInfo I)
An information struct used to provide DenseMap with the various necessary components for a given valu...
A specification for a virtual function call with all constant integer arguments.
Flags specific to function summaries.
FFlags & operator&=(const FFlags &RHS)
Call(uint64_t ParamNo, ValueInfo Callee, const ConstantRange &Offsets)
ParamAccess(uint64_t ParamNo, const ConstantRange &Use)
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
All type identifier related information.
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
An "identifier" for a virtual function.
void addSummary(std::unique_ptr< GlobalValueSummary > Summary)
Add a summary corresponding to a global value definition in a module with the corresponding GUID.
void verifyLocal() const
Verify that the HasLocal flag is consistent with the SummaryList.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
Access a read-only list of global value summary structures for a particular value held in the GlobalV...
union llvm::GlobalValueSummaryInfo::NameOrGV U
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned Promoted
This symbol was promoted.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
GVFlags(GlobalValue::LinkageTypes Linkage, GlobalValue::VisibilityTypes Visibility, bool NotEligibleToImport, bool Live, bool IsLocal, bool CanAutoHide, ImportKind ImportType, bool NoRenameOnPromotion)
Convenience Constructors.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant, GlobalObject::VCallVisibility Vis)
static NodeRef getEntryNode(ModuleSummaryIndex *I)
static NodeRef valueInfoFromEdge(FunctionSummary::EdgeTy &P)
static ChildIteratorType child_begin(NodeRef N)
static ChildEdgeIteratorType child_edge_begin(NodeRef N)
static NodeRef edge_dest(EdgeRef E)
SmallVector< FunctionSummary::EdgeTy, 0 >::iterator ChildEdgeIteratorType
mapped_iterator< SmallVector< FunctionSummary::EdgeTy, 0 >::iterator, decltype(&valueInfoFromEdge)> ChildIteratorType
static NodeRef getEntryNode(ValueInfo V)
static ChildIteratorType child_end(NodeRef N)
static ChildEdgeIteratorType child_edge_end(NodeRef N)
FunctionSummary::EdgeTy & EdgeRef
typename ModuleSummaryIndex *::UnknownGraphTypeError NodeRef
Definition GraphTraits.h:95
Summary of a single MIB in a memprof metadata on allocations.
MIBInfo(AllocationType AllocType, SmallVector< unsigned > StackIdIndices)
AllocationType AllocType
SmallVector< unsigned > StackIdIndices
TypeIdOffsetVtableInfo(uint64_t Offset, ValueInfo VI)
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
Kind
Specifies which kind of type check we should emit for this byte array.
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
Struct that holds a reference to a particular GUID in a global value summary.
PointerIntPair< const GlobalValueSummaryMapTy::value_type *, 3, int > RefAndFlags
LLVM_ABI GlobalValue::VisibilityTypes getELFVisibility() const
Returns the most constraining visibility among summaries.
bool isValidAccessSpecifier() const
const GlobalValueSummaryMapTy::value_type * getRef() const
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
StringRef name() const
bool isWriteOnly() const
const GlobalValue * getValue() const
void verifyLocal() const
LLVM_ABI bool noRenameOnPromotion() const
ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R)
bool isReadOnly() const
LLVM_ABI bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
unsigned getAccessSpecifier() const
ValueInfo()=default
LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation=false) const
Checks if all summaries are DSO local (have the flag set).
GlobalValue::GUID getGUID() const
VirtFuncOffset(ValueInfo VI, uint64_t Offset)
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
This class should be specialized by any type that needs to be converted to/from a YAML mapping.
Definition YAMLTraits.h:63
const GlobalValue * GV
The GlobalValue corresponding to this summary.
StringRef Name
Summary string representation.