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