1 //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===//
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 // This pass implements whole program optimization of virtual calls in cases
10 // where we know (via !type metadata) that the list of callees is fixed. This
11 // includes the following:
12 // - Single implementation devirtualization: if a virtual call has a single
13 //   possible callee, replace all calls with a direct call to that callee.
14 // - Virtual constant propagation: if the virtual function's return type is an
15 //   integer <=64 bits and all possible callees are readnone, for each class and
16 //   each list of constant arguments: evaluate the function, store the return
17 //   value alongside the virtual table, and rewrite each virtual call as a load
18 //   from the virtual table.
19 // - Uniform return value optimization: if the conditions for virtual constant
20 //   propagation hold and each function returns the same constant value, replace
21 //   each virtual call with that constant.
22 // - Unique return value optimization for i1 return values: if the conditions
23 //   for virtual constant propagation hold and a single vtable's function
24 //   returns 0, or a single vtable's function returns 1, replace each virtual
25 //   call with a comparison of the vptr against that vtable's address.
26 //
27 // This pass is intended to be used during the regular and thin LTO pipelines:
28 //
29 // During regular LTO, the pass determines the best optimization for each
30 // virtual call and applies the resolutions directly to virtual calls that are
31 // eligible for virtual call optimization (i.e. calls that use either of the
32 // llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics).
33 //
34 // During hybrid Regular/ThinLTO, the pass operates in two phases:
35 // - Export phase: this is run during the thin link over a single merged module
36 //   that contains all vtables with !type metadata that participate in the link.
37 //   The pass computes a resolution for each virtual call and stores it in the
38 //   type identifier summary.
39 // - Import phase: this is run during the thin backends over the individual
40 //   modules. The pass applies the resolutions previously computed during the
41 //   import phase to each eligible virtual call.
42 //
43 // During ThinLTO, the pass operates in two phases:
44 // - Export phase: this is run during the thin link over the index which
45 //   contains a summary of all vtables with !type metadata that participate in
46 //   the link. It computes a resolution for each virtual call and stores it in
47 //   the type identifier summary. Only single implementation devirtualization
48 //   is supported.
49 // - Import phase: (same as with hybrid case above).
50 //
51 //===----------------------------------------------------------------------===//
52 
53 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/DenseMapInfo.h"
57 #include "llvm/ADT/DenseSet.h"
58 #include "llvm/ADT/MapVector.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/iterator_range.h"
61 #include "llvm/Analysis/AliasAnalysis.h"
62 #include "llvm/Analysis/BasicAliasAnalysis.h"
63 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
64 #include "llvm/Analysis/TypeMetadataUtils.h"
65 #include "llvm/Bitcode/BitcodeReader.h"
66 #include "llvm/Bitcode/BitcodeWriter.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GlobalAlias.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InstrTypes.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/LLVMContext.h"
81 #include "llvm/IR/Metadata.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/ModuleSummaryIndexYAML.h"
84 #include "llvm/InitializePasses.h"
85 #include "llvm/Pass.h"
86 #include "llvm/PassRegistry.h"
87 #include "llvm/Support/Casting.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Errc.h"
90 #include "llvm/Support/Error.h"
91 #include "llvm/Support/FileSystem.h"
92 #include "llvm/Support/GlobPattern.h"
93 #include "llvm/Support/MathExtras.h"
94 #include "llvm/Transforms/IPO.h"
95 #include "llvm/Transforms/IPO/FunctionAttrs.h"
96 #include "llvm/Transforms/Utils/Evaluator.h"
97 #include <algorithm>
98 #include <cstddef>
99 #include <map>
100 #include <set>
101 #include <string>
102 
103 using namespace llvm;
104 using namespace wholeprogramdevirt;
105 
106 #define DEBUG_TYPE "wholeprogramdevirt"
107 
108 static cl::opt<PassSummaryAction> ClSummaryAction(
109     "wholeprogramdevirt-summary-action",
110     cl::desc("What to do with the summary when running this pass"),
111     cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
112                clEnumValN(PassSummaryAction::Import, "import",
113                           "Import typeid resolutions from summary and globals"),
114                clEnumValN(PassSummaryAction::Export, "export",
115                           "Export typeid resolutions to summary and globals")),
116     cl::Hidden);
117 
118 static cl::opt<std::string> ClReadSummary(
119     "wholeprogramdevirt-read-summary",
120     cl::desc(
121         "Read summary from given bitcode or YAML file before running pass"),
122     cl::Hidden);
123 
124 static cl::opt<std::string> ClWriteSummary(
125     "wholeprogramdevirt-write-summary",
126     cl::desc("Write summary to given bitcode or YAML file after running pass. "
127              "Output file format is deduced from extension: *.bc means writing "
128              "bitcode, otherwise YAML"),
129     cl::Hidden);
130 
131 static cl::opt<unsigned>
132     ClThreshold("wholeprogramdevirt-branch-funnel-threshold", cl::Hidden,
133                 cl::init(10), cl::ZeroOrMore,
134                 cl::desc("Maximum number of call targets per "
135                          "call site to enable branch funnels"));
136 
137 static cl::opt<bool>
138     PrintSummaryDevirt("wholeprogramdevirt-print-index-based", cl::Hidden,
139                        cl::init(false), cl::ZeroOrMore,
140                        cl::desc("Print index-based devirtualization messages"));
141 
142 /// Provide a way to force enable whole program visibility in tests.
143 /// This is needed to support legacy tests that don't contain
144 /// !vcall_visibility metadata (the mere presense of type tests
145 /// previously implied hidden visibility).
146 cl::opt<bool>
147     WholeProgramVisibility("whole-program-visibility", cl::init(false),
148                            cl::Hidden, cl::ZeroOrMore,
149                            cl::desc("Enable whole program visibility"));
150 
151 /// Provide a way to force disable whole program for debugging or workarounds,
152 /// when enabled via the linker.
153 cl::opt<bool> DisableWholeProgramVisibility(
154     "disable-whole-program-visibility", cl::init(false), cl::Hidden,
155     cl::ZeroOrMore,
156     cl::desc("Disable whole program visibility (overrides enabling options)"));
157 
158 /// Provide way to prevent certain function from being devirtualized
159 cl::list<std::string>
160     SkipFunctionNames("wholeprogramdevirt-skip",
161                       cl::desc("Prevent function(s) from being devirtualized"),
162                       cl::Hidden, cl::ZeroOrMore, cl::CommaSeparated);
163 
164 namespace {
165 struct PatternList {
166   std::vector<GlobPattern> Patterns;
167   template <class T> void init(const T &StringList) {
168     for (const auto &S : StringList)
169       if (Expected<GlobPattern> Pat = GlobPattern::create(S))
170         Patterns.push_back(std::move(*Pat));
171   }
172   bool match(StringRef S) {
173     for (const GlobPattern &P : Patterns)
174       if (P.match(S))
175         return true;
176     return false;
177   }
178 };
179 } // namespace
180 
181 // Find the minimum offset that we may store a value of size Size bits at. If
182 // IsAfter is set, look for an offset before the object, otherwise look for an
183 // offset after the object.
184 uint64_t
185 wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
186                                      bool IsAfter, uint64_t Size) {
187   // Find a minimum offset taking into account only vtable sizes.
188   uint64_t MinByte = 0;
189   for (const VirtualCallTarget &Target : Targets) {
190     if (IsAfter)
191       MinByte = std::max(MinByte, Target.minAfterBytes());
192     else
193       MinByte = std::max(MinByte, Target.minBeforeBytes());
194   }
195 
196   // Build a vector of arrays of bytes covering, for each target, a slice of the
197   // used region (see AccumBitVector::BytesUsed in
198   // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
199   // this aligns the used regions to start at MinByte.
200   //
201   // In this example, A, B and C are vtables, # is a byte already allocated for
202   // a virtual function pointer, AAAA... (etc.) are the used regions for the
203   // vtables and Offset(X) is the value computed for the Offset variable below
204   // for X.
205   //
206   //                    Offset(A)
207   //                    |       |
208   //                            |MinByte
209   // A: ################AAAAAAAA|AAAAAAAA
210   // B: ########BBBBBBBBBBBBBBBB|BBBB
211   // C: ########################|CCCCCCCCCCCCCCCC
212   //            |   Offset(B)   |
213   //
214   // This code produces the slices of A, B and C that appear after the divider
215   // at MinByte.
216   std::vector<ArrayRef<uint8_t>> Used;
217   for (const VirtualCallTarget &Target : Targets) {
218     ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
219                                        : Target.TM->Bits->Before.BytesUsed;
220     uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
221                               : MinByte - Target.minBeforeBytes();
222 
223     // Disregard used regions that are smaller than Offset. These are
224     // effectively all-free regions that do not need to be checked.
225     if (VTUsed.size() > Offset)
226       Used.push_back(VTUsed.slice(Offset));
227   }
228 
229   if (Size == 1) {
230     // Find a free bit in each member of Used.
231     for (unsigned I = 0;; ++I) {
232       uint8_t BitsUsed = 0;
233       for (auto &&B : Used)
234         if (I < B.size())
235           BitsUsed |= B[I];
236       if (BitsUsed != 0xff)
237         return (MinByte + I) * 8 +
238                countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
239     }
240   } else {
241     // Find a free (Size/8) byte region in each member of Used.
242     // FIXME: see if alignment helps.
243     for (unsigned I = 0;; ++I) {
244       for (auto &&B : Used) {
245         unsigned Byte = 0;
246         while ((I + Byte) < B.size() && Byte < (Size / 8)) {
247           if (B[I + Byte])
248             goto NextI;
249           ++Byte;
250         }
251       }
252       return (MinByte + I) * 8;
253     NextI:;
254     }
255   }
256 }
257 
258 void wholeprogramdevirt::setBeforeReturnValues(
259     MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
260     unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
261   if (BitWidth == 1)
262     OffsetByte = -(AllocBefore / 8 + 1);
263   else
264     OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
265   OffsetBit = AllocBefore % 8;
266 
267   for (VirtualCallTarget &Target : Targets) {
268     if (BitWidth == 1)
269       Target.setBeforeBit(AllocBefore);
270     else
271       Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
272   }
273 }
274 
275 void wholeprogramdevirt::setAfterReturnValues(
276     MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
277     unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
278   if (BitWidth == 1)
279     OffsetByte = AllocAfter / 8;
280   else
281     OffsetByte = (AllocAfter + 7) / 8;
282   OffsetBit = AllocAfter % 8;
283 
284   for (VirtualCallTarget &Target : Targets) {
285     if (BitWidth == 1)
286       Target.setAfterBit(AllocAfter);
287     else
288       Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
289   }
290 }
291 
292 VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
293     : Fn(Fn), TM(TM),
294       IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
295 
296 namespace {
297 
298 // A slot in a set of virtual tables. The TypeID identifies the set of virtual
299 // tables, and the ByteOffset is the offset in bytes from the address point to
300 // the virtual function pointer.
301 struct VTableSlot {
302   Metadata *TypeID;
303   uint64_t ByteOffset;
304 };
305 
306 } // end anonymous namespace
307 
308 namespace llvm {
309 
310 template <> struct DenseMapInfo<VTableSlot> {
311   static VTableSlot getEmptyKey() {
312     return {DenseMapInfo<Metadata *>::getEmptyKey(),
313             DenseMapInfo<uint64_t>::getEmptyKey()};
314   }
315   static VTableSlot getTombstoneKey() {
316     return {DenseMapInfo<Metadata *>::getTombstoneKey(),
317             DenseMapInfo<uint64_t>::getTombstoneKey()};
318   }
319   static unsigned getHashValue(const VTableSlot &I) {
320     return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
321            DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
322   }
323   static bool isEqual(const VTableSlot &LHS,
324                       const VTableSlot &RHS) {
325     return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
326   }
327 };
328 
329 template <> struct DenseMapInfo<VTableSlotSummary> {
330   static VTableSlotSummary getEmptyKey() {
331     return {DenseMapInfo<StringRef>::getEmptyKey(),
332             DenseMapInfo<uint64_t>::getEmptyKey()};
333   }
334   static VTableSlotSummary getTombstoneKey() {
335     return {DenseMapInfo<StringRef>::getTombstoneKey(),
336             DenseMapInfo<uint64_t>::getTombstoneKey()};
337   }
338   static unsigned getHashValue(const VTableSlotSummary &I) {
339     return DenseMapInfo<StringRef>::getHashValue(I.TypeID) ^
340            DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
341   }
342   static bool isEqual(const VTableSlotSummary &LHS,
343                       const VTableSlotSummary &RHS) {
344     return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
345   }
346 };
347 
348 } // end namespace llvm
349 
350 namespace {
351 
352 // A virtual call site. VTable is the loaded virtual table pointer, and CS is
353 // the indirect virtual call.
354 struct VirtualCallSite {
355   Value *VTable = nullptr;
356   CallBase &CB;
357 
358   // If non-null, this field points to the associated unsafe use count stored in
359   // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
360   // of that field for details.
361   unsigned *NumUnsafeUses = nullptr;
362 
363   void
364   emitRemark(const StringRef OptName, const StringRef TargetName,
365              function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
366     Function *F = CB.getCaller();
367     DebugLoc DLoc = CB.getDebugLoc();
368     BasicBlock *Block = CB.getParent();
369 
370     using namespace ore;
371     OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
372                       << NV("Optimization", OptName)
373                       << ": devirtualized a call to "
374                       << NV("FunctionName", TargetName));
375   }
376 
377   void replaceAndErase(
378       const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
379       function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
380       Value *New) {
381     if (RemarksEnabled)
382       emitRemark(OptName, TargetName, OREGetter);
383     CB.replaceAllUsesWith(New);
384     if (auto *II = dyn_cast<InvokeInst>(&CB)) {
385       BranchInst::Create(II->getNormalDest(), &CB);
386       II->getUnwindDest()->removePredecessor(II->getParent());
387     }
388     CB.eraseFromParent();
389     // This use is no longer unsafe.
390     if (NumUnsafeUses)
391       --*NumUnsafeUses;
392   }
393 };
394 
395 // Call site information collected for a specific VTableSlot and possibly a list
396 // of constant integer arguments. The grouping by arguments is handled by the
397 // VTableSlotInfo class.
398 struct CallSiteInfo {
399   /// The set of call sites for this slot. Used during regular LTO and the
400   /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
401   /// call sites that appear in the merged module itself); in each of these
402   /// cases we are directly operating on the call sites at the IR level.
403   std::vector<VirtualCallSite> CallSites;
404 
405   /// Whether all call sites represented by this CallSiteInfo, including those
406   /// in summaries, have been devirtualized. This starts off as true because a
407   /// default constructed CallSiteInfo represents no call sites.
408   bool AllCallSitesDevirted = true;
409 
410   // These fields are used during the export phase of ThinLTO and reflect
411   // information collected from function summaries.
412 
413   /// Whether any function summary contains an llvm.assume(llvm.type.test) for
414   /// this slot.
415   bool SummaryHasTypeTestAssumeUsers = false;
416 
417   /// CFI-specific: a vector containing the list of function summaries that use
418   /// the llvm.type.checked.load intrinsic and therefore will require
419   /// resolutions for llvm.type.test in order to implement CFI checks if
420   /// devirtualization was unsuccessful. If devirtualization was successful, the
421   /// pass will clear this vector by calling markDevirt(). If at the end of the
422   /// pass the vector is non-empty, we will need to add a use of llvm.type.test
423   /// to each of the function summaries in the vector.
424   std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
425   std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
426 
427   bool isExported() const {
428     return SummaryHasTypeTestAssumeUsers ||
429            !SummaryTypeCheckedLoadUsers.empty();
430   }
431 
432   void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
433     SummaryTypeCheckedLoadUsers.push_back(FS);
434     AllCallSitesDevirted = false;
435   }
436 
437   void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
438     SummaryTypeTestAssumeUsers.push_back(FS);
439     SummaryHasTypeTestAssumeUsers = true;
440     AllCallSitesDevirted = false;
441   }
442 
443   void markDevirt() {
444     AllCallSitesDevirted = true;
445 
446     // As explained in the comment for SummaryTypeCheckedLoadUsers.
447     SummaryTypeCheckedLoadUsers.clear();
448   }
449 };
450 
451 // Call site information collected for a specific VTableSlot.
452 struct VTableSlotInfo {
453   // The set of call sites which do not have all constant integer arguments
454   // (excluding "this").
455   CallSiteInfo CSInfo;
456 
457   // The set of call sites with all constant integer arguments (excluding
458   // "this"), grouped by argument list.
459   std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
460 
461   void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses);
462 
463 private:
464   CallSiteInfo &findCallSiteInfo(CallBase &CB);
465 };
466 
467 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) {
468   std::vector<uint64_t> Args;
469   auto *CBType = dyn_cast<IntegerType>(CB.getType());
470   if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty())
471     return CSInfo;
472   for (auto &&Arg : make_range(CB.arg_begin() + 1, CB.arg_end())) {
473     auto *CI = dyn_cast<ConstantInt>(Arg);
474     if (!CI || CI->getBitWidth() > 64)
475       return CSInfo;
476     Args.push_back(CI->getZExtValue());
477   }
478   return ConstCSInfo[Args];
479 }
480 
481 void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB,
482                                  unsigned *NumUnsafeUses) {
483   auto &CSI = findCallSiteInfo(CB);
484   CSI.AllCallSitesDevirted = false;
485   CSI.CallSites.push_back({VTable, CB, NumUnsafeUses});
486 }
487 
488 struct DevirtModule {
489   Module &M;
490   function_ref<AAResults &(Function &)> AARGetter;
491   function_ref<DominatorTree &(Function &)> LookupDomTree;
492 
493   ModuleSummaryIndex *ExportSummary;
494   const ModuleSummaryIndex *ImportSummary;
495 
496   IntegerType *Int8Ty;
497   PointerType *Int8PtrTy;
498   IntegerType *Int32Ty;
499   IntegerType *Int64Ty;
500   IntegerType *IntPtrTy;
501   /// Sizeless array type, used for imported vtables. This provides a signal
502   /// to analyzers that these imports may alias, as they do for example
503   /// when multiple unique return values occur in the same vtable.
504   ArrayType *Int8Arr0Ty;
505 
506   bool RemarksEnabled;
507   function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
508 
509   MapVector<VTableSlot, VTableSlotInfo> CallSlots;
510 
511   // This map keeps track of the number of "unsafe" uses of a loaded function
512   // pointer. The key is the associated llvm.type.test intrinsic call generated
513   // by this pass. An unsafe use is one that calls the loaded function pointer
514   // directly. Every time we eliminate an unsafe use (for example, by
515   // devirtualizing it or by applying virtual constant propagation), we
516   // decrement the value stored in this map. If a value reaches zero, we can
517   // eliminate the type check by RAUWing the associated llvm.type.test call with
518   // true.
519   std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
520   PatternList FunctionsToSkip;
521 
522   DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
523                function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
524                function_ref<DominatorTree &(Function &)> LookupDomTree,
525                ModuleSummaryIndex *ExportSummary,
526                const ModuleSummaryIndex *ImportSummary)
527       : M(M), AARGetter(AARGetter), LookupDomTree(LookupDomTree),
528         ExportSummary(ExportSummary), ImportSummary(ImportSummary),
529         Int8Ty(Type::getInt8Ty(M.getContext())),
530         Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
531         Int32Ty(Type::getInt32Ty(M.getContext())),
532         Int64Ty(Type::getInt64Ty(M.getContext())),
533         IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
534         Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)),
535         RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
536     assert(!(ExportSummary && ImportSummary));
537     FunctionsToSkip.init(SkipFunctionNames);
538   }
539 
540   bool areRemarksEnabled();
541 
542   void scanTypeTestUsers(Function *TypeTestFunc);
543   void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
544 
545   void buildTypeIdentifierMap(
546       std::vector<VTableBits> &Bits,
547       DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
548   bool
549   tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
550                             const std::set<TypeMemberInfo> &TypeMemberInfos,
551                             uint64_t ByteOffset);
552 
553   void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
554                              bool &IsExported);
555   bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
556                            MutableArrayRef<VirtualCallTarget> TargetsForSlot,
557                            VTableSlotInfo &SlotInfo,
558                            WholeProgramDevirtResolution *Res);
559 
560   void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Constant *JT,
561                               bool &IsExported);
562   void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
563                             VTableSlotInfo &SlotInfo,
564                             WholeProgramDevirtResolution *Res, VTableSlot Slot);
565 
566   bool tryEvaluateFunctionsWithArgs(
567       MutableArrayRef<VirtualCallTarget> TargetsForSlot,
568       ArrayRef<uint64_t> Args);
569 
570   void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
571                              uint64_t TheRetVal);
572   bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
573                            CallSiteInfo &CSInfo,
574                            WholeProgramDevirtResolution::ByArg *Res);
575 
576   // Returns the global symbol name that is used to export information about the
577   // given vtable slot and list of arguments.
578   std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
579                             StringRef Name);
580 
581   bool shouldExportConstantsAsAbsoluteSymbols();
582 
583   // This function is called during the export phase to create a symbol
584   // definition containing information about the given vtable slot and list of
585   // arguments.
586   void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
587                     Constant *C);
588   void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
589                       uint32_t Const, uint32_t &Storage);
590 
591   // This function is called during the import phase to create a reference to
592   // the symbol definition created during the export phase.
593   Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
594                          StringRef Name);
595   Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
596                            StringRef Name, IntegerType *IntTy,
597                            uint32_t Storage);
598 
599   Constant *getMemberAddr(const TypeMemberInfo *M);
600 
601   void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
602                             Constant *UniqueMemberAddr);
603   bool tryUniqueRetValOpt(unsigned BitWidth,
604                           MutableArrayRef<VirtualCallTarget> TargetsForSlot,
605                           CallSiteInfo &CSInfo,
606                           WholeProgramDevirtResolution::ByArg *Res,
607                           VTableSlot Slot, ArrayRef<uint64_t> Args);
608 
609   void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
610                              Constant *Byte, Constant *Bit);
611   bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
612                            VTableSlotInfo &SlotInfo,
613                            WholeProgramDevirtResolution *Res, VTableSlot Slot);
614 
615   void rebuildGlobal(VTableBits &B);
616 
617   // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
618   void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
619 
620   // If we were able to eliminate all unsafe uses for a type checked load,
621   // eliminate the associated type tests by replacing them with true.
622   void removeRedundantTypeTests();
623 
624   bool run();
625 
626   // Lower the module using the action and summary passed as command line
627   // arguments. For testing purposes only.
628   static bool
629   runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
630                 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
631                 function_ref<DominatorTree &(Function &)> LookupDomTree);
632 };
633 
634 struct DevirtIndex {
635   ModuleSummaryIndex &ExportSummary;
636   // The set in which to record GUIDs exported from their module by
637   // devirtualization, used by client to ensure they are not internalized.
638   std::set<GlobalValue::GUID> &ExportedGUIDs;
639   // A map in which to record the information necessary to locate the WPD
640   // resolution for local targets in case they are exported by cross module
641   // importing.
642   std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
643 
644   MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
645 
646   PatternList FunctionsToSkip;
647 
648   DevirtIndex(
649       ModuleSummaryIndex &ExportSummary,
650       std::set<GlobalValue::GUID> &ExportedGUIDs,
651       std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap)
652       : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
653         LocalWPDTargetsMap(LocalWPDTargetsMap) {
654     FunctionsToSkip.init(SkipFunctionNames);
655   }
656 
657   bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
658                                  const TypeIdCompatibleVtableInfo TIdInfo,
659                                  uint64_t ByteOffset);
660 
661   bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
662                            VTableSlotSummary &SlotSummary,
663                            VTableSlotInfo &SlotInfo,
664                            WholeProgramDevirtResolution *Res,
665                            std::set<ValueInfo> &DevirtTargets);
666 
667   void run();
668 };
669 
670 struct WholeProgramDevirt : public ModulePass {
671   static char ID;
672 
673   bool UseCommandLine = false;
674 
675   ModuleSummaryIndex *ExportSummary = nullptr;
676   const ModuleSummaryIndex *ImportSummary = nullptr;
677 
678   WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
679     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
680   }
681 
682   WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
683                      const ModuleSummaryIndex *ImportSummary)
684       : ModulePass(ID), ExportSummary(ExportSummary),
685         ImportSummary(ImportSummary) {
686     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
687   }
688 
689   bool runOnModule(Module &M) override {
690     if (skipModule(M))
691       return false;
692 
693     // In the new pass manager, we can request the optimization
694     // remark emitter pass on a per-function-basis, which the
695     // OREGetter will do for us.
696     // In the old pass manager, this is harder, so we just build
697     // an optimization remark emitter on the fly, when we need it.
698     std::unique_ptr<OptimizationRemarkEmitter> ORE;
699     auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
700       ORE = std::make_unique<OptimizationRemarkEmitter>(F);
701       return *ORE;
702     };
703 
704     auto LookupDomTree = [this](Function &F) -> DominatorTree & {
705       return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
706     };
707 
708     if (UseCommandLine)
709       return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter,
710                                          LookupDomTree);
711 
712     return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree,
713                         ExportSummary, ImportSummary)
714         .run();
715   }
716 
717   void getAnalysisUsage(AnalysisUsage &AU) const override {
718     AU.addRequired<AssumptionCacheTracker>();
719     AU.addRequired<TargetLibraryInfoWrapperPass>();
720     AU.addRequired<DominatorTreeWrapperPass>();
721   }
722 };
723 
724 } // end anonymous namespace
725 
726 INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
727                       "Whole program devirtualization", false, false)
728 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
729 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
730 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
731 INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
732                     "Whole program devirtualization", false, false)
733 char WholeProgramDevirt::ID = 0;
734 
735 ModulePass *
736 llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
737                                    const ModuleSummaryIndex *ImportSummary) {
738   return new WholeProgramDevirt(ExportSummary, ImportSummary);
739 }
740 
741 PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
742                                               ModuleAnalysisManager &AM) {
743   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
744   auto AARGetter = [&](Function &F) -> AAResults & {
745     return FAM.getResult<AAManager>(F);
746   };
747   auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
748     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
749   };
750   auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
751     return FAM.getResult<DominatorTreeAnalysis>(F);
752   };
753   if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
754                     ImportSummary)
755            .run())
756     return PreservedAnalyses::all();
757   return PreservedAnalyses::none();
758 }
759 
760 // Enable whole program visibility if enabled by client (e.g. linker) or
761 // internal option, and not force disabled.
762 static bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) {
763   return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) &&
764          !DisableWholeProgramVisibility;
765 }
766 
767 namespace llvm {
768 
769 /// If whole program visibility asserted, then upgrade all public vcall
770 /// visibility metadata on vtable definitions to linkage unit visibility in
771 /// Module IR (for regular or hybrid LTO).
772 void updateVCallVisibilityInModule(Module &M,
773                                    bool WholeProgramVisibilityEnabledInLTO) {
774   if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
775     return;
776   for (GlobalVariable &GV : M.globals())
777     // Add linkage unit visibility to any variable with type metadata, which are
778     // the vtable definitions. We won't have an existing vcall_visibility
779     // metadata on vtable definitions with public visibility.
780     if (GV.hasMetadata(LLVMContext::MD_type) &&
781         GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
782       GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit);
783 }
784 
785 /// If whole program visibility asserted, then upgrade all public vcall
786 /// visibility metadata on vtable definition summaries to linkage unit
787 /// visibility in Module summary index (for ThinLTO).
788 void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index,
789                                   bool WholeProgramVisibilityEnabledInLTO) {
790   if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
791     return;
792   for (auto &P : Index) {
793     for (auto &S : P.second.SummaryList) {
794       auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
795       if (!GVar || GVar->vTableFuncs().empty() ||
796           GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic)
797         continue;
798       GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
799     }
800   }
801 }
802 
803 void runWholeProgramDevirtOnIndex(
804     ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
805     std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
806   DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run();
807 }
808 
809 void updateIndexWPDForExports(
810     ModuleSummaryIndex &Summary,
811     function_ref<bool(StringRef, ValueInfo)> isExported,
812     std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
813   for (auto &T : LocalWPDTargetsMap) {
814     auto &VI = T.first;
815     // This was enforced earlier during trySingleImplDevirt.
816     assert(VI.getSummaryList().size() == 1 &&
817            "Devirt of local target has more than one copy");
818     auto &S = VI.getSummaryList()[0];
819     if (!isExported(S->modulePath(), VI))
820       continue;
821 
822     // It's been exported by a cross module import.
823     for (auto &SlotSummary : T.second) {
824       auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
825       assert(TIdSum);
826       auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
827       assert(WPDRes != TIdSum->WPDRes.end());
828       WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
829           WPDRes->second.SingleImplName,
830           Summary.getModuleHash(S->modulePath()));
831     }
832   }
833 }
834 
835 } // end namespace llvm
836 
837 static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) {
838   // Check that summary index contains regular LTO module when performing
839   // export to prevent occasional use of index from pure ThinLTO compilation
840   // (-fno-split-lto-module). This kind of summary index is passed to
841   // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
842   const auto &ModPaths = Summary->modulePaths();
843   if (ClSummaryAction != PassSummaryAction::Import &&
844       ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) ==
845           ModPaths.end())
846     return createStringError(
847         errc::invalid_argument,
848         "combined summary should contain Regular LTO module");
849   return ErrorSuccess();
850 }
851 
852 bool DevirtModule::runForTesting(
853     Module &M, function_ref<AAResults &(Function &)> AARGetter,
854     function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
855     function_ref<DominatorTree &(Function &)> LookupDomTree) {
856   std::unique_ptr<ModuleSummaryIndex> Summary =
857       std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
858 
859   // Handle the command-line summary arguments. This code is for testing
860   // purposes only, so we handle errors directly.
861   if (!ClReadSummary.empty()) {
862     ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
863                           ": ");
864     auto ReadSummaryFile =
865         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
866     if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
867             getModuleSummaryIndex(*ReadSummaryFile)) {
868       Summary = std::move(*SummaryOrErr);
869       ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
870     } else {
871       // Try YAML if we've failed with bitcode.
872       consumeError(SummaryOrErr.takeError());
873       yaml::Input In(ReadSummaryFile->getBuffer());
874       In >> *Summary;
875       ExitOnErr(errorCodeToError(In.error()));
876     }
877   }
878 
879   bool Changed =
880       DevirtModule(M, AARGetter, OREGetter, LookupDomTree,
881                    ClSummaryAction == PassSummaryAction::Export ? Summary.get()
882                                                                 : nullptr,
883                    ClSummaryAction == PassSummaryAction::Import ? Summary.get()
884                                                                 : nullptr)
885           .run();
886 
887   if (!ClWriteSummary.empty()) {
888     ExitOnError ExitOnErr(
889         "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
890     std::error_code EC;
891     if (StringRef(ClWriteSummary).endswith(".bc")) {
892       raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
893       ExitOnErr(errorCodeToError(EC));
894       WriteIndexToFile(*Summary, OS);
895     } else {
896       raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_Text);
897       ExitOnErr(errorCodeToError(EC));
898       yaml::Output Out(OS);
899       Out << *Summary;
900     }
901   }
902 
903   return Changed;
904 }
905 
906 void DevirtModule::buildTypeIdentifierMap(
907     std::vector<VTableBits> &Bits,
908     DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
909   DenseMap<GlobalVariable *, VTableBits *> GVToBits;
910   Bits.reserve(M.getGlobalList().size());
911   SmallVector<MDNode *, 2> Types;
912   for (GlobalVariable &GV : M.globals()) {
913     Types.clear();
914     GV.getMetadata(LLVMContext::MD_type, Types);
915     if (GV.isDeclaration() || Types.empty())
916       continue;
917 
918     VTableBits *&BitsPtr = GVToBits[&GV];
919     if (!BitsPtr) {
920       Bits.emplace_back();
921       Bits.back().GV = &GV;
922       Bits.back().ObjectSize =
923           M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
924       BitsPtr = &Bits.back();
925     }
926 
927     for (MDNode *Type : Types) {
928       auto TypeID = Type->getOperand(1).get();
929 
930       uint64_t Offset =
931           cast<ConstantInt>(
932               cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
933               ->getZExtValue();
934 
935       TypeIdMap[TypeID].insert({BitsPtr, Offset});
936     }
937   }
938 }
939 
940 bool DevirtModule::tryFindVirtualCallTargets(
941     std::vector<VirtualCallTarget> &TargetsForSlot,
942     const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
943   for (const TypeMemberInfo &TM : TypeMemberInfos) {
944     if (!TM.Bits->GV->isConstant())
945       return false;
946 
947     // We cannot perform whole program devirtualization analysis on a vtable
948     // with public LTO visibility.
949     if (TM.Bits->GV->getVCallVisibility() ==
950         GlobalObject::VCallVisibilityPublic)
951       return false;
952 
953     Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
954                                        TM.Offset + ByteOffset, M);
955     if (!Ptr)
956       return false;
957 
958     auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
959     if (!Fn)
960       return false;
961 
962     if (FunctionsToSkip.match(Fn->getName()))
963       return false;
964 
965     // We can disregard __cxa_pure_virtual as a possible call target, as
966     // calls to pure virtuals are UB.
967     if (Fn->getName() == "__cxa_pure_virtual")
968       continue;
969 
970     TargetsForSlot.push_back({Fn, &TM});
971   }
972 
973   // Give up if we couldn't find any targets.
974   return !TargetsForSlot.empty();
975 }
976 
977 bool DevirtIndex::tryFindVirtualCallTargets(
978     std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo,
979     uint64_t ByteOffset) {
980   for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
981     // Find the first non-available_externally linkage vtable initializer.
982     // We can have multiple available_externally, linkonce_odr and weak_odr
983     // vtable initializers, however we want to skip available_externally as they
984     // do not have type metadata attached, and therefore the summary will not
985     // contain any vtable functions. We can also have multiple external
986     // vtable initializers in the case of comdats, which we cannot check here.
987     // The linker should give an error in this case.
988     //
989     // Also, handle the case of same-named local Vtables with the same path
990     // and therefore the same GUID. This can happen if there isn't enough
991     // distinguishing path when compiling the source file. In that case we
992     // conservatively return false early.
993     const GlobalVarSummary *VS = nullptr;
994     bool LocalFound = false;
995     for (auto &S : P.VTableVI.getSummaryList()) {
996       if (GlobalValue::isLocalLinkage(S->linkage())) {
997         if (LocalFound)
998           return false;
999         LocalFound = true;
1000       }
1001       if (!GlobalValue::isAvailableExternallyLinkage(S->linkage())) {
1002         VS = cast<GlobalVarSummary>(S->getBaseObject());
1003         // We cannot perform whole program devirtualization analysis on a vtable
1004         // with public LTO visibility.
1005         if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
1006           return false;
1007       }
1008     }
1009     if (!VS->isLive())
1010       continue;
1011     for (auto VTP : VS->vTableFuncs()) {
1012       if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
1013         continue;
1014 
1015       TargetsForSlot.push_back(VTP.FuncVI);
1016     }
1017   }
1018 
1019   // Give up if we couldn't find any targets.
1020   return !TargetsForSlot.empty();
1021 }
1022 
1023 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
1024                                          Constant *TheFn, bool &IsExported) {
1025   auto Apply = [&](CallSiteInfo &CSInfo) {
1026     for (auto &&VCallSite : CSInfo.CallSites) {
1027       if (RemarksEnabled)
1028         VCallSite.emitRemark("single-impl",
1029                              TheFn->stripPointerCasts()->getName(), OREGetter);
1030       VCallSite.CB.setCalledOperand(ConstantExpr::getBitCast(
1031           TheFn, VCallSite.CB.getCalledOperand()->getType()));
1032       // This use is no longer unsafe.
1033       if (VCallSite.NumUnsafeUses)
1034         --*VCallSite.NumUnsafeUses;
1035     }
1036     if (CSInfo.isExported())
1037       IsExported = true;
1038     CSInfo.markDevirt();
1039   };
1040   Apply(SlotInfo.CSInfo);
1041   for (auto &P : SlotInfo.ConstCSInfo)
1042     Apply(P.second);
1043 }
1044 
1045 static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
1046   // We can't add calls if we haven't seen a definition
1047   if (Callee.getSummaryList().empty())
1048     return false;
1049 
1050   // Insert calls into the summary index so that the devirtualized targets
1051   // are eligible for import.
1052   // FIXME: Annotate type tests with hotness. For now, mark these as hot
1053   // to better ensure we have the opportunity to inline them.
1054   bool IsExported = false;
1055   auto &S = Callee.getSummaryList()[0];
1056   CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0);
1057   auto AddCalls = [&](CallSiteInfo &CSInfo) {
1058     for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
1059       FS->addCall({Callee, CI});
1060       IsExported |= S->modulePath() != FS->modulePath();
1061     }
1062     for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
1063       FS->addCall({Callee, CI});
1064       IsExported |= S->modulePath() != FS->modulePath();
1065     }
1066   };
1067   AddCalls(SlotInfo.CSInfo);
1068   for (auto &P : SlotInfo.ConstCSInfo)
1069     AddCalls(P.second);
1070   return IsExported;
1071 }
1072 
1073 bool DevirtModule::trySingleImplDevirt(
1074     ModuleSummaryIndex *ExportSummary,
1075     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1076     WholeProgramDevirtResolution *Res) {
1077   // See if the program contains a single implementation of this virtual
1078   // function.
1079   Function *TheFn = TargetsForSlot[0].Fn;
1080   for (auto &&Target : TargetsForSlot)
1081     if (TheFn != Target.Fn)
1082       return false;
1083 
1084   // If so, update each call site to call that implementation directly.
1085   if (RemarksEnabled)
1086     TargetsForSlot[0].WasDevirt = true;
1087 
1088   bool IsExported = false;
1089   applySingleImplDevirt(SlotInfo, TheFn, IsExported);
1090   if (!IsExported)
1091     return false;
1092 
1093   // If the only implementation has local linkage, we must promote to external
1094   // to make it visible to thin LTO objects. We can only get here during the
1095   // ThinLTO export phase.
1096   if (TheFn->hasLocalLinkage()) {
1097     std::string NewName = (TheFn->getName() + "$merged").str();
1098 
1099     // Since we are renaming the function, any comdats with the same name must
1100     // also be renamed. This is required when targeting COFF, as the comdat name
1101     // must match one of the names of the symbols in the comdat.
1102     if (Comdat *C = TheFn->getComdat()) {
1103       if (C->getName() == TheFn->getName()) {
1104         Comdat *NewC = M.getOrInsertComdat(NewName);
1105         NewC->setSelectionKind(C->getSelectionKind());
1106         for (GlobalObject &GO : M.global_objects())
1107           if (GO.getComdat() == C)
1108             GO.setComdat(NewC);
1109       }
1110     }
1111 
1112     TheFn->setLinkage(GlobalValue::ExternalLinkage);
1113     TheFn->setVisibility(GlobalValue::HiddenVisibility);
1114     TheFn->setName(NewName);
1115   }
1116   if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
1117     // Any needed promotion of 'TheFn' has already been done during
1118     // LTO unit split, so we can ignore return value of AddCalls.
1119     AddCalls(SlotInfo, TheFnVI);
1120 
1121   Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1122   Res->SingleImplName = std::string(TheFn->getName());
1123 
1124   return true;
1125 }
1126 
1127 bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
1128                                       VTableSlotSummary &SlotSummary,
1129                                       VTableSlotInfo &SlotInfo,
1130                                       WholeProgramDevirtResolution *Res,
1131                                       std::set<ValueInfo> &DevirtTargets) {
1132   // See if the program contains a single implementation of this virtual
1133   // function.
1134   auto TheFn = TargetsForSlot[0];
1135   for (auto &&Target : TargetsForSlot)
1136     if (TheFn != Target)
1137       return false;
1138 
1139   // Don't devirtualize if we don't have target definition.
1140   auto Size = TheFn.getSummaryList().size();
1141   if (!Size)
1142     return false;
1143 
1144   // Don't devirtualize function if we're told to skip it
1145   // in -wholeprogramdevirt-skip.
1146   if (FunctionsToSkip.match(TheFn.name()))
1147     return false;
1148 
1149   // If the summary list contains multiple summaries where at least one is
1150   // a local, give up, as we won't know which (possibly promoted) name to use.
1151   for (auto &S : TheFn.getSummaryList())
1152     if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1)
1153       return false;
1154 
1155   // Collect functions devirtualized at least for one call site for stats.
1156   if (PrintSummaryDevirt)
1157     DevirtTargets.insert(TheFn);
1158 
1159   auto &S = TheFn.getSummaryList()[0];
1160   bool IsExported = AddCalls(SlotInfo, TheFn);
1161   if (IsExported)
1162     ExportedGUIDs.insert(TheFn.getGUID());
1163 
1164   // Record in summary for use in devirtualization during the ThinLTO import
1165   // step.
1166   Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1167   if (GlobalValue::isLocalLinkage(S->linkage())) {
1168     if (IsExported)
1169       // If target is a local function and we are exporting it by
1170       // devirtualizing a call in another module, we need to record the
1171       // promoted name.
1172       Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
1173           TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
1174     else {
1175       LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1176       Res->SingleImplName = std::string(TheFn.name());
1177     }
1178   } else
1179     Res->SingleImplName = std::string(TheFn.name());
1180 
1181   // Name will be empty if this thin link driven off of serialized combined
1182   // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
1183   // legacy LTO API anyway.
1184   assert(!Res->SingleImplName.empty());
1185 
1186   return true;
1187 }
1188 
1189 void DevirtModule::tryICallBranchFunnel(
1190     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1191     WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1192   Triple T(M.getTargetTriple());
1193   if (T.getArch() != Triple::x86_64)
1194     return;
1195 
1196   if (TargetsForSlot.size() > ClThreshold)
1197     return;
1198 
1199   bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1200   if (!HasNonDevirt)
1201     for (auto &P : SlotInfo.ConstCSInfo)
1202       if (!P.second.AllCallSitesDevirted) {
1203         HasNonDevirt = true;
1204         break;
1205       }
1206 
1207   if (!HasNonDevirt)
1208     return;
1209 
1210   FunctionType *FT =
1211       FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
1212   Function *JT;
1213   if (isa<MDString>(Slot.TypeID)) {
1214     JT = Function::Create(FT, Function::ExternalLinkage,
1215                           M.getDataLayout().getProgramAddressSpace(),
1216                           getGlobalName(Slot, {}, "branch_funnel"), &M);
1217     JT->setVisibility(GlobalValue::HiddenVisibility);
1218   } else {
1219     JT = Function::Create(FT, Function::InternalLinkage,
1220                           M.getDataLayout().getProgramAddressSpace(),
1221                           "branch_funnel", &M);
1222   }
1223   JT->addAttribute(1, Attribute::Nest);
1224 
1225   std::vector<Value *> JTArgs;
1226   JTArgs.push_back(JT->arg_begin());
1227   for (auto &T : TargetsForSlot) {
1228     JTArgs.push_back(getMemberAddr(T.TM));
1229     JTArgs.push_back(T.Fn);
1230   }
1231 
1232   BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
1233   Function *Intr =
1234       Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
1235 
1236   auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
1237   CI->setTailCallKind(CallInst::TCK_MustTail);
1238   ReturnInst::Create(M.getContext(), nullptr, BB);
1239 
1240   bool IsExported = false;
1241   applyICallBranchFunnel(SlotInfo, JT, IsExported);
1242   if (IsExported)
1243     Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
1244 }
1245 
1246 void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1247                                           Constant *JT, bool &IsExported) {
1248   auto Apply = [&](CallSiteInfo &CSInfo) {
1249     if (CSInfo.isExported())
1250       IsExported = true;
1251     if (CSInfo.AllCallSitesDevirted)
1252       return;
1253     for (auto &&VCallSite : CSInfo.CallSites) {
1254       CallBase &CB = VCallSite.CB;
1255 
1256       // Jump tables are only profitable if the retpoline mitigation is enabled.
1257       Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features");
1258       if (FSAttr.hasAttribute(Attribute::None) ||
1259           !FSAttr.getValueAsString().contains("+retpoline"))
1260         continue;
1261 
1262       if (RemarksEnabled)
1263         VCallSite.emitRemark("branch-funnel",
1264                              JT->stripPointerCasts()->getName(), OREGetter);
1265 
1266       // Pass the address of the vtable in the nest register, which is r10 on
1267       // x86_64.
1268       std::vector<Type *> NewArgs;
1269       NewArgs.push_back(Int8PtrTy);
1270       for (Type *T : CB.getFunctionType()->params())
1271         NewArgs.push_back(T);
1272       FunctionType *NewFT =
1273           FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs,
1274                             CB.getFunctionType()->isVarArg());
1275       PointerType *NewFTPtr = PointerType::getUnqual(NewFT);
1276 
1277       IRBuilder<> IRB(&CB);
1278       std::vector<Value *> Args;
1279       Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
1280       Args.insert(Args.end(), CB.arg_begin(), CB.arg_end());
1281 
1282       CallBase *NewCS = nullptr;
1283       if (isa<CallInst>(CB))
1284         NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args);
1285       else
1286         NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr),
1287                                  cast<InvokeInst>(CB).getNormalDest(),
1288                                  cast<InvokeInst>(CB).getUnwindDest(), Args);
1289       NewCS->setCallingConv(CB.getCallingConv());
1290 
1291       AttributeList Attrs = CB.getAttributes();
1292       std::vector<AttributeSet> NewArgAttrs;
1293       NewArgAttrs.push_back(AttributeSet::get(
1294           M.getContext(), ArrayRef<Attribute>{Attribute::get(
1295                               M.getContext(), Attribute::Nest)}));
1296       for (unsigned I = 0; I + 2 <  Attrs.getNumAttrSets(); ++I)
1297         NewArgAttrs.push_back(Attrs.getParamAttributes(I));
1298       NewCS->setAttributes(
1299           AttributeList::get(M.getContext(), Attrs.getFnAttributes(),
1300                              Attrs.getRetAttributes(), NewArgAttrs));
1301 
1302       CB.replaceAllUsesWith(NewCS);
1303       CB.eraseFromParent();
1304 
1305       // This use is no longer unsafe.
1306       if (VCallSite.NumUnsafeUses)
1307         --*VCallSite.NumUnsafeUses;
1308     }
1309     // Don't mark as devirtualized because there may be callers compiled without
1310     // retpoline mitigation, which would mean that they are lowered to
1311     // llvm.type.test and therefore require an llvm.type.test resolution for the
1312     // type identifier.
1313   };
1314   Apply(SlotInfo.CSInfo);
1315   for (auto &P : SlotInfo.ConstCSInfo)
1316     Apply(P.second);
1317 }
1318 
1319 bool DevirtModule::tryEvaluateFunctionsWithArgs(
1320     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
1321     ArrayRef<uint64_t> Args) {
1322   // Evaluate each function and store the result in each target's RetVal
1323   // field.
1324   for (VirtualCallTarget &Target : TargetsForSlot) {
1325     if (Target.Fn->arg_size() != Args.size() + 1)
1326       return false;
1327 
1328     Evaluator Eval(M.getDataLayout(), nullptr);
1329     SmallVector<Constant *, 2> EvalArgs;
1330     EvalArgs.push_back(
1331         Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
1332     for (unsigned I = 0; I != Args.size(); ++I) {
1333       auto *ArgTy = dyn_cast<IntegerType>(
1334           Target.Fn->getFunctionType()->getParamType(I + 1));
1335       if (!ArgTy)
1336         return false;
1337       EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
1338     }
1339 
1340     Constant *RetVal;
1341     if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
1342         !isa<ConstantInt>(RetVal))
1343       return false;
1344     Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
1345   }
1346   return true;
1347 }
1348 
1349 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1350                                          uint64_t TheRetVal) {
1351   for (auto Call : CSInfo.CallSites)
1352     Call.replaceAndErase(
1353         "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
1354         ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal));
1355   CSInfo.markDevirt();
1356 }
1357 
1358 bool DevirtModule::tryUniformRetValOpt(
1359     MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1360     WholeProgramDevirtResolution::ByArg *Res) {
1361   // Uniform return value optimization. If all functions return the same
1362   // constant, replace all calls with that constant.
1363   uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1364   for (const VirtualCallTarget &Target : TargetsForSlot)
1365     if (Target.RetVal != TheRetVal)
1366       return false;
1367 
1368   if (CSInfo.isExported()) {
1369     Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
1370     Res->Info = TheRetVal;
1371   }
1372 
1373   applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
1374   if (RemarksEnabled)
1375     for (auto &&Target : TargetsForSlot)
1376       Target.WasDevirt = true;
1377   return true;
1378 }
1379 
1380 std::string DevirtModule::getGlobalName(VTableSlot Slot,
1381                                         ArrayRef<uint64_t> Args,
1382                                         StringRef Name) {
1383   std::string FullName = "__typeid_";
1384   raw_string_ostream OS(FullName);
1385   OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1386   for (uint64_t Arg : Args)
1387     OS << '_' << Arg;
1388   OS << '_' << Name;
1389   return OS.str();
1390 }
1391 
1392 bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1393   Triple T(M.getTargetTriple());
1394   return T.isX86() && T.getObjectFormat() == Triple::ELF;
1395 }
1396 
1397 void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1398                                 StringRef Name, Constant *C) {
1399   GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1400                                         getGlobalName(Slot, Args, Name), C, &M);
1401   GA->setVisibility(GlobalValue::HiddenVisibility);
1402 }
1403 
1404 void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1405                                   StringRef Name, uint32_t Const,
1406                                   uint32_t &Storage) {
1407   if (shouldExportConstantsAsAbsoluteSymbols()) {
1408     exportGlobal(
1409         Slot, Args, Name,
1410         ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1411     return;
1412   }
1413 
1414   Storage = Const;
1415 }
1416 
1417 Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1418                                      StringRef Name) {
1419   Constant *C =
1420       M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
1421   auto *GV = dyn_cast<GlobalVariable>(C);
1422   if (GV)
1423     GV->setVisibility(GlobalValue::HiddenVisibility);
1424   return C;
1425 }
1426 
1427 Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1428                                        StringRef Name, IntegerType *IntTy,
1429                                        uint32_t Storage) {
1430   if (!shouldExportConstantsAsAbsoluteSymbols())
1431     return ConstantInt::get(IntTy, Storage);
1432 
1433   Constant *C = importGlobal(Slot, Args, Name);
1434   auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1435   C = ConstantExpr::getPtrToInt(C, IntTy);
1436 
1437   // We only need to set metadata if the global is newly created, in which
1438   // case it would not have hidden visibility.
1439   if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
1440     return C;
1441 
1442   auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1443     auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1444     auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1445     GV->setMetadata(LLVMContext::MD_absolute_symbol,
1446                     MDNode::get(M.getContext(), {MinC, MaxC}));
1447   };
1448   unsigned AbsWidth = IntTy->getBitWidth();
1449   if (AbsWidth == IntPtrTy->getBitWidth())
1450     SetAbsRange(~0ull, ~0ull); // Full set.
1451   else
1452     SetAbsRange(0, 1ull << AbsWidth);
1453   return C;
1454 }
1455 
1456 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1457                                         bool IsOne,
1458                                         Constant *UniqueMemberAddr) {
1459   for (auto &&Call : CSInfo.CallSites) {
1460     IRBuilder<> B(&Call.CB);
1461     Value *Cmp =
1462         B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable,
1463                      B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType()));
1464     Cmp = B.CreateZExt(Cmp, Call.CB.getType());
1465     Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1466                          Cmp);
1467   }
1468   CSInfo.markDevirt();
1469 }
1470 
1471 Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1472   Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1473   return ConstantExpr::getGetElementPtr(Int8Ty, C,
1474                                         ConstantInt::get(Int64Ty, M->Offset));
1475 }
1476 
1477 bool DevirtModule::tryUniqueRetValOpt(
1478     unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
1479     CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1480     VTableSlot Slot, ArrayRef<uint64_t> Args) {
1481   // IsOne controls whether we look for a 0 or a 1.
1482   auto tryUniqueRetValOptFor = [&](bool IsOne) {
1483     const TypeMemberInfo *UniqueMember = nullptr;
1484     for (const VirtualCallTarget &Target : TargetsForSlot) {
1485       if (Target.RetVal == (IsOne ? 1 : 0)) {
1486         if (UniqueMember)
1487           return false;
1488         UniqueMember = Target.TM;
1489       }
1490     }
1491 
1492     // We should have found a unique member or bailed out by now. We already
1493     // checked for a uniform return value in tryUniformRetValOpt.
1494     assert(UniqueMember);
1495 
1496     Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
1497     if (CSInfo.isExported()) {
1498       Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1499       Res->Info = IsOne;
1500 
1501       exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1502     }
1503 
1504     // Replace each call with the comparison.
1505     applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1506                          UniqueMemberAddr);
1507 
1508     // Update devirtualization statistics for targets.
1509     if (RemarksEnabled)
1510       for (auto &&Target : TargetsForSlot)
1511         Target.WasDevirt = true;
1512 
1513     return true;
1514   };
1515 
1516   if (BitWidth == 1) {
1517     if (tryUniqueRetValOptFor(true))
1518       return true;
1519     if (tryUniqueRetValOptFor(false))
1520       return true;
1521   }
1522   return false;
1523 }
1524 
1525 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1526                                          Constant *Byte, Constant *Bit) {
1527   for (auto Call : CSInfo.CallSites) {
1528     auto *RetType = cast<IntegerType>(Call.CB.getType());
1529     IRBuilder<> B(&Call.CB);
1530     Value *Addr =
1531         B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
1532     if (RetType->getBitWidth() == 1) {
1533       Value *Bits = B.CreateLoad(Int8Ty, Addr);
1534       Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1535       auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1536       Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
1537                            OREGetter, IsBitSet);
1538     } else {
1539       Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1540       Value *Val = B.CreateLoad(RetType, ValAddr);
1541       Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1542                            OREGetter, Val);
1543     }
1544   }
1545   CSInfo.markDevirt();
1546 }
1547 
1548 bool DevirtModule::tryVirtualConstProp(
1549     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1550     WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1551   // This only works if the function returns an integer.
1552   auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1553   if (!RetType)
1554     return false;
1555   unsigned BitWidth = RetType->getBitWidth();
1556   if (BitWidth > 64)
1557     return false;
1558 
1559   // Make sure that each function is defined, does not access memory, takes at
1560   // least one argument, does not use its first argument (which we assume is
1561   // 'this'), and has the same return type.
1562   //
1563   // Note that we test whether this copy of the function is readnone, rather
1564   // than testing function attributes, which must hold for any copy of the
1565   // function, even a less optimized version substituted at link time. This is
1566   // sound because the virtual constant propagation optimizations effectively
1567   // inline all implementations of the virtual function into each call site,
1568   // rather than using function attributes to perform local optimization.
1569   for (VirtualCallTarget &Target : TargetsForSlot) {
1570     if (Target.Fn->isDeclaration() ||
1571         computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1572             MAK_ReadNone ||
1573         Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
1574         Target.Fn->getReturnType() != RetType)
1575       return false;
1576   }
1577 
1578   for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1579     if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1580       continue;
1581 
1582     WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1583     if (Res)
1584       ResByArg = &Res->ResByArg[CSByConstantArg.first];
1585 
1586     if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1587       continue;
1588 
1589     if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1590                            ResByArg, Slot, CSByConstantArg.first))
1591       continue;
1592 
1593     // Find an allocation offset in bits in all vtables associated with the
1594     // type.
1595     uint64_t AllocBefore =
1596         findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1597     uint64_t AllocAfter =
1598         findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1599 
1600     // Calculate the total amount of padding needed to store a value at both
1601     // ends of the object.
1602     uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1603     for (auto &&Target : TargetsForSlot) {
1604       TotalPaddingBefore += std::max<int64_t>(
1605           (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1606       TotalPaddingAfter += std::max<int64_t>(
1607           (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1608     }
1609 
1610     // If the amount of padding is too large, give up.
1611     // FIXME: do something smarter here.
1612     if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1613       continue;
1614 
1615     // Calculate the offset to the value as a (possibly negative) byte offset
1616     // and (if applicable) a bit offset, and store the values in the targets.
1617     int64_t OffsetByte;
1618     uint64_t OffsetBit;
1619     if (TotalPaddingBefore <= TotalPaddingAfter)
1620       setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1621                             OffsetBit);
1622     else
1623       setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1624                            OffsetBit);
1625 
1626     if (RemarksEnabled)
1627       for (auto &&Target : TargetsForSlot)
1628         Target.WasDevirt = true;
1629 
1630 
1631     if (CSByConstantArg.second.isExported()) {
1632       ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
1633       exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1634                      ResByArg->Byte);
1635       exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1636                      ResByArg->Bit);
1637     }
1638 
1639     // Rewrite each call to a load from OffsetByte/OffsetBit.
1640     Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1641     Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
1642     applyVirtualConstProp(CSByConstantArg.second,
1643                           TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
1644   }
1645   return true;
1646 }
1647 
1648 void DevirtModule::rebuildGlobal(VTableBits &B) {
1649   if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1650     return;
1651 
1652   // Align the before byte array to the global's minimum alignment so that we
1653   // don't break any alignment requirements on the global.
1654   MaybeAlign Alignment(B.GV->getAlignment());
1655   if (!Alignment)
1656     Alignment =
1657         Align(M.getDataLayout().getABITypeAlignment(B.GV->getValueType()));
1658   B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
1659 
1660   // Before was stored in reverse order; flip it now.
1661   for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1662     std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1663 
1664   // Build an anonymous global containing the before bytes, followed by the
1665   // original initializer, followed by the after bytes.
1666   auto NewInit = ConstantStruct::getAnon(
1667       {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1668        B.GV->getInitializer(),
1669        ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1670   auto NewGV =
1671       new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1672                          GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1673   NewGV->setSection(B.GV->getSection());
1674   NewGV->setComdat(B.GV->getComdat());
1675   NewGV->setAlignment(MaybeAlign(B.GV->getAlignment()));
1676 
1677   // Copy the original vtable's metadata to the anonymous global, adjusting
1678   // offsets as required.
1679   NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1680 
1681   // Build an alias named after the original global, pointing at the second
1682   // element (the original initializer).
1683   auto Alias = GlobalAlias::create(
1684       B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1685       ConstantExpr::getGetElementPtr(
1686           NewInit->getType(), NewGV,
1687           ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1688                                ConstantInt::get(Int32Ty, 1)}),
1689       &M);
1690   Alias->setVisibility(B.GV->getVisibility());
1691   Alias->takeName(B.GV);
1692 
1693   B.GV->replaceAllUsesWith(Alias);
1694   B.GV->eraseFromParent();
1695 }
1696 
1697 bool DevirtModule::areRemarksEnabled() {
1698   const auto &FL = M.getFunctionList();
1699   for (const Function &Fn : FL) {
1700     const auto &BBL = Fn.getBasicBlockList();
1701     if (BBL.empty())
1702       continue;
1703     auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
1704     return DI.isEnabled();
1705   }
1706   return false;
1707 }
1708 
1709 void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc) {
1710   // Find all virtual calls via a virtual table pointer %p under an assumption
1711   // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1712   // points to a member of the type identifier %md. Group calls by (type ID,
1713   // offset) pair (effectively the identity of the virtual function) and store
1714   // to CallSlots.
1715   DenseSet<CallBase *> SeenCallSites;
1716   for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
1717        I != E;) {
1718     auto CI = dyn_cast<CallInst>(I->getUser());
1719     ++I;
1720     if (!CI)
1721       continue;
1722 
1723     // Search for virtual calls based on %p and add them to DevirtCalls.
1724     SmallVector<DevirtCallSite, 1> DevirtCalls;
1725     SmallVector<CallInst *, 1> Assumes;
1726     auto &DT = LookupDomTree(*CI->getFunction());
1727     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
1728 
1729     // If we found any, add them to CallSlots.
1730     if (!Assumes.empty()) {
1731       Metadata *TypeId =
1732           cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1733       Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
1734       for (DevirtCallSite Call : DevirtCalls) {
1735         // Only add this CallSite if we haven't seen it before. The vtable
1736         // pointer may have been CSE'd with pointers from other call sites,
1737         // and we don't want to process call sites multiple times. We can't
1738         // just skip the vtable Ptr if it has been seen before, however, since
1739         // it may be shared by type tests that dominate different calls.
1740         if (SeenCallSites.insert(&Call.CB).second)
1741           CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr);
1742       }
1743     }
1744 
1745     // We no longer need the assumes or the type test.
1746     for (auto Assume : Assumes)
1747       Assume->eraseFromParent();
1748     // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1749     // may use the vtable argument later.
1750     if (CI->use_empty())
1751       CI->eraseFromParent();
1752   }
1753 }
1754 
1755 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1756   Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1757 
1758   for (auto I = TypeCheckedLoadFunc->use_begin(),
1759             E = TypeCheckedLoadFunc->use_end();
1760        I != E;) {
1761     auto CI = dyn_cast<CallInst>(I->getUser());
1762     ++I;
1763     if (!CI)
1764       continue;
1765 
1766     Value *Ptr = CI->getArgOperand(0);
1767     Value *Offset = CI->getArgOperand(1);
1768     Value *TypeIdValue = CI->getArgOperand(2);
1769     Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1770 
1771     SmallVector<DevirtCallSite, 1> DevirtCalls;
1772     SmallVector<Instruction *, 1> LoadedPtrs;
1773     SmallVector<Instruction *, 1> Preds;
1774     bool HasNonCallUses = false;
1775     auto &DT = LookupDomTree(*CI->getFunction());
1776     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1777                                                HasNonCallUses, CI, DT);
1778 
1779     // Start by generating "pessimistic" code that explicitly loads the function
1780     // pointer from the vtable and performs the type check. If possible, we will
1781     // eliminate the load and the type check later.
1782 
1783     // If possible, only generate the load at the point where it is used.
1784     // This helps avoid unnecessary spills.
1785     IRBuilder<> LoadB(
1786         (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1787     Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1788     Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1789     Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1790 
1791     for (Instruction *LoadedPtr : LoadedPtrs) {
1792       LoadedPtr->replaceAllUsesWith(LoadedValue);
1793       LoadedPtr->eraseFromParent();
1794     }
1795 
1796     // Likewise for the type test.
1797     IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1798     CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1799 
1800     for (Instruction *Pred : Preds) {
1801       Pred->replaceAllUsesWith(TypeTestCall);
1802       Pred->eraseFromParent();
1803     }
1804 
1805     // We have already erased any extractvalue instructions that refer to the
1806     // intrinsic call, but the intrinsic may have other non-extractvalue uses
1807     // (although this is unlikely). In that case, explicitly build a pair and
1808     // RAUW it.
1809     if (!CI->use_empty()) {
1810       Value *Pair = UndefValue::get(CI->getType());
1811       IRBuilder<> B(CI);
1812       Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1813       Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1814       CI->replaceAllUsesWith(Pair);
1815     }
1816 
1817     // The number of unsafe uses is initially the number of uses.
1818     auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1819     NumUnsafeUses = DevirtCalls.size();
1820 
1821     // If the function pointer has a non-call user, we cannot eliminate the type
1822     // check, as one of those users may eventually call the pointer. Increment
1823     // the unsafe use count to make sure it cannot reach zero.
1824     if (HasNonCallUses)
1825       ++NumUnsafeUses;
1826     for (DevirtCallSite Call : DevirtCalls) {
1827       CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB,
1828                                                    &NumUnsafeUses);
1829     }
1830 
1831     CI->eraseFromParent();
1832   }
1833 }
1834 
1835 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
1836   auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
1837   if (!TypeId)
1838     return;
1839   const TypeIdSummary *TidSummary =
1840       ImportSummary->getTypeIdSummary(TypeId->getString());
1841   if (!TidSummary)
1842     return;
1843   auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1844   if (ResI == TidSummary->WPDRes.end())
1845     return;
1846   const WholeProgramDevirtResolution &Res = ResI->second;
1847 
1848   if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1849     assert(!Res.SingleImplName.empty());
1850     // The type of the function in the declaration is irrelevant because every
1851     // call site will cast it to the correct type.
1852     Constant *SingleImpl =
1853         cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
1854                                              Type::getVoidTy(M.getContext()))
1855                            .getCallee());
1856 
1857     // This is the import phase so we should not be exporting anything.
1858     bool IsExported = false;
1859     applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1860     assert(!IsExported);
1861   }
1862 
1863   for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1864     auto I = Res.ResByArg.find(CSByConstantArg.first);
1865     if (I == Res.ResByArg.end())
1866       continue;
1867     auto &ResByArg = I->second;
1868     // FIXME: We should figure out what to do about the "function name" argument
1869     // to the apply* functions, as the function names are unavailable during the
1870     // importing phase. For now we just pass the empty string. This does not
1871     // impact correctness because the function names are just used for remarks.
1872     switch (ResByArg.TheKind) {
1873     case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1874       applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1875       break;
1876     case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1877       Constant *UniqueMemberAddr =
1878           importGlobal(Slot, CSByConstantArg.first, "unique_member");
1879       applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1880                            UniqueMemberAddr);
1881       break;
1882     }
1883     case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
1884       Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
1885                                       Int32Ty, ResByArg.Byte);
1886       Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
1887                                      ResByArg.Bit);
1888       applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
1889       break;
1890     }
1891     default:
1892       break;
1893     }
1894   }
1895 
1896   if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
1897     // The type of the function is irrelevant, because it's bitcast at calls
1898     // anyhow.
1899     Constant *JT = cast<Constant>(
1900         M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
1901                               Type::getVoidTy(M.getContext()))
1902             .getCallee());
1903     bool IsExported = false;
1904     applyICallBranchFunnel(SlotInfo, JT, IsExported);
1905     assert(!IsExported);
1906   }
1907 }
1908 
1909 void DevirtModule::removeRedundantTypeTests() {
1910   auto True = ConstantInt::getTrue(M.getContext());
1911   for (auto &&U : NumUnsafeUsesForTypeTest) {
1912     if (U.second == 0) {
1913       U.first->replaceAllUsesWith(True);
1914       U.first->eraseFromParent();
1915     }
1916   }
1917 }
1918 
1919 bool DevirtModule::run() {
1920   // If only some of the modules were split, we cannot correctly perform
1921   // this transformation. We already checked for the presense of type tests
1922   // with partially split modules during the thin link, and would have emitted
1923   // an error if any were found, so here we can simply return.
1924   if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
1925       (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
1926     return false;
1927 
1928   Function *TypeTestFunc =
1929       M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1930   Function *TypeCheckedLoadFunc =
1931       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1932   Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1933 
1934   // Normally if there are no users of the devirtualization intrinsics in the
1935   // module, this pass has nothing to do. But if we are exporting, we also need
1936   // to handle any users that appear only in the function summaries.
1937   if (!ExportSummary &&
1938       (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
1939        AssumeFunc->use_empty()) &&
1940       (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1941     return false;
1942 
1943   if (TypeTestFunc && AssumeFunc)
1944     scanTypeTestUsers(TypeTestFunc);
1945 
1946   if (TypeCheckedLoadFunc)
1947     scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
1948 
1949   if (ImportSummary) {
1950     for (auto &S : CallSlots)
1951       importResolution(S.first, S.second);
1952 
1953     removeRedundantTypeTests();
1954 
1955     // We have lowered or deleted the type instrinsics, so we will no
1956     // longer have enough information to reason about the liveness of virtual
1957     // function pointers in GlobalDCE.
1958     for (GlobalVariable &GV : M.globals())
1959       GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
1960 
1961     // The rest of the code is only necessary when exporting or during regular
1962     // LTO, so we are done.
1963     return true;
1964   }
1965 
1966   // Rebuild type metadata into a map for easy lookup.
1967   std::vector<VTableBits> Bits;
1968   DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1969   buildTypeIdentifierMap(Bits, TypeIdMap);
1970   if (TypeIdMap.empty())
1971     return true;
1972 
1973   // Collect information from summary about which calls to try to devirtualize.
1974   if (ExportSummary) {
1975     DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1976     for (auto &P : TypeIdMap) {
1977       if (auto *TypeId = dyn_cast<MDString>(P.first))
1978         MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1979             TypeId);
1980     }
1981 
1982     for (auto &P : *ExportSummary) {
1983       for (auto &S : P.second.SummaryList) {
1984         auto *FS = dyn_cast<FunctionSummary>(S.get());
1985         if (!FS)
1986           continue;
1987         // FIXME: Only add live functions.
1988         for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1989           for (Metadata *MD : MetadataByGUID[VF.GUID]) {
1990             CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
1991           }
1992         }
1993         for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1994           for (Metadata *MD : MetadataByGUID[VF.GUID]) {
1995             CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
1996           }
1997         }
1998         for (const FunctionSummary::ConstVCall &VC :
1999              FS->type_test_assume_const_vcalls()) {
2000           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2001             CallSlots[{MD, VC.VFunc.Offset}]
2002                 .ConstCSInfo[VC.Args]
2003                 .addSummaryTypeTestAssumeUser(FS);
2004           }
2005         }
2006         for (const FunctionSummary::ConstVCall &VC :
2007              FS->type_checked_load_const_vcalls()) {
2008           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2009             CallSlots[{MD, VC.VFunc.Offset}]
2010                 .ConstCSInfo[VC.Args]
2011                 .addSummaryTypeCheckedLoadUser(FS);
2012           }
2013         }
2014       }
2015     }
2016   }
2017 
2018   // For each (type, offset) pair:
2019   bool DidVirtualConstProp = false;
2020   std::map<std::string, Function*> DevirtTargets;
2021   for (auto &S : CallSlots) {
2022     // Search each of the members of the type identifier for the virtual
2023     // function implementation at offset S.first.ByteOffset, and add to
2024     // TargetsForSlot.
2025     std::vector<VirtualCallTarget> TargetsForSlot;
2026     if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
2027                                   S.first.ByteOffset)) {
2028       WholeProgramDevirtResolution *Res = nullptr;
2029       if (ExportSummary && isa<MDString>(S.first.TypeID))
2030         Res = &ExportSummary
2031                    ->getOrInsertTypeIdSummary(
2032                        cast<MDString>(S.first.TypeID)->getString())
2033                    .WPDRes[S.first.ByteOffset];
2034 
2035       if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
2036         DidVirtualConstProp |=
2037             tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
2038 
2039         tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
2040       }
2041 
2042       // Collect functions devirtualized at least for one call site for stats.
2043       if (RemarksEnabled)
2044         for (const auto &T : TargetsForSlot)
2045           if (T.WasDevirt)
2046             DevirtTargets[std::string(T.Fn->getName())] = T.Fn;
2047     }
2048 
2049     // CFI-specific: if we are exporting and any llvm.type.checked.load
2050     // intrinsics were *not* devirtualized, we need to add the resulting
2051     // llvm.type.test intrinsics to the function summaries so that the
2052     // LowerTypeTests pass will export them.
2053     if (ExportSummary && isa<MDString>(S.first.TypeID)) {
2054       auto GUID =
2055           GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
2056       for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
2057         FS->addTypeTest(GUID);
2058       for (auto &CCS : S.second.ConstCSInfo)
2059         for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
2060           FS->addTypeTest(GUID);
2061     }
2062   }
2063 
2064   if (RemarksEnabled) {
2065     // Generate remarks for each devirtualized function.
2066     for (const auto &DT : DevirtTargets) {
2067       Function *F = DT.second;
2068 
2069       using namespace ore;
2070       OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
2071                         << "devirtualized "
2072                         << NV("FunctionName", DT.first));
2073     }
2074   }
2075 
2076   removeRedundantTypeTests();
2077 
2078   // Rebuild each global we touched as part of virtual constant propagation to
2079   // include the before and after bytes.
2080   if (DidVirtualConstProp)
2081     for (VTableBits &B : Bits)
2082       rebuildGlobal(B);
2083 
2084   // We have lowered or deleted the type instrinsics, so we will no
2085   // longer have enough information to reason about the liveness of virtual
2086   // function pointers in GlobalDCE.
2087   for (GlobalVariable &GV : M.globals())
2088     GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2089 
2090   return true;
2091 }
2092 
2093 void DevirtIndex::run() {
2094   if (ExportSummary.typeIdCompatibleVtableMap().empty())
2095     return;
2096 
2097   DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
2098   for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
2099     NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first);
2100   }
2101 
2102   // Collect information from summary about which calls to try to devirtualize.
2103   for (auto &P : ExportSummary) {
2104     for (auto &S : P.second.SummaryList) {
2105       auto *FS = dyn_cast<FunctionSummary>(S.get());
2106       if (!FS)
2107         continue;
2108       // FIXME: Only add live functions.
2109       for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2110         for (StringRef Name : NameByGUID[VF.GUID]) {
2111           CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2112         }
2113       }
2114       for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2115         for (StringRef Name : NameByGUID[VF.GUID]) {
2116           CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2117         }
2118       }
2119       for (const FunctionSummary::ConstVCall &VC :
2120            FS->type_test_assume_const_vcalls()) {
2121         for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2122           CallSlots[{Name, VC.VFunc.Offset}]
2123               .ConstCSInfo[VC.Args]
2124               .addSummaryTypeTestAssumeUser(FS);
2125         }
2126       }
2127       for (const FunctionSummary::ConstVCall &VC :
2128            FS->type_checked_load_const_vcalls()) {
2129         for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2130           CallSlots[{Name, VC.VFunc.Offset}]
2131               .ConstCSInfo[VC.Args]
2132               .addSummaryTypeCheckedLoadUser(FS);
2133         }
2134       }
2135     }
2136   }
2137 
2138   std::set<ValueInfo> DevirtTargets;
2139   // For each (type, offset) pair:
2140   for (auto &S : CallSlots) {
2141     // Search each of the members of the type identifier for the virtual
2142     // function implementation at offset S.first.ByteOffset, and add to
2143     // TargetsForSlot.
2144     std::vector<ValueInfo> TargetsForSlot;
2145     auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2146     assert(TidSummary);
2147     if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2148                                   S.first.ByteOffset)) {
2149       WholeProgramDevirtResolution *Res =
2150           &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID)
2151                .WPDRes[S.first.ByteOffset];
2152 
2153       if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2154                                DevirtTargets))
2155         continue;
2156     }
2157   }
2158 
2159   // Optionally have the thin link print message for each devirtualized
2160   // function.
2161   if (PrintSummaryDevirt)
2162     for (const auto &DT : DevirtTargets)
2163       errs() << "Devirtualized call to " << DT << "\n";
2164 
2165   return;
2166 }
2167