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"
21#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/StringSet.h"
30#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/Module.h"
38#include <algorithm>
39#include <array>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
43#include <map>
44#include <memory>
45#include <optional>
46#include <set>
47#include <string>
48#include <unordered_set>
49#include <utility>
50#include <vector>
51
52namespace llvm {
53
54template <class GraphType> struct GraphTraits;
55
56namespace yaml {
57
58template <typename T> struct MappingTraits;
59
60} // end namespace yaml
61
62/// Class to accumulate and hold information about a callee.
63struct CalleeInfo {
64 enum class HotnessType : uint8_t {
66 Cold = 1,
67 None = 2,
68 Hot = 3,
70 };
71
72 // The size of the bit-field might need to be adjusted if more values are
73 // added to HotnessType enum.
75
76 // True if at least one of the calls to the callee is a tail call.
79
83 explicit CalleeInfo(HotnessType Hotness, bool HasTC)
84 : Hotness(static_cast<uint32_t>(Hotness)), HasTailCall(HasTC) {}
85
86 void updateHotness(const HotnessType OtherHotness) {
87 Hotness = std::max(Hotness, static_cast<uint32_t>(OtherHotness));
88 }
89
90 bool hasTailCall() const { return HasTailCall; }
91
92 void setHasTailCall(const bool HasTC) { HasTailCall = HasTC; }
93
95};
96
98 switch (HT) {
100 return "unknown";
102 return "cold";
104 return "none";
106 return "hot";
108 return "critical";
109 }
110 llvm_unreachable("invalid hotness");
111}
112
113class GlobalValueSummary;
114
115using GlobalValueSummaryList = std::vector<std::unique_ptr<GlobalValueSummary>>;
116
117struct alignas(8) GlobalValueSummaryInfo {
118 union NameOrGV {
119 NameOrGV(bool HaveGVs) {
120 if (HaveGVs)
121 GV = nullptr;
122 else
123 Name = "";
124 }
125
126 /// The GlobalValue corresponding to this summary. This is only used in
127 /// per-module summaries and when the IR is available. E.g. when module
128 /// analysis is being run, or when parsing both the IR and the summary
129 /// from assembly.
131
132 /// Summary string representation. This StringRef points to BC module
133 /// string table and is valid until module data is stored in memory.
134 /// This is guaranteed to happen until runThinLTOBackend function is
135 /// called, so it is safe to use this field during thin link. This field
136 /// is only valid if summary index was loaded from BC file.
138 } U;
139
140 inline GlobalValueSummaryInfo(bool HaveGVs);
141
142 /// Access a read-only list of global value summary structures for a
143 /// particular value held in the GlobalValueMap.
145 return SummaryList;
146 }
147
148 /// Add a summary corresponding to a global value definition in a module with
149 /// the corresponding GUID.
150 inline void addSummary(std::unique_ptr<GlobalValueSummary> Summary);
151
152 /// Verify that the HasLocal flag is consistent with the SummaryList. Should
153 /// only be called prior to index-based internalization and promotion.
154 inline void verifyLocal() const;
155
156 bool hasLocal() const { return HasLocal; }
157
158private:
159 /// List of global value summary structures for a particular value held
160 /// in the GlobalValueMap. Requires a vector in the case of multiple
161 /// COMDAT values of the same name, weak symbols, locals of the same name when
162 /// compiling without sufficient distinguishing path, or (theoretically) hash
163 /// collisions. Each summary is from a different module.
164 GlobalValueSummaryList SummaryList;
165
166 /// True if the SummaryList contains at least one summary with local linkage.
167 /// In most cases there should be only one, unless translation units with
168 /// same-named locals were compiled without distinguishing path. And generally
169 /// there should not be a mix of local and non-local summaries, because the
170 /// GUID for a local is computed with the path prepended and a ';' delimiter.
171 /// In extremely rare cases there could be a GUID hash collision. Having the
172 /// flag saves having to walk through all summaries to prove the existence or
173 /// not of any locals.
174 /// NOTE: this flag is set when the index is built. It does not reflect
175 /// index-based internalization and promotion decisions. Generally most
176 /// index-based analysis occurs before then, but any users should assert that
177 /// the withInternalizeAndPromote() flag is not set on the index.
178 /// TODO: Replace checks in various ThinLTO analyses that loop through all
179 /// summaries to handle the local case with a check of the flag.
180 bool HasLocal : 1;
181};
182
183/// Map from global value GUID to corresponding summary structures. Use a
184/// std::map rather than a DenseMap so that pointers to the map's value_type
185/// (which are used by ValueInfo) are not invalidated by insertion. Also it will
186/// likely incur less overhead, as the value type is not very small and the size
187/// of the map is unknown, resulting in inefficiencies due to repeated
188/// insertions and resizing.
190 std::map<GlobalValue::GUID, GlobalValueSummaryInfo>;
191
192/// Struct that holds a reference to a particular GUID in a global value
193/// summary.
194struct ValueInfo {
195 enum Flags { HaveGV = 1, ReadOnly = 2, WriteOnly = 4 };
198
199 ValueInfo() = default;
200 ValueInfo(bool HaveGVs, const GlobalValueSummaryMapTy::value_type *R) {
201 RefAndFlags.setPointer(R);
202 RefAndFlags.setInt(HaveGVs);
203 }
204
205 explicit operator bool() const { return getRef(); }
206
207 GlobalValue::GUID getGUID() const { return getRef()->first; }
208 const GlobalValue *getValue() const {
209 assert(haveGVs());
210 return getRef()->second.U.GV;
211 }
212
214 return getRef()->second.getSummaryList();
215 }
216
217 void verifyLocal() const { getRef()->second.verifyLocal(); }
218
219 bool hasLocal() const { return getRef()->second.hasLocal(); }
220
221 // Even if the index is built with GVs available, we may not have one for
222 // summary entries synthesized for profiled indirect call targets.
223 bool hasName() const { return !haveGVs() || getValue(); }
224
225 StringRef name() const {
226 assert(!haveGVs() || getRef()->second.U.GV);
227 return haveGVs() ? getRef()->second.U.GV->getName()
228 : getRef()->second.U.Name;
229 }
230
231 bool haveGVs() const { return RefAndFlags.getInt() & HaveGV; }
232 bool isReadOnly() const {
234 return RefAndFlags.getInt() & ReadOnly;
235 }
236 bool isWriteOnly() const {
238 return RefAndFlags.getInt() & WriteOnly;
239 }
240 unsigned getAccessSpecifier() const {
242 return RefAndFlags.getInt() & (ReadOnly | WriteOnly);
243 }
245 unsigned BadAccessMask = ReadOnly | WriteOnly;
246 return (RefAndFlags.getInt() & BadAccessMask) != BadAccessMask;
247 }
248 void setReadOnly() {
249 // We expect ro/wo attribute to set only once during
250 // ValueInfo lifetime.
252 RefAndFlags.setInt(RefAndFlags.getInt() | ReadOnly);
253 }
256 RefAndFlags.setInt(RefAndFlags.getInt() | WriteOnly);
257 }
258
259 const GlobalValueSummaryMapTy::value_type *getRef() const {
260 return RefAndFlags.getPointer();
261 }
262
263 /// Returns the most constraining visibility among summaries. The
264 /// visibilities, ordered from least to most constraining, are: default,
265 /// protected and hidden.
267
268 /// Checks if all summaries are DSO local (have the flag set). When DSOLocal
269 /// propagation has been done, set the parameter to enable fast check.
270 LLVM_ABI bool isDSOLocal(bool WithDSOLocalPropagation = false) const;
271
272 /// Checks if all copies are eligible for auto-hiding (have flag set).
273 LLVM_ABI bool canAutoHide() const;
274
276};
277
279 OS << VI.getGUID();
280 if (!VI.name().empty())
281 OS << " (" << VI.name() << ")";
282 return OS;
283}
284
285inline bool operator==(const ValueInfo &A, const ValueInfo &B) {
286 assert(A.getRef() && B.getRef() &&
287 "Need ValueInfo with non-null Ref for comparison");
288 return A.getRef() == B.getRef();
289}
290
291inline bool operator!=(const ValueInfo &A, const ValueInfo &B) {
292 assert(A.getRef() && B.getRef() &&
293 "Need ValueInfo with non-null Ref for comparison");
294 return A.getRef() != B.getRef();
295}
296
297inline bool operator<(const ValueInfo &A, const ValueInfo &B) {
298 assert(A.getRef() && B.getRef() &&
299 "Need ValueInfo with non-null Ref to compare GUIDs");
300 return A.getGUID() < B.getGUID();
301}
302
303template <> struct DenseMapInfo<ValueInfo> {
304 static inline ValueInfo getEmptyKey() {
305 return ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
306 }
307
308 static inline bool isSpecialKey(ValueInfo V) { return V == getEmptyKey(); }
309
310 static bool isEqual(ValueInfo L, ValueInfo R) {
311 // We are not supposed to mix ValueInfo(s) with different HaveGVs flag
312 // in a same container.
313 assert(isSpecialKey(L) || isSpecialKey(R) || (L.haveGVs() == R.haveGVs()));
314 return L.getRef() == R.getRef();
315 }
316 static unsigned getHashValue(ValueInfo I) { return hash_value(I.getRef()); }
317};
318
319// For optional hinted size reporting, holds a pair of the full stack id
320// (pre-trimming, from the full context in the profile), and the associated
321// total profiled size.
326
327/// Summary of memprof callsite metadata.
329 // Actual callee function.
331
332 // Used to record whole program analysis cloning decisions.
333 // The ThinLTO backend will need to create as many clones as there are entries
334 // in the vector (it is expected and should be confirmed that all such
335 // summaries in the same FunctionSummary have the same number of entries).
336 // Each index records version info for the corresponding clone of this
337 // function. The value is the callee clone it calls (becomes the appended
338 // suffix id). Index 0 is the original version, and a value of 0 calls the
339 // original callee.
341
342 // Represents stack ids in this context, recorded as indices into the
343 // StackIds vector in the summary index, which in turn holds the full 64-bit
344 // stack ids. This reduces memory as there are in practice far fewer unique
345 // stack ids than stack id references.
347
354};
355
357 OS << "Callee: " << SNI.Callee;
358 OS << " Clones: " << llvm::interleaved(SNI.Clones);
359 OS << " StackIds: " << llvm::interleaved(SNI.StackIdIndices);
360 return OS;
361}
362
363// Allocation type assigned to an allocation reached by a given context.
364// More can be added, now this is cold, notcold and hot.
365// Values should be powers of two so that they can be ORed, in particular to
366// track allocations that have different behavior with different calling
367// contexts.
369 None = 0,
371 Cold = 2,
372 Hot = 4,
373 All = 7 // This should always be set to the OR of all values.
374};
375
376/// Summary of a single MIB in a memprof metadata on allocations.
377struct MIBInfo {
378 // The allocation type for this profiled context.
380
381 // Represents stack ids in this context, recorded as indices into the
382 // StackIds vector in the summary index, which in turn holds the full 64-bit
383 // stack ids. This reduces memory as there are in practice far fewer unique
384 // stack ids than stack id references.
386
389};
390
391inline raw_ostream &operator<<(raw_ostream &OS, const MIBInfo &MIB) {
392 OS << "AllocType " << (unsigned)MIB.AllocType;
393 OS << " StackIds: " << llvm::interleaved(MIB.StackIdIndices);
394 return OS;
395}
396
397/// Summary of memprof metadata on allocations.
398struct AllocInfo {
399 // Used to record whole program analysis cloning decisions.
400 // The ThinLTO backend will need to create as many clones as there are entries
401 // in the vector (it is expected and should be confirmed that all such
402 // summaries in the same FunctionSummary have the same number of entries).
403 // Each index records version info for the corresponding clone of this
404 // function. The value is the allocation type of the corresponding allocation.
405 // Index 0 is the original version. Before cloning, index 0 may have more than
406 // one allocation type.
408
409 // Vector of MIBs in this memprof metadata.
410 std::vector<MIBInfo> MIBs;
411
412 // If requested, keep track of full stack contexts and total profiled sizes
413 // for each MIB. This will be a vector of the same length and order as the
414 // MIBs vector, if non-empty. Note that each MIB in the summary can have
415 // multiple of these as we trim the contexts when possible during matching.
416 // For hinted size reporting we, however, want the original pre-trimmed full
417 // stack context id for better correlation with the profile.
418 std::vector<std::vector<ContextTotalSize>> ContextSizeInfos;
419
420 AllocInfo(std::vector<MIBInfo> MIBs) : MIBs(std::move(MIBs)) {
421 Versions.push_back(0);
422 }
425};
426
428 OS << "Versions: "
430
431 OS << " MIB:\n";
432 for (auto &M : AE.MIBs)
433 OS << "\t\t" << M << "\n";
434 if (!AE.ContextSizeInfos.empty()) {
435 OS << "\tContextSizeInfo per MIB:\n";
436 for (auto Infos : AE.ContextSizeInfos) {
437 OS << "\t\t";
438 ListSeparator InfoLS;
439 for (auto [FullStackId, TotalSize] : Infos)
440 OS << InfoLS << "{ " << FullStackId << ", " << TotalSize << " }";
441 OS << "\n";
442 }
443 }
444 return OS;
445}
446
447/// Function and variable summary information to aid decisions and
448/// implementation of importing.
450public:
451 /// Sububclass discriminator (for dyn_cast<> et al.)
453
454 enum ImportKind : unsigned {
455 // The global value definition corresponding to the summary should be
456 // imported from source module
458
459 // When its definition doesn't exist in the destination module and not
460 // imported (e.g., function is too large to be inlined), the global value
461 // declaration corresponding to the summary should be imported, or the
462 // attributes from summary should be annotated on the function declaration.
464 };
465
466 /// Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
467 struct GVFlags {
468 /// The linkage type of the associated global value.
469 ///
470 /// One use is to flag values that have local linkage types and need to
471 /// have module identifier appended before placing into the combined
472 /// index, to disambiguate from other values with the same name.
473 /// In the future this will be used to update and optimize linkage
474 /// types based on global summary-based analysis.
475 unsigned Linkage : 4;
476
477 /// Indicates the visibility.
478 unsigned Visibility : 2;
479
480 /// Indicate if the global value cannot be imported (e.g. it cannot
481 /// be renamed or references something that can't be renamed).
483
484 /// In per-module summary, indicate that the global value must be considered
485 /// a live root for index-based liveness analysis. Used for special LLVM
486 /// values such as llvm.global_ctors that the linker does not know about.
487 ///
488 /// In combined summary, indicate that the global value is live.
489 unsigned Live : 1;
490
491 /// Indicates that the linker resolved the symbol to a definition from
492 /// within the same linkage unit.
493 unsigned DSOLocal : 1;
494
495 /// In the per-module summary, indicates that the global value is
496 /// linkonce_odr and global unnamed addr (so eligible for auto-hiding
497 /// via hidden visibility). In the combined summary, indicates that the
498 /// prevailing linkonce_odr copy can be auto-hidden via hidden visibility
499 /// when it is upgraded to weak_odr in the backend. This is legal when
500 /// all copies are eligible for auto-hiding (i.e. all copies were
501 /// linkonce_odr global unnamed addr. If any copy is not (e.g. it was
502 /// originally weak_odr, we cannot auto-hide the prevailing copy as it
503 /// means the symbol was externally visible.
504 unsigned CanAutoHide : 1;
505
506 /// This field is written by the ThinLTO indexing step to postlink combined
507 /// summary. The value is interpreted as 'ImportKind' enum defined above.
508 unsigned ImportType : 1;
509
510 /// This symbol was promoted. Thinlink stages need to be aware of this
511 /// transition
512 unsigned Promoted : 1;
513
514 /// This field is written by the ThinLTO prelink stage to decide whether
515 /// a particular static global value should be promoted or not.
517
518 /// Convenience Constructors
529 };
530
531private:
532 /// Kind of summary for use in dyn_cast<> et al.
533 SummaryKind Kind;
534
535 GVFlags Flags;
536
537 /// This is the hash of the name of the symbol in the original file. It is
538 /// identical to the GUID for global symbols, but differs for local since the
539 /// GUID includes the module level id in the hash.
540 GlobalValue::GUID OriginalName = 0;
541
542 /// Path of module IR containing value's definition, used to locate
543 /// module during importing.
544 ///
545 /// This is only used during parsing of the combined index, or when
546 /// parsing the per-module index for creation of the combined summary index,
547 /// not during writing of the per-module index which doesn't contain a
548 /// module path string table.
549 StringRef ModulePath;
550
551 /// List of values referenced by this global value's definition
552 /// (either by the initializer of a global variable, or referenced
553 /// from within a function). This does not include functions called, which
554 /// are listed in the derived FunctionSummary object.
555 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
556 /// smaller memory footprint.
557 SmallVector<ValueInfo, 0> RefEdgeList;
558
559protected:
562 : Kind(K), Flags(Flags), RefEdgeList(std::move(Refs)) {
563 assert((K != AliasKind || Refs.empty()) &&
564 "Expect no references for AliasSummary");
565 }
566
567public:
568 virtual ~GlobalValueSummary() = default;
569
570 /// Returns the hash of the original name, it is identical to the GUID for
571 /// externally visible symbols, but not for local ones.
572 GlobalValue::GUID getOriginalName() const { return OriginalName; }
573
574 /// Initialize the original name hash in this summary.
575 void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; }
576
577 /// Which kind of summary subclass this is.
578 SummaryKind getSummaryKind() const { return Kind; }
579
580 /// Set the path to the module containing this function, for use in
581 /// the combined index.
582 void setModulePath(StringRef ModPath) { ModulePath = ModPath; }
583
584 /// Get the path to the module containing this function.
585 StringRef modulePath() const { return ModulePath; }
586
587 /// Get the flags for this GlobalValue (see \p struct GVFlags).
588 GVFlags flags() const { return Flags; }
589
590 /// Return linkage type recorded for this global value.
592 return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage);
593 }
594
595 bool wasPromoted() const { return Flags.Promoted; }
596
597 void promote() {
599 "unexpected (re-)promotion of non-local symbol");
600 assert(!Flags.Promoted);
601 Flags.Promoted = true;
603 }
604
605 /// Sets the linkage to the value determined by global summary-based
606 /// optimization. Will be applied in the ThinLTO backends.
609 assert(!GlobalValue::isExternalLinkage(Linkage) && "use `promote` instead");
610 Flags.Linkage = Linkage;
611 }
612
616
617 /// Return true if this global value can't be imported.
618 bool notEligibleToImport() const { return Flags.NotEligibleToImport; }
619
620 bool isLive() const { return Flags.Live; }
621
622 void setLive(bool Live) { Flags.Live = Live; }
623
624 void setDSOLocal(bool Local) { Flags.DSOLocal = Local; }
625
626 bool isDSOLocal() const { return Flags.DSOLocal; }
627
628 void setCanAutoHide(bool CanAutoHide) { Flags.CanAutoHide = CanAutoHide; }
629
630 bool canAutoHide() const { return Flags.CanAutoHide; }
631
632 bool shouldImportAsDecl() const {
633 return Flags.ImportType == GlobalValueSummary::ImportKind::Declaration;
634 }
635
636 void setImportKind(ImportKind IK) { Flags.ImportType = IK; }
637
638 void setNoRenameOnPromotion(bool NoRenameOnPromotion) {
639 Flags.NoRenameOnPromotion = NoRenameOnPromotion;
640 }
641
642 bool noRenameOnPromotion() const { return Flags.NoRenameOnPromotion; }
643
645 return static_cast<ImportKind>(Flags.ImportType);
646 }
647
649 return (GlobalValue::VisibilityTypes)Flags.Visibility;
650 }
652 Flags.Visibility = (unsigned)Vis;
653 }
654
655 /// Flag that this global value cannot be imported.
656 void setNotEligibleToImport() { Flags.NotEligibleToImport = true; }
657
658 /// Return the list of values referenced by this global value definition.
659 ArrayRef<ValueInfo> refs() const { return RefEdgeList; }
660
661 /// If this is an alias summary, returns the summary of the aliased object (a
662 /// global variable or function), otherwise returns itself.
664 const GlobalValueSummary *getBaseObject() const;
665
666 friend class ModuleSummaryIndex;
667};
668
670 : U(HaveGVs), HasLocal(false) {}
671
673 std::unique_ptr<GlobalValueSummary> Summary) {
674 if (GlobalValue::isLocalLinkage(Summary->linkage()))
675 HasLocal = true;
676 return SummaryList.push_back(std::move(Summary));
677}
678
680 assert(HasLocal ==
681 llvm::any_of(SummaryList,
682 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
683 return GlobalValue::isLocalLinkage(Summary->linkage());
684 }));
685}
686
687/// Alias summary information.
689 ValueInfo AliaseeValueInfo;
690
691 /// This is the Aliasee in the same module as alias (could get from VI, trades
692 /// memory for time). Note that this pointer may be null (and the value info
693 /// empty) when we have a distributed index where the alias is being imported
694 /// (as a copy of the aliasee), but the aliasee is not.
695 GlobalValueSummary *AliaseeSummary = nullptr;
696
697public:
700
701 /// Check if this is an alias summary.
702 static bool classof(const GlobalValueSummary *GVS) {
703 return GVS->getSummaryKind() == AliasKind;
704 }
705
706 void setAliasee(ValueInfo &AliaseeVI, GlobalValueSummary *Aliasee) {
707 AliaseeValueInfo = AliaseeVI;
708 AliaseeSummary = Aliasee;
709 }
710
711 bool hasAliasee() const {
712 assert(!!AliaseeSummary == (AliaseeValueInfo &&
713 !AliaseeValueInfo.getSummaryList().empty()) &&
714 "Expect to have both aliasee summary and summary list or neither");
715 return !!AliaseeSummary;
716 }
717
719 assert(AliaseeSummary && "Unexpected missing aliasee summary");
720 return *AliaseeSummary;
721 }
722
724 return const_cast<GlobalValueSummary &>(
725 static_cast<const AliasSummary *>(this)->getAliasee());
726 }
728 assert(AliaseeValueInfo && "Unexpected missing aliasee");
729 return AliaseeValueInfo;
730 }
732 assert(AliaseeValueInfo && "Unexpected missing aliasee");
733 return AliaseeValueInfo.getGUID();
734 }
735};
736
738 if (auto *AS = dyn_cast<AliasSummary>(this))
739 return &AS->getAliasee();
740 return this;
741}
742
744 if (auto *AS = dyn_cast<AliasSummary>(this))
745 return &AS->getAliasee();
746 return this;
747}
748
749/// Function summary information to aid decisions and implementation of
750/// importing.
752public:
753 /// <CalleeValueInfo, CalleeInfo> call edge pair.
754 using EdgeTy = std::pair<ValueInfo, CalleeInfo>;
755
756 /// Types for -force-summary-edges-cold debugging option.
762
763 /// An "identifier" for a virtual function. This contains the type identifier
764 /// represented as a GUID and the offset from the address point to the virtual
765 /// function pointer, where "address point" is as defined in the Itanium ABI:
766 /// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
771
772 /// A specification for a virtual function call with all constant integer
773 /// arguments. This is used to perform virtual constant propagation on the
774 /// summary.
775 struct ConstVCall {
777 std::vector<uint64_t> Args;
778 };
779
780 /// All type identifier related information. Because these fields are
781 /// relatively uncommon we only allocate space for them if necessary.
782 struct TypeIdInfo {
783 /// List of type identifiers used by this function in llvm.type.test
784 /// intrinsics referenced by something other than an llvm.assume intrinsic,
785 /// represented as GUIDs.
786 std::vector<GlobalValue::GUID> TypeTests;
787
788 /// List of virtual calls made by this function using (respectively)
789 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do
790 /// not have all constant integer arguments.
792
793 /// List of virtual calls made by this function using (respectively)
794 /// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with
795 /// all constant integer arguments.
796 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
798 };
799
800 /// Flags specific to function summaries.
801 struct FFlags {
802 // Function attribute flags. Used to track if a function accesses memory,
803 // recurses or aliases.
804 unsigned ReadNone : 1;
805 unsigned ReadOnly : 1;
806 unsigned NoRecurse : 1;
807 unsigned ReturnDoesNotAlias : 1;
808
809 // Indicate if the global value cannot be inlined.
810 unsigned NoInline : 1;
811 // Indicate if function should be always inlined.
812 unsigned AlwaysInline : 1;
813 // Indicate if function never raises an exception. Can be modified during
814 // thinlink function attribute propagation
815 unsigned NoUnwind : 1;
816 // Indicate if function contains instructions that mayThrow
817 unsigned MayThrow : 1;
818
819 // If there are calls to unknown targets (e.g. indirect)
820 unsigned HasUnknownCall : 1;
821
822 // Indicate if a function must be an unreachable function.
823 //
824 // This bit is sufficient but not necessary;
825 // if this bit is on, the function must be regarded as unreachable;
826 // if this bit is off, the function might be reachable or unreachable.
827 unsigned MustBeUnreachable : 1;
828
830 this->ReadNone &= RHS.ReadNone;
831 this->ReadOnly &= RHS.ReadOnly;
832 this->NoRecurse &= RHS.NoRecurse;
833 this->ReturnDoesNotAlias &= RHS.ReturnDoesNotAlias;
834 this->NoInline &= RHS.NoInline;
835 this->AlwaysInline &= RHS.AlwaysInline;
836 this->NoUnwind &= RHS.NoUnwind;
837 this->MayThrow &= RHS.MayThrow;
838 this->HasUnknownCall &= RHS.HasUnknownCall;
839 this->MustBeUnreachable &= RHS.MustBeUnreachable;
840 return *this;
841 }
842
843 bool anyFlagSet() {
844 return this->ReadNone | this->ReadOnly | this->NoRecurse |
845 this->ReturnDoesNotAlias | this->NoInline | this->AlwaysInline |
846 this->NoUnwind | this->MayThrow | this->HasUnknownCall |
847 this->MustBeUnreachable;
848 }
849
850 operator std::string() {
851 std::string Output;
852 raw_string_ostream OS(Output);
853 OS << "funcFlags: (";
854 OS << "readNone: " << this->ReadNone;
855 OS << ", readOnly: " << this->ReadOnly;
856 OS << ", noRecurse: " << this->NoRecurse;
857 OS << ", returnDoesNotAlias: " << this->ReturnDoesNotAlias;
858 OS << ", noInline: " << this->NoInline;
859 OS << ", alwaysInline: " << this->AlwaysInline;
860 OS << ", noUnwind: " << this->NoUnwind;
861 OS << ", mayThrow: " << this->MayThrow;
862 OS << ", hasUnknownCall: " << this->HasUnknownCall;
863 OS << ", mustBeUnreachable: " << this->MustBeUnreachable;
864 OS << ")";
865 return Output;
866 }
867 };
868
869 /// Describes the uses of a parameter by the function.
870 struct ParamAccess {
871 static constexpr uint32_t RangeWidth = 64;
872
873 /// Describes the use of a value in a call instruction, specifying the
874 /// call's target, the value's parameter number, and the possible range of
875 /// offsets from the beginning of the value that are passed.
885
887 /// The range contains byte offsets from the parameter pointer which
888 /// accessed by the function. In the per-module summary, it only includes
889 /// accesses made by the function instructions. In the combined summary, it
890 /// also includes accesses by nested function calls.
891 ConstantRange Use{/*BitWidth=*/RangeWidth, /*isFullSet=*/true};
892 /// In the per-module summary, it summarizes the byte offset applied to each
893 /// pointer parameter before passing to each corresponding callee.
894 /// In the combined summary, it's empty and information is propagated by
895 /// inter-procedural analysis and applied to the Use field.
896 std::vector<Call> Calls;
897
898 ParamAccess() = default;
901 };
902
903 /// Create an empty FunctionSummary (with specified call edges).
904 /// Used to represent external nodes and the dummy root node.
905 static FunctionSummary
907 return FunctionSummary(
911 /*NotEligibleToImport=*/true, /*Live=*/true, /*IsLocal=*/false,
912 /*CanAutoHide=*/false, GlobalValueSummary::ImportKind::Definition,
913 /*NoRenameOnPromotion=*/false),
915 std::move(Edges), std::vector<GlobalValue::GUID>(),
916 std::vector<FunctionSummary::VFuncId>(),
917 std::vector<FunctionSummary::VFuncId>(),
918 std::vector<FunctionSummary::ConstVCall>(),
919 std::vector<FunctionSummary::ConstVCall>(),
920 std::vector<FunctionSummary::ParamAccess>(),
921 std::vector<CallsiteInfo>(), std::vector<AllocInfo>());
922 }
923
924 /// A dummy node to reference external functions that aren't in the index
926
927private:
928 /// Number of instructions (ignoring debug instructions, e.g.) computed
929 /// during the initial compile step when the summary index is first built.
930 unsigned InstCount;
931
932 /// Function summary specific flags.
933 FFlags FunFlags;
934
935 /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function.
936 /// We use SmallVector<ValueInfo, 0> instead of std::vector<ValueInfo> for its
937 /// smaller memory footprint.
938 SmallVector<EdgeTy, 0> CallGraphEdgeList;
939
940 std::unique_ptr<TypeIdInfo> TIdInfo;
941
942 /// Uses for every parameter to this function.
943 using ParamAccessesTy = std::vector<ParamAccess>;
944 std::unique_ptr<ParamAccessesTy> ParamAccesses;
945
946 /// Optional list of memprof callsite metadata summaries. The correspondence
947 /// between the callsite summary and the callsites in the function is implied
948 /// by the order in the vector (and can be validated by comparing the stack
949 /// ids in the CallsiteInfo to those in the instruction callsite metadata).
950 /// As a memory savings optimization, we only create these for the prevailing
951 /// copy of a symbol when creating the combined index during LTO.
952 using CallsitesTy = std::vector<CallsiteInfo>;
953 std::unique_ptr<CallsitesTy> Callsites;
954
955 /// Optional list of allocation memprof metadata summaries. The correspondence
956 /// between the alloc memprof summary and the allocation callsites in the
957 /// function is implied by the order in the vector (and can be validated by
958 /// comparing the stack ids in the AllocInfo to those in the instruction
959 /// memprof metadata).
960 /// As a memory savings optimization, we only create these for the prevailing
961 /// copy of a symbol when creating the combined index during LTO.
962 using AllocsTy = std::vector<AllocInfo>;
963 std::unique_ptr<AllocsTy> Allocs;
964
965public:
966 FunctionSummary(GVFlags Flags, unsigned NumInsts, FFlags FunFlags,
968 SmallVectorImpl<EdgeTy> &&CGEdges,
969 std::vector<GlobalValue::GUID> TypeTests,
970 std::vector<VFuncId> TypeTestAssumeVCalls,
971 std::vector<VFuncId> TypeCheckedLoadVCalls,
972 std::vector<ConstVCall> TypeTestAssumeConstVCalls,
973 std::vector<ConstVCall> TypeCheckedLoadConstVCalls,
974 std::vector<ParamAccess> Params, CallsitesTy CallsiteList,
975 AllocsTy AllocList)
976 : GlobalValueSummary(FunctionKind, Flags, std::move(Refs)),
977 InstCount(NumInsts), FunFlags(FunFlags),
978 CallGraphEdgeList(std::move(CGEdges)) {
979 if (!TypeTests.empty() || !TypeTestAssumeVCalls.empty() ||
980 !TypeCheckedLoadVCalls.empty() || !TypeTestAssumeConstVCalls.empty() ||
981 !TypeCheckedLoadConstVCalls.empty())
982 TIdInfo = std::make_unique<TypeIdInfo>(
983 TypeIdInfo{std::move(TypeTests), std::move(TypeTestAssumeVCalls),
984 std::move(TypeCheckedLoadVCalls),
985 std::move(TypeTestAssumeConstVCalls),
986 std::move(TypeCheckedLoadConstVCalls)});
987 if (!Params.empty())
988 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(Params));
989 if (!CallsiteList.empty())
990 Callsites = std::make_unique<CallsitesTy>(std::move(CallsiteList));
991 if (!AllocList.empty())
992 Allocs = std::make_unique<AllocsTy>(std::move(AllocList));
993 }
994 // Gets the number of readonly and writeonly refs in RefEdgeList
995 LLVM_ABI std::pair<unsigned, unsigned> specialRefCounts() const;
996
997 /// Check if this is a function summary.
998 static bool classof(const GlobalValueSummary *GVS) {
999 return GVS->getSummaryKind() == FunctionKind;
1000 }
1001
1002 /// Get function summary flags.
1003 FFlags fflags() const { return FunFlags; }
1004
1005 void setNoRecurse() { FunFlags.NoRecurse = true; }
1006
1007 void setNoUnwind() { FunFlags.NoUnwind = true; }
1008
1009 /// Get the instruction count recorded for this function.
1010 unsigned instCount() const { return InstCount; }
1011
1012 /// Return the list of <CalleeValueInfo, CalleeInfo> pairs.
1013 ArrayRef<EdgeTy> calls() const { return CallGraphEdgeList; }
1014
1015 SmallVector<EdgeTy, 0> &mutableCalls() { return CallGraphEdgeList; }
1016
1017 void addCall(EdgeTy E) { CallGraphEdgeList.push_back(E); }
1018
1019 /// Returns the list of type identifiers used by this function in
1020 /// llvm.type.test intrinsics other than by an llvm.assume intrinsic,
1021 /// represented as GUIDs.
1023 if (TIdInfo)
1024 return TIdInfo->TypeTests;
1025 return {};
1026 }
1027
1028 /// Returns the list of virtual calls made by this function using
1029 /// llvm.assume(llvm.type.test) intrinsics that do not have all constant
1030 /// integer arguments.
1032 if (TIdInfo)
1033 return TIdInfo->TypeTestAssumeVCalls;
1034 return {};
1035 }
1036
1037 /// Returns the list of virtual calls made by this function using
1038 /// llvm.type.checked.load intrinsics that do not have all constant integer
1039 /// arguments.
1041 if (TIdInfo)
1042 return TIdInfo->TypeCheckedLoadVCalls;
1043 return {};
1044 }
1045
1046 /// Returns the list of virtual calls made by this function using
1047 /// llvm.assume(llvm.type.test) intrinsics with all constant integer
1048 /// arguments.
1050 if (TIdInfo)
1051 return TIdInfo->TypeTestAssumeConstVCalls;
1052 return {};
1053 }
1054
1055 /// Returns the list of virtual calls made by this function using
1056 /// llvm.type.checked.load intrinsics with all constant integer arguments.
1058 if (TIdInfo)
1059 return TIdInfo->TypeCheckedLoadConstVCalls;
1060 return {};
1061 }
1062
1063 /// Returns the list of known uses of pointer parameters.
1065 if (ParamAccesses)
1066 return *ParamAccesses;
1067 return {};
1068 }
1069
1070 /// Sets the list of known uses of pointer parameters.
1071 void setParamAccesses(std::vector<ParamAccess> NewParams) {
1072 if (NewParams.empty())
1073 ParamAccesses.reset();
1074 else if (ParamAccesses)
1075 *ParamAccesses = std::move(NewParams);
1076 else
1077 ParamAccesses = std::make_unique<ParamAccessesTy>(std::move(NewParams));
1078 }
1079
1080 /// Add a type test to the summary. This is used by WholeProgramDevirt if we
1081 /// were unable to devirtualize a checked call.
1083 if (!TIdInfo)
1084 TIdInfo = std::make_unique<TypeIdInfo>();
1085 TIdInfo->TypeTests.push_back(Guid);
1086 }
1087
1088 const TypeIdInfo *getTypeIdInfo() const { return TIdInfo.get(); };
1089
1091 if (Callsites)
1092 return *Callsites;
1093 return {};
1094 }
1095
1096 CallsitesTy &mutableCallsites() {
1097 assert(Callsites);
1098 return *Callsites;
1099 }
1100
1101 void addCallsite(CallsiteInfo &&Callsite) {
1102 if (!Callsites)
1103 Callsites = std::make_unique<CallsitesTy>();
1104 Callsites->push_back(std::move(Callsite));
1105 }
1106
1108 if (Allocs)
1109 return *Allocs;
1110 return {};
1111 }
1112
1114 if (!Allocs)
1115 Allocs = std::make_unique<AllocsTy>();
1116 Allocs->push_back(std::move(Alloc));
1117 }
1118
1119 AllocsTy &mutableAllocs() {
1120 assert(Allocs);
1121 return *Allocs;
1122 }
1123
1124 friend struct GraphTraits<ValueInfo>;
1125};
1126
1127template <> struct DenseMapInfo<FunctionSummary::VFuncId> {
1128 static FunctionSummary::VFuncId getEmptyKey() { return {0, uint64_t(-1)}; }
1129
1131 return L.GUID == R.GUID && L.Offset == R.Offset;
1132 }
1133
1134 static unsigned getHashValue(FunctionSummary::VFuncId I) { return I.GUID; }
1135};
1136
1137template <> struct DenseMapInfo<FunctionSummary::ConstVCall> {
1139 return {{0, uint64_t(-1)}, {}};
1140 }
1141
1144 return DenseMapInfo<FunctionSummary::VFuncId>::isEqual(L.VFunc, R.VFunc) &&
1145 L.Args == R.Args;
1146 }
1147
1149 return I.VFunc.GUID;
1150 }
1151};
1152
1153/// The ValueInfo and offset for a function within a vtable definition
1154/// initializer array.
1162/// List of functions referenced by a particular vtable definition.
1163using VTableFuncList = std::vector<VirtFuncOffset>;
1164
1165/// Global variable summary information to aid decisions and
1166/// implementation of importing.
1167///
1168/// Global variable summary has two extra flag, telling if it is
1169/// readonly or writeonly. Both readonly and writeonly variables
1170/// can be optimized in the backed: readonly variables can be
1171/// const-folded, while writeonly vars can be completely eliminated
1172/// together with corresponding stores. We let both things happen
1173/// by means of internalizing such variables after ThinLTO import.
1175private:
1176 /// For vtable definitions this holds the list of functions and
1177 /// their corresponding offsets within the initializer array.
1178 std::unique_ptr<VTableFuncList> VTableFuncs;
1179
1180public:
1181 struct GVarFlags {
1182 GVarFlags(bool ReadOnly, bool WriteOnly, bool Constant,
1184 : MaybeReadOnly(ReadOnly), MaybeWriteOnly(WriteOnly),
1186
1187 // If true indicates that this global variable might be accessed
1188 // purely by non-volatile load instructions. This in turn means
1189 // it can be internalized in source and destination modules during
1190 // thin LTO import because it neither modified nor its address
1191 // is taken.
1192 unsigned MaybeReadOnly : 1;
1193 // If true indicates that variable is possibly only written to, so
1194 // its value isn't loaded and its address isn't taken anywhere.
1195 // False, when 'Constant' attribute is set.
1196 unsigned MaybeWriteOnly : 1;
1197 // Indicates that value is a compile-time constant. Global variable
1198 // can be 'Constant' while not being 'ReadOnly' on several occasions:
1199 // - it is volatile, (e.g mapped device address)
1200 // - its address is taken, meaning that unlike 'ReadOnly' vars we can't
1201 // internalize it.
1202 // Constant variables are always imported thus giving compiler an
1203 // opportunity to make some extra optimizations. Readonly constants
1204 // are also internalized.
1205 unsigned Constant : 1;
1206 // Set from metadata on vtable definitions during the module summary
1207 // analysis.
1208 unsigned VCallVisibility : 2;
1210
1215
1216 /// Check if this is a global variable summary.
1217 static bool classof(const GlobalValueSummary *GVS) {
1218 return GVS->getSummaryKind() == GlobalVarKind;
1219 }
1220
1221 GVarFlags varflags() const { return VarFlags; }
1222 void setReadOnly(bool RO) { VarFlags.MaybeReadOnly = RO; }
1223 void setWriteOnly(bool WO) { VarFlags.MaybeWriteOnly = WO; }
1224 bool maybeReadOnly() const { return VarFlags.MaybeReadOnly; }
1225 bool maybeWriteOnly() const { return VarFlags.MaybeWriteOnly; }
1226 bool isConstant() const { return VarFlags.Constant; }
1228 VarFlags.VCallVisibility = Vis;
1229 }
1233
1235 assert(!VTableFuncs);
1236 VTableFuncs = std::make_unique<VTableFuncList>(std::move(Funcs));
1237 }
1238
1240 if (VTableFuncs)
1241 return *VTableFuncs;
1242 return {};
1243 }
1244};
1245
1247 /// Specifies which kind of type check we should emit for this byte array.
1248 /// See http://clang.llvm.org/docs/ControlFlowIntegrityDesign.html for full
1249 /// details on each kind of check; the enumerators are described with
1250 /// reference to that document.
1251 enum Kind {
1252 Unsat, ///< Unsatisfiable type (i.e. no global has this type metadata)
1253 ByteArray, ///< Test a byte array (first example)
1254 Inline, ///< Inlined bit vector ("Short Inline Bit Vectors")
1255 Single, ///< Single element (last example in "Short Inline Bit Vectors")
1256 AllOnes, ///< All-ones bit vector ("Eliminating Bit Vector Checks for
1257 /// All-Ones Bit Vectors")
1258 Unknown, ///< Unknown (analysis not performed, don't lower)
1260
1261 /// Range of size-1 expressed as a bit width. For example, if the size is in
1262 /// range [1,256], this number will be 8. This helps generate the most compact
1263 /// instruction sequences.
1264 unsigned SizeM1BitWidth = 0;
1265
1266 // The following fields are only used if the target does not support the use
1267 // of absolute symbols to store constants. Their meanings are the same as the
1268 // corresponding fields in LowerTypeTestsModule::TypeIdLowering in
1269 // LowerTypeTests.cpp.
1270
1275};
1276
1278 enum Kind {
1279 Indir, ///< Just do a regular virtual call
1280 SingleImpl, ///< Single implementation devirtualization
1281 BranchFunnel, ///< When retpoline mitigation is enabled, use a branch funnel
1282 ///< that is defined in the merged module. Otherwise same as
1283 ///< Indir.
1285
1286 std::string SingleImplName;
1287
1288 struct ByArg {
1289 enum Kind {
1290 Indir, ///< Just do a regular virtual call
1291 UniformRetVal, ///< Uniform return value optimization
1292 UniqueRetVal, ///< Unique return value optimization
1293 VirtualConstProp, ///< Virtual constant propagation
1295
1296 /// Additional information for the resolution:
1297 /// - UniformRetVal: the uniform return value.
1298 /// - UniqueRetVal: the return value associated with the unique vtable (0 or
1299 /// 1).
1301
1302 // The following fields are only used if the target does not support the use
1303 // of absolute symbols to store constants.
1304
1307 };
1308
1309 /// Resolutions for calls with all constant integer arguments (excluding the
1310 /// first argument, "this"), where the key is the argument vector.
1311 std::map<std::vector<uint64_t>, ByArg> ResByArg;
1312};
1313
1316
1317 /// Mapping from byte offset to whole-program devirt resolution for that
1318 /// (typeid, byte offset) pair.
1319 std::map<uint64_t, WholeProgramDevirtResolution> WPDRes;
1320};
1321
1322/// Encapsulate the names of CFI target functions. It interfaces with ThinLTO to
1323/// determine efficiently which of the names need to be exported for a
1324/// particular module.
1326 // `Names` is the authoritative source of data. `ThinLTOToNamesIndex` is there
1327 // just to efficiently retrieve which names in this index need exporting for
1328 // a particular module index. We cannot guarantee the ThinLTO GUIDs are
1329 // collision - free, so we associate a collection to a guid. Functions with
1330 // the same name may have different GUIDs, too. So we index a list of names
1331 // with the same GUID under that GUID key. We don't need the reverse because
1332 // the queries from ThinLTO use GUIDs as key.
1333 // Note that StringSet rehashing doesn't move keys, so we can safely store the
1334 // StringRef value inserted in `Names` in ThinLTOToNamesIndex, and avoid
1335 // copies.
1336 // Design note: we could do away with Names and use ThinLTOToNamesIndex as
1337 // index and data source, but opted against, for a small heap penalty, to
1338 // avoid confusion wrt the role GUIDs play in this case: they are an artifact
1339 // of the need to interface with ThinLTO, not otherwise necessary to CFI.
1340 StringSet<> Names;
1341
1342 using InternalIndexGroup = SetVector<StringRef>;
1344
1345 using NestedIterator = InternalIndexGroup::const_iterator;
1346
1347public:
1348 CfiFunctionIndex() = default;
1351
1352 /// API used for serialization, e.g. YAML.
1353 std::vector<std::pair<StringRef, GlobalValue::GUID>>
1355 std::vector<std::pair<StringRef, GlobalValue::GUID>> Symbols;
1356 for (auto &[GUID, Names] : ThinLTOToNamesIndex)
1357 for (auto Name : Names)
1358 Symbols.emplace_back(Name, GUID);
1359 llvm::sort(Symbols);
1360 return Symbols;
1361 }
1362
1363 /// get the set of GUIDs that should also be exported because they are the
1364 /// GUIDs of the cfi functions encapsulated here.
1366 return map_range(ThinLTOToNamesIndex, [](auto I) { return I.first; });
1367 }
1368
1369 /// get the name(s) associated with a given ThinLTO GUID. This enables
1370 /// efficient identification of the subset of names that should be included in
1371 /// a module summary.
1373 auto I = ThinLTOToNamesIndex.find(GUID);
1374 if (I == ThinLTOToNamesIndex.end())
1375 return make_range(NestedIterator{}, NestedIterator{});
1376 return make_range(I->second.begin(), I->second.end());
1377 }
1378
1379 /// Add the function name and the GUID that ThinLTO uses for it.
1381 auto [Iter, _] = Names.insert(Name);
1382 ThinLTOToNamesIndex[GUID].insert(Iter->first());
1383 }
1384
1385 bool contains(StringRef Name) const {
1386 return Names.find(Name) != Names.end();
1387 }
1388
1389 bool empty() const {
1390 assert(Names.empty() == ThinLTOToNamesIndex.empty());
1391 return Names.empty();
1392 }
1393};
1394
1395/// 160 bits SHA1
1396using ModuleHash = std::array<uint32_t, 5>;
1397
1398/// Type used for iterating through the global value summary map.
1399using const_gvsummary_iterator = GlobalValueSummaryMapTy::const_iterator;
1400using gvsummary_iterator = GlobalValueSummaryMapTy::iterator;
1401
1402/// String table to hold/own module path strings, as well as a hash
1403/// of the module. The StringMap makes a copy of and owns inserted strings.
1405
1406/// Map of global value GUID to its summary, used to identify values defined in
1407/// a particular module, and provide efficient access to their summary.
1409
1410/// Map of a module name to the GUIDs and summaries we will import from that
1411/// module.
1413 std::map<std::string, GVSummaryMapTy, std::less<>>;
1414
1415/// A set of global value summary pointers.
1416using GVSummaryPtrSet = std::unordered_set<GlobalValueSummary *>;
1417
1418/// Map of a type GUID to type id string and summary (multimap used
1419/// in case of GUID conflicts).
1421 std::multimap<GlobalValue::GUID, std::pair<StringRef, TypeIdSummary>>;
1422
1423/// The following data structures summarize type metadata information.
1424/// For type metadata overview see https://llvm.org/docs/TypeMetadata.html.
1425/// Each type metadata includes both the type identifier and the offset of
1426/// the address point of the type (the address held by objects of that type
1427/// which may not be the beginning of the virtual table). Vtable definitions
1428/// are decorated with type metadata for the types they are compatible with.
1429///
1430/// Holds information about vtable definitions decorated with type metadata:
1431/// the vtable definition value and its address point offset in a type
1432/// identifier metadata it is decorated (compatible) with.
1440/// List of vtable definitions decorated by a particular type identifier,
1441/// and their corresponding offsets in that type identifier's metadata.
1442/// Note that each type identifier may be compatible with multiple vtables, due
1443/// to inheritance, which is why this is a vector.
1444using TypeIdCompatibleVtableInfo = std::vector<TypeIdOffsetVtableInfo>;
1445
1446/// Class to hold module path string table and global value map,
1447/// and encapsulate methods for operating on them.
1449private:
1450 /// Map from value name to list of summary instances for values of that
1451 /// name (may be duplicates in the COMDAT case, e.g.).
1452 GlobalValueSummaryMapTy GlobalValueMap;
1453
1454 /// Holds strings for combined index, mapping to the corresponding module ID.
1455 ModulePathStringTableTy ModulePathStringTable;
1456
1457 BumpPtrAllocator TypeIdSaverAlloc;
1458 UniqueStringSaver TypeIdSaver;
1459
1460 /// Mapping from type identifier GUIDs to type identifier and its summary
1461 /// information. Produced by thin link.
1462 TypeIdSummaryMapTy TypeIdMap;
1463
1464 /// Mapping from type identifier to information about vtables decorated
1465 /// with that type identifier's metadata. Produced by per module summary
1466 /// analysis and consumed by thin link. For more information, see description
1467 /// above where TypeIdCompatibleVtableInfo is defined.
1468 std::map<StringRef, TypeIdCompatibleVtableInfo, std::less<>>
1469 TypeIdCompatibleVtableMap;
1470
1471 /// Mapping from original ID to GUID. If original ID can map to multiple
1472 /// GUIDs, it will be mapped to 0.
1474
1475 /// Indicates that summary-based GlobalValue GC has run, and values with
1476 /// GVFlags::Live==false are really dead. Otherwise, all values must be
1477 /// considered live.
1478 bool WithGlobalValueDeadStripping = false;
1479
1480 /// Indicates that summary-based attribute propagation has run and
1481 /// GVarFlags::MaybeReadonly / GVarFlags::MaybeWriteonly are really
1482 /// read/write only.
1483 bool WithAttributePropagation = false;
1484
1485 /// Indicates that summary-based DSOLocal propagation has run and the flag in
1486 /// every summary of a GV is synchronized.
1487 bool WithDSOLocalPropagation = false;
1488
1489 /// Indicates that summary-based internalization and promotion has run.
1490 bool WithInternalizeAndPromote = false;
1491
1492 /// Indicates that we have whole program visibility.
1493 bool WithWholeProgramVisibility = false;
1494
1495 /// Indicates that summary-based synthetic entry count propagation has run
1496 bool HasSyntheticEntryCounts = false;
1497
1498 /// Indicates that we linked with allocator supporting hot/cold new operators.
1499 bool WithSupportsHotColdNew = false;
1500
1501 /// Indicates that distributed backend should skip compilation of the
1502 /// module. Flag is suppose to be set by distributed ThinLTO indexing
1503 /// when it detected that the module is not needed during the final
1504 /// linking. As result distributed backend should just output a minimal
1505 /// valid object file.
1506 bool SkipModuleByDistributedBackend = false;
1507
1508 /// If true then we're performing analysis of IR module, or parsing along with
1509 /// the IR from assembly. The value of 'false' means we're reading summary
1510 /// from BC or YAML source. Affects the type of value stored in NameOrGV
1511 /// union.
1512 bool HaveGVs;
1513
1514 // True if the index was created for a module compiled with -fsplit-lto-unit.
1515 bool EnableSplitLTOUnit;
1516
1517 // True if the index was created for a module compiled with -funified-lto
1518 bool UnifiedLTO;
1519
1520 // True if some of the modules were compiled with -fsplit-lto-unit and
1521 // some were not. Set when the combined index is created during the thin link.
1522 bool PartiallySplitLTOUnits = false;
1523
1524 /// True if some of the FunctionSummary contains a ParamAccess.
1525 bool HasParamAccess = false;
1526
1527 CfiFunctionIndex CfiFunctionDefs;
1528 CfiFunctionIndex CfiFunctionDecls;
1529
1530 // Used in cases where we want to record the name of a global, but
1531 // don't have the string owned elsewhere (e.g. the Strtab on a module).
1532 BumpPtrAllocator Alloc;
1533 StringSaver Saver;
1534
1535 // The total number of basic blocks in the module in the per-module summary or
1536 // the total number of basic blocks in the LTO unit in the combined index.
1537 // FIXME: Putting this in the distributed ThinLTO index files breaks LTO
1538 // backend caching on any BB change to any linked file. It is currently not
1539 // used except in the case of a SamplePGO partial profile, and should be
1540 // reevaluated/redesigned to allow more effective incremental builds in that
1541 // case.
1542 uint64_t BlockCount = 0;
1543
1544 // List of unique stack ids (hashes). We use a 4B index of the id in the
1545 // stack id lists on the alloc and callsite summaries for memory savings,
1546 // since the number of unique ids is in practice much smaller than the
1547 // number of stack id references in the summaries.
1548 std::vector<uint64_t> StackIds;
1549
1550 // Temporary map while building StackIds list. Clear when index is completely
1551 // built via releaseTemporaryMemory.
1552 DenseMap<uint64_t, unsigned> StackIdToIndex;
1553
1554 // YAML I/O support.
1556
1557 GlobalValueSummaryMapTy::value_type *
1558 getOrInsertValuePtr(GlobalValue::GUID GUID) {
1559 return &*GlobalValueMap.emplace(GUID, GlobalValueSummaryInfo(HaveGVs))
1560 .first;
1561 }
1562
1563public:
1564 // See HaveGVs variable comment.
1565 ModuleSummaryIndex(bool HaveGVs, bool EnableSplitLTOUnit = false,
1566 bool UnifiedLTO = false)
1567 : TypeIdSaver(TypeIdSaverAlloc), HaveGVs(HaveGVs),
1568 EnableSplitLTOUnit(EnableSplitLTOUnit), UnifiedLTO(UnifiedLTO),
1569 Saver(Alloc) {}
1570
1571 // Current version for the module summary in bitcode files.
1572 // The BitcodeSummaryVersion should be bumped whenever we introduce changes
1573 // in the way some record are interpreted, like flags for instance.
1574 // Note that incrementing this may require changes in both BitcodeReader.cpp
1575 // and BitcodeWriter.cpp.
1576 static constexpr uint64_t BitcodeSummaryVersion = 14;
1577
1578 // Regular LTO module name for ASM writer
1579 static constexpr const char *getRegularLTOModuleName() {
1580 return "[Regular LTO]";
1581 }
1582
1583 bool haveGVs() const { return HaveGVs; }
1584
1585 LLVM_ABI uint64_t getFlags() const;
1586 LLVM_ABI void setFlags(uint64_t Flags);
1587
1588 uint64_t getBlockCount() const { return BlockCount; }
1589 void addBlockCount(uint64_t C) { BlockCount += C; }
1590 void setBlockCount(uint64_t C) { BlockCount = C; }
1591
1592 gvsummary_iterator begin() { return GlobalValueMap.begin(); }
1593 const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); }
1594 gvsummary_iterator end() { return GlobalValueMap.end(); }
1595 const_gvsummary_iterator end() const { return GlobalValueMap.end(); }
1596 size_t size() const { return GlobalValueMap.size(); }
1597
1598 const std::vector<uint64_t> &stackIds() const { return StackIds; }
1599
1600 unsigned addOrGetStackIdIndex(uint64_t StackId) {
1601 auto Inserted = StackIdToIndex.insert({StackId, StackIds.size()});
1602 if (Inserted.second)
1603 StackIds.push_back(StackId);
1604 return Inserted.first->second;
1605 }
1606
1607 uint64_t getStackIdAtIndex(unsigned Index) const {
1608 assert(StackIds.size() > Index);
1609 return StackIds[Index];
1610 }
1611
1612 // Facility to release memory from data structures only needed during index
1613 // construction (including while building combined index). Currently this only
1614 // releases the temporary map used while constructing a correspondence between
1615 // stack ids and their index in the StackIds vector. Mostly impactful when
1616 // building a large combined index.
1618 assert(StackIdToIndex.size() == StackIds.size());
1619 StackIdToIndex.clear();
1620 StackIds.shrink_to_fit();
1621 }
1622
1623 /// Convenience function for doing a DFS on a ValueInfo. Marks the function in
1624 /// the FunctionHasParent map.
1626 std::map<ValueInfo, bool> &FunctionHasParent) {
1627 if (!V.getSummaryList().size())
1628 return; // skip external functions that don't have summaries
1629
1630 // Mark discovered if we haven't yet
1631 auto S = FunctionHasParent.emplace(V, false);
1632
1633 // Stop if we've already discovered this node
1634 if (!S.second)
1635 return;
1636
1638 dyn_cast<FunctionSummary>(V.getSummaryList().front().get());
1639 assert(F != nullptr && "Expected FunctionSummary node");
1640
1641 for (const auto &C : F->calls()) {
1642 // Insert node if necessary
1643 auto S = FunctionHasParent.emplace(C.first, true);
1644
1645 // Skip nodes that we're sure have parents
1646 if (!S.second && S.first->second)
1647 continue;
1648
1649 if (S.second)
1650 discoverNodes(C.first, FunctionHasParent);
1651 else
1652 S.first->second = true;
1653 }
1654 }
1655
1656 // Calculate the callgraph root
1658 // Functions that have a parent will be marked in FunctionHasParent pair.
1659 // Once we've marked all functions, the functions in the map that are false
1660 // have no parent (so they're the roots)
1661 std::map<ValueInfo, bool> FunctionHasParent;
1662
1663 for (auto &S : *this) {
1664 // Skip external functions
1665 if (!S.second.getSummaryList().size() ||
1666 !isa<FunctionSummary>(S.second.getSummaryList().front().get()))
1667 continue;
1668 discoverNodes(ValueInfo(HaveGVs, &S), FunctionHasParent);
1669 }
1670
1672 // create edges to all roots in the Index
1673 for (auto &P : FunctionHasParent) {
1674 if (P.second)
1675 continue; // skip over non-root nodes
1676 Edges.push_back(std::make_pair(P.first, CalleeInfo{}));
1677 }
1678 return FunctionSummary::makeDummyFunctionSummary(std::move(Edges));
1679 }
1680
1682 return WithGlobalValueDeadStripping;
1683 }
1685 WithGlobalValueDeadStripping = true;
1686 }
1687
1688 bool withAttributePropagation() const { return WithAttributePropagation; }
1690 WithAttributePropagation = true;
1691 }
1692
1693 bool withDSOLocalPropagation() const { return WithDSOLocalPropagation; }
1694 void setWithDSOLocalPropagation() { WithDSOLocalPropagation = true; }
1695
1696 bool withInternalizeAndPromote() const { return WithInternalizeAndPromote; }
1697 void setWithInternalizeAndPromote() { WithInternalizeAndPromote = true; }
1698
1699 bool withWholeProgramVisibility() const { return WithWholeProgramVisibility; }
1700 void setWithWholeProgramVisibility() { WithWholeProgramVisibility = true; }
1701
1702 bool isReadOnly(const GlobalVarSummary *GVS) const {
1703 return WithAttributePropagation && GVS->maybeReadOnly();
1704 }
1705 bool isWriteOnly(const GlobalVarSummary *GVS) const {
1706 return WithAttributePropagation && GVS->maybeWriteOnly();
1707 }
1708
1709 bool withSupportsHotColdNew() const { return WithSupportsHotColdNew; }
1710 void setWithSupportsHotColdNew() { WithSupportsHotColdNew = true; }
1711
1713 return SkipModuleByDistributedBackend;
1714 }
1716 SkipModuleByDistributedBackend = true;
1717 }
1718
1719 bool enableSplitLTOUnit() const { return EnableSplitLTOUnit; }
1720 void setEnableSplitLTOUnit() { EnableSplitLTOUnit = true; }
1721
1722 bool hasUnifiedLTO() const { return UnifiedLTO; }
1723 void setUnifiedLTO() { UnifiedLTO = true; }
1724
1725 bool partiallySplitLTOUnits() const { return PartiallySplitLTOUnits; }
1726 void setPartiallySplitLTOUnits() { PartiallySplitLTOUnits = true; }
1727
1728 bool hasParamAccess() const { return HasParamAccess; }
1729
1730 bool isGlobalValueLive(const GlobalValueSummary *GVS) const {
1731 return !WithGlobalValueDeadStripping || GVS->isLive();
1732 }
1733 LLVM_ABI bool isGUIDLive(GlobalValue::GUID GUID) const;
1734
1735 /// Return a ValueInfo for the index value_type (convenient when iterating
1736 /// index).
1737 ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const {
1738 return ValueInfo(HaveGVs, &R);
1739 }
1740
1741 /// Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
1743 auto I = GlobalValueMap.find(GUID);
1744 return ValueInfo(HaveGVs, I == GlobalValueMap.end() ? nullptr : &*I);
1745 }
1746
1747 /// Return a ValueInfo for \p GUID.
1749 return ValueInfo(HaveGVs, getOrInsertValuePtr(GUID));
1750 }
1751
1752 // Save a string in the Index. Use before passing Name to
1753 // getOrInsertValueInfo when the string isn't owned elsewhere (e.g. on the
1754 // module's Strtab).
1755 StringRef saveString(StringRef String) { return Saver.save(String); }
1756
1757 /// Return a ValueInfo for \p GUID setting value \p Name.
1759 assert(!HaveGVs);
1760 auto VP = getOrInsertValuePtr(GUID);
1761 VP->second.U.Name = Name;
1762 return ValueInfo(HaveGVs, VP);
1763 }
1764
1765 /// Return a ValueInfo for \p GV and mark it as belonging to GV.
1767 assert(HaveGVs);
1768 auto VP = getOrInsertValuePtr(GV->getGUID());
1769 VP->second.U.GV = GV;
1770 return ValueInfo(HaveGVs, VP);
1771 }
1772
1773 /// Return the GUID for \p OriginalId in the OidGuidMap.
1775 const auto I = OidGuidMap.find(OriginalID);
1776 return I == OidGuidMap.end() ? 0 : I->second;
1777 }
1778
1779 CfiFunctionIndex &cfiFunctionDefs() { return CfiFunctionDefs; }
1780 const CfiFunctionIndex &cfiFunctionDefs() const { return CfiFunctionDefs; }
1781
1782 CfiFunctionIndex &cfiFunctionDecls() { return CfiFunctionDecls; }
1783 const CfiFunctionIndex &cfiFunctionDecls() const { return CfiFunctionDecls; }
1784
1785 /// Add a global value summary for a value.
1787 std::unique_ptr<GlobalValueSummary> Summary) {
1788 addGlobalValueSummary(getOrInsertValueInfo(&GV), std::move(Summary));
1789 }
1790
1791 /// Add a global value summary for a value of the given name.
1793 std::unique_ptr<GlobalValueSummary> Summary) {
1797 std::move(Summary));
1798 }
1799
1800 /// Add a global value summary for the given ValueInfo.
1802 std::unique_ptr<GlobalValueSummary> Summary) {
1803 if (const FunctionSummary *FS = dyn_cast<FunctionSummary>(Summary.get()))
1804 HasParamAccess |= !FS->paramAccesses().empty();
1805 addOriginalName(VI.getGUID(), Summary->getOriginalName());
1806 // Here we have a notionally const VI, but the value it points to is owned
1807 // by the non-const *this.
1808 const_cast<GlobalValueSummaryMapTy::value_type *>(VI.getRef())
1809 ->second.addSummary(std::move(Summary));
1810 }
1811
1812 /// Add an original name for the value of the given GUID.
1814 GlobalValue::GUID OrigGUID) {
1815 if (OrigGUID == 0 || ValueGUID == OrigGUID)
1816 return;
1817 auto [It, Inserted] = OidGuidMap.try_emplace(OrigGUID, ValueGUID);
1818 if (!Inserted && It->second != ValueGUID)
1819 It->second = 0;
1820 }
1821
1822 /// Find the summary for ValueInfo \p VI in module \p ModuleId, or nullptr if
1823 /// not found.
1825 auto SummaryList = VI.getSummaryList();
1826 auto Summary =
1827 llvm::find_if(SummaryList,
1828 [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
1829 return Summary->modulePath() == ModuleId;
1830 });
1831 if (Summary == SummaryList.end())
1832 return nullptr;
1833 return Summary->get();
1834 }
1835
1836 /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if
1837 /// not found.
1839 StringRef ModuleId) const {
1840 auto CalleeInfo = getValueInfo(ValueGUID);
1841 if (!CalleeInfo)
1842 return nullptr; // This function does not have a summary
1843 return findSummaryInModule(CalleeInfo, ModuleId);
1844 }
1845
1846 /// Returns the first GlobalValueSummary for \p GV, asserting that there
1847 /// is only one if \p PerModuleIndex.
1849 bool PerModuleIndex = true) const {
1850 assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name");
1851 return getGlobalValueSummary(GV.getGUID(), PerModuleIndex);
1852 }
1853
1854 /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that
1855 /// there
1856 /// is only one if \p PerModuleIndex.
1859 bool PerModuleIndex = true) const;
1860
1861 /// Table of modules, containing module hash and id.
1863 return ModulePathStringTable;
1864 }
1865
1866 /// Table of modules, containing hash and id.
1867 StringMap<ModuleHash> &modulePaths() { return ModulePathStringTable; }
1868
1869 /// Get the module SHA1 hash recorded for the given module path.
1870 const ModuleHash &getModuleHash(const StringRef ModPath) const {
1871 auto It = ModulePathStringTable.find(ModPath);
1872 assert(It != ModulePathStringTable.end() && "Module not registered");
1873 return It->second;
1874 }
1875
1876 /// Convenience method for creating a promoted global name
1877 /// for the given value name of a local, and its original module's ID.
1878 static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) {
1879 std::string Suffix = utostr((uint64_t(ModHash[0]) << 32) |
1880 ModHash[1]); // Take the first 64 bits
1881 return getGlobalNameForLocal(Name, Suffix);
1882 }
1883
1884 static std::string getGlobalNameForLocal(StringRef Name, StringRef Suffix) {
1885 SmallString<256> NewName(Name);
1886 NewName += ".llvm.";
1887 NewName += Suffix;
1888 return std::string(NewName);
1889 }
1890
1891 /// Helper to obtain the unpromoted name for a global value (or the original
1892 /// name if not promoted). Split off the rightmost ".llvm.${hash}" suffix,
1893 /// because it is possible in certain clients (not clang at the moment) for
1894 /// two rounds of ThinLTO optimization and therefore promotion to occur.
1896 std::pair<StringRef, StringRef> Pair = Name.rsplit(".llvm.");
1897 return Pair.first;
1898 }
1899
1901
1902 /// Add a new module with the given \p Hash, mapped to the given \p
1903 /// ModID, and return a reference to the module.
1905 return &*ModulePathStringTable.insert({ModPath, Hash}).first;
1906 }
1907
1908 /// Return module entry for module with the given \p ModPath.
1910 auto It = ModulePathStringTable.find(ModPath);
1911 assert(It != ModulePathStringTable.end() && "Module not registered");
1912 return &*It;
1913 }
1914
1915 /// Return module entry for module with the given \p ModPath.
1916 const ModuleInfo *getModule(StringRef ModPath) const {
1917 auto It = ModulePathStringTable.find(ModPath);
1918 assert(It != ModulePathStringTable.end() && "Module not registered");
1919 return &*It;
1920 }
1921
1922 /// Check if the given Module has any functions available for exporting
1923 /// in the index. We consider any module present in the ModulePathStringTable
1924 /// to have exported functions.
1925 bool hasExportedFunctions(const Module &M) const {
1926 return ModulePathStringTable.count(M.getModuleIdentifier());
1927 }
1928
1929 const TypeIdSummaryMapTy &typeIds() const { return TypeIdMap; }
1930
1931 /// Return an existing or new TypeIdSummary entry for \p TypeId.
1932 /// This accessor can mutate the map and therefore should not be used in
1933 /// the ThinLTO backends.
1935 auto TidIter = TypeIdMap.equal_range(
1937 for (auto &[GUID, TypeIdPair] : make_range(TidIter))
1938 if (TypeIdPair.first == TypeId)
1939 return TypeIdPair.second;
1940 auto It =
1941 TypeIdMap.insert({GlobalValue::getGUIDAssumingExternalLinkage(TypeId),
1942 {TypeIdSaver.save(TypeId), TypeIdSummary()}});
1943 return It->second.second;
1944 }
1945
1946 /// This returns either a pointer to the type id summary (if present in the
1947 /// summary map) or null (if not present). This may be used when importing.
1949 auto TidIter = TypeIdMap.equal_range(
1951 for (const auto &[GUID, TypeIdPair] : make_range(TidIter))
1952 if (TypeIdPair.first == TypeId)
1953 return &TypeIdPair.second;
1954 return nullptr;
1955 }
1956
1958 return const_cast<TypeIdSummary *>(
1959 static_cast<const ModuleSummaryIndex *>(this)->getTypeIdSummary(
1960 TypeId));
1961 }
1962
1963 const auto &typeIdCompatibleVtableMap() const {
1964 return TypeIdCompatibleVtableMap;
1965 }
1966
1967 /// Return an existing or new TypeIdCompatibleVtableMap entry for \p TypeId.
1968 /// This accessor can mutate the map and therefore should not be used in
1969 /// the ThinLTO backends.
1972 return TypeIdCompatibleVtableMap[TypeIdSaver.save(TypeId)];
1973 }
1974
1975 /// For the given \p TypeId, this returns the TypeIdCompatibleVtableMap
1976 /// entry if present in the summary map. This may be used when importing.
1977 std::optional<TypeIdCompatibleVtableInfo>
1979 auto I = TypeIdCompatibleVtableMap.find(TypeId);
1980 if (I == TypeIdCompatibleVtableMap.end())
1981 return std::nullopt;
1982 return I->second;
1983 }
1984
1985 /// Collect for the given module the list of functions it defines
1986 /// (GUID -> Summary).
1987 LLVM_ABI void
1989 GVSummaryMapTy &GVSummaryMap) const;
1990
1991 /// Collect for each module the list of Summaries it defines (GUID ->
1992 /// Summary).
1993 template <class Map>
1994 void
1995 collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const {
1996 for (const auto &GlobalList : *this) {
1997 auto GUID = GlobalList.first;
1998 for (const auto &Summary : GlobalList.second.getSummaryList()) {
1999 ModuleToDefinedGVSummaries[Summary->modulePath()][GUID] = Summary.get();
2000 }
2001 }
2002 }
2003
2004 /// Print to an output stream.
2005 LLVM_ABI void print(raw_ostream &OS, bool IsForDebug = false) const;
2006
2007 /// Dump to stderr (for debugging).
2008 LLVM_ABI void dump() const;
2009
2010 /// Export summary to dot file for GraphViz.
2011 LLVM_ABI void
2013 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) const;
2014
2015 /// Print out strongly connected components for debugging.
2016 LLVM_ABI void dumpSCCs(raw_ostream &OS);
2017
2018 /// Do the access attribute and DSOLocal propagation in combined index.
2019 LLVM_ABI void
2020 propagateAttributes(const DenseSet<GlobalValue::GUID> &PreservedSymbols);
2021
2022 /// Checks if we can import global variable from another module.
2024 bool AnalyzeRefs) const;
2025
2026 /// Same as above but checks whether the global var is importable as a
2027 /// declaration.
2029 bool AnalyzeRefs, bool &CanImportDecl) const;
2030};
2031
2032/// GraphTraits definition to build SCC for the index
2033template <> struct GraphTraits<ValueInfo> {
2036
2038 return P.first;
2039 }
2042 decltype(&valueInfoFromEdge)>;
2043
2046
2047 static NodeRef getEntryNode(ValueInfo V) { return V; }
2048
2050 if (!N.getSummaryList().size()) // handle external function
2051 return ChildIteratorType(
2052 FunctionSummary::ExternalNode.CallGraphEdgeList.begin(),
2055 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2056 return ChildIteratorType(F->CallGraphEdgeList.begin(), &valueInfoFromEdge);
2057 }
2058
2060 if (!N.getSummaryList().size()) // handle external function
2061 return ChildIteratorType(
2062 FunctionSummary::ExternalNode.CallGraphEdgeList.end(),
2065 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2066 return ChildIteratorType(F->CallGraphEdgeList.end(), &valueInfoFromEdge);
2067 }
2068
2070 if (!N.getSummaryList().size()) // handle external function
2071 return FunctionSummary::ExternalNode.CallGraphEdgeList.begin();
2072
2074 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2075 return F->CallGraphEdgeList.begin();
2076 }
2077
2079 if (!N.getSummaryList().size()) // handle external function
2080 return FunctionSummary::ExternalNode.CallGraphEdgeList.end();
2081
2083 cast<FunctionSummary>(N.getSummaryList().front()->getBaseObject());
2084 return F->CallGraphEdgeList.end();
2085 }
2086
2087 static NodeRef edge_dest(EdgeRef E) { return E.first; }
2088};
2089
2090template <>
2093 std::unique_ptr<GlobalValueSummary> Root =
2094 std::make_unique<FunctionSummary>(I->calculateCallGraphRoot());
2095 GlobalValueSummaryInfo G(I->haveGVs());
2096 G.addSummary(std::move(Root));
2097 static auto P =
2098 GlobalValueSummaryMapTy::value_type(GlobalValue::GUID(0), std::move(G));
2099 return ValueInfo(I->haveGVs(), &P);
2100 }
2101};
2102} // end namespace llvm
2103
2104#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.
#define _
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 implements a set that has insertion order iteration characteristics.
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
StringSet - A set-like wrapper for the StringMap.
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
Encapsulate the names of CFI target functions.
std::vector< std::pair< StringRef, GlobalValue::GUID > > getSortedSymbols() const
API used for serialization, e.g. YAML.
auto getExportedThinLTOGUIDs() const
get the set of GUIDs that should also be exported because they are the GUIDs of the cfi functions enc...
CfiFunctionIndex(CfiFunctionIndex &&)=default
auto getNamesForGUID(GlobalValue::GUID GUID) const
get the name(s) associated with a given ThinLTO GUID.
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
bool contains(StringRef Name) const
CfiFunctionIndex(const CfiFunctionIndex &)=delete
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.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
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.
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:67
PointerIntPair - This class implements a pair of a pointer and small integer.
A vector that has set insertion semantics.
Definition SetVector.h:57
typename vector_type::const_iterator const_iterator
Definition SetVector.h:73
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
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
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
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.
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.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
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:861
#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 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 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.