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