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