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/iterator_range.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/Analysis/AliasAnalysis.h"
53 #include "llvm/Analysis/BasicAliasAnalysis.h"
54 #include "llvm/Analysis/TypeMetadataUtils.h"
55 #include "llvm/IR/CallSite.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugInfoMetadata.h"
59 #include "llvm/IR/DebugLoc.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/DiagnosticInfo.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalAlias.h"
64 #include "llvm/IR/GlobalVariable.h"
65 #include "llvm/IR/IRBuilder.h"
66 #include "llvm/IR/InstrTypes.h"
67 #include "llvm/IR/Instruction.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/LLVMContext.h"
71 #include "llvm/IR/Metadata.h"
72 #include "llvm/IR/Module.h"
73 #include "llvm/IR/ModuleSummaryIndexYAML.h"
74 #include "llvm/Pass.h"
75 #include "llvm/PassRegistry.h"
76 #include "llvm/PassSupport.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/Error.h"
79 #include "llvm/Support/FileSystem.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Transforms/IPO.h"
82 #include "llvm/Transforms/IPO/FunctionAttrs.h"
83 #include "llvm/Transforms/Utils/Evaluator.h"
84 #include <algorithm>
85 #include <cstddef>
86 #include <map>
87 #include <set>
88 #include <string>
89 
90 using namespace llvm;
91 using namespace wholeprogramdevirt;
92 
93 #define DEBUG_TYPE "wholeprogramdevirt"
94 
95 static cl::opt<PassSummaryAction> ClSummaryAction(
96     "wholeprogramdevirt-summary-action",
97     cl::desc("What to do with the summary when running this pass"),
98     cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
99                clEnumValN(PassSummaryAction::Import, "import",
100                           "Import typeid resolutions from summary and globals"),
101                clEnumValN(PassSummaryAction::Export, "export",
102                           "Export typeid resolutions to summary and globals")),
103     cl::Hidden);
104 
105 static cl::opt<std::string> ClReadSummary(
106     "wholeprogramdevirt-read-summary",
107     cl::desc("Read summary from given YAML file before running pass"),
108     cl::Hidden);
109 
110 static cl::opt<std::string> ClWriteSummary(
111     "wholeprogramdevirt-write-summary",
112     cl::desc("Write summary to given YAML file after running pass"),
113     cl::Hidden);
114 
115 // Find the minimum offset that we may store a value of size Size bits at. If
116 // IsAfter is set, look for an offset before the object, otherwise look for an
117 // offset after the object.
118 uint64_t
119 wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets,
120                                      bool IsAfter, uint64_t Size) {
121   // Find a minimum offset taking into account only vtable sizes.
122   uint64_t MinByte = 0;
123   for (const VirtualCallTarget &Target : Targets) {
124     if (IsAfter)
125       MinByte = std::max(MinByte, Target.minAfterBytes());
126     else
127       MinByte = std::max(MinByte, Target.minBeforeBytes());
128   }
129 
130   // Build a vector of arrays of bytes covering, for each target, a slice of the
131   // used region (see AccumBitVector::BytesUsed in
132   // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
133   // this aligns the used regions to start at MinByte.
134   //
135   // In this example, A, B and C are vtables, # is a byte already allocated for
136   // a virtual function pointer, AAAA... (etc.) are the used regions for the
137   // vtables and Offset(X) is the value computed for the Offset variable below
138   // for X.
139   //
140   //                    Offset(A)
141   //                    |       |
142   //                            |MinByte
143   // A: ################AAAAAAAA|AAAAAAAA
144   // B: ########BBBBBBBBBBBBBBBB|BBBB
145   // C: ########################|CCCCCCCCCCCCCCCC
146   //            |   Offset(B)   |
147   //
148   // This code produces the slices of A, B and C that appear after the divider
149   // at MinByte.
150   std::vector<ArrayRef<uint8_t>> Used;
151   for (const VirtualCallTarget &Target : Targets) {
152     ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
153                                        : Target.TM->Bits->Before.BytesUsed;
154     uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
155                               : MinByte - Target.minBeforeBytes();
156 
157     // Disregard used regions that are smaller than Offset. These are
158     // effectively all-free regions that do not need to be checked.
159     if (VTUsed.size() > Offset)
160       Used.push_back(VTUsed.slice(Offset));
161   }
162 
163   if (Size == 1) {
164     // Find a free bit in each member of Used.
165     for (unsigned I = 0;; ++I) {
166       uint8_t BitsUsed = 0;
167       for (auto &&B : Used)
168         if (I < B.size())
169           BitsUsed |= B[I];
170       if (BitsUsed != 0xff)
171         return (MinByte + I) * 8 +
172                countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined);
173     }
174   } else {
175     // Find a free (Size/8) byte region in each member of Used.
176     // FIXME: see if alignment helps.
177     for (unsigned I = 0;; ++I) {
178       for (auto &&B : Used) {
179         unsigned Byte = 0;
180         while ((I + Byte) < B.size() && Byte < (Size / 8)) {
181           if (B[I + Byte])
182             goto NextI;
183           ++Byte;
184         }
185       }
186       return (MinByte + I) * 8;
187     NextI:;
188     }
189   }
190 }
191 
192 void wholeprogramdevirt::setBeforeReturnValues(
193     MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
194     unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
195   if (BitWidth == 1)
196     OffsetByte = -(AllocBefore / 8 + 1);
197   else
198     OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
199   OffsetBit = AllocBefore % 8;
200 
201   for (VirtualCallTarget &Target : Targets) {
202     if (BitWidth == 1)
203       Target.setBeforeBit(AllocBefore);
204     else
205       Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
206   }
207 }
208 
209 void wholeprogramdevirt::setAfterReturnValues(
210     MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
211     unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
212   if (BitWidth == 1)
213     OffsetByte = AllocAfter / 8;
214   else
215     OffsetByte = (AllocAfter + 7) / 8;
216   OffsetBit = AllocAfter % 8;
217 
218   for (VirtualCallTarget &Target : Targets) {
219     if (BitWidth == 1)
220       Target.setAfterBit(AllocAfter);
221     else
222       Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
223   }
224 }
225 
226 VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM)
227     : Fn(Fn), TM(TM),
228       IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {}
229 
230 namespace {
231 
232 // A slot in a set of virtual tables. The TypeID identifies the set of virtual
233 // tables, and the ByteOffset is the offset in bytes from the address point to
234 // the virtual function pointer.
235 struct VTableSlot {
236   Metadata *TypeID;
237   uint64_t ByteOffset;
238 };
239 
240 } // end anonymous namespace
241 
242 namespace llvm {
243 
244 template <> struct DenseMapInfo<VTableSlot> {
245   static VTableSlot getEmptyKey() {
246     return {DenseMapInfo<Metadata *>::getEmptyKey(),
247             DenseMapInfo<uint64_t>::getEmptyKey()};
248   }
249   static VTableSlot getTombstoneKey() {
250     return {DenseMapInfo<Metadata *>::getTombstoneKey(),
251             DenseMapInfo<uint64_t>::getTombstoneKey()};
252   }
253   static unsigned getHashValue(const VTableSlot &I) {
254     return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^
255            DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset);
256   }
257   static bool isEqual(const VTableSlot &LHS,
258                       const VTableSlot &RHS) {
259     return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
260   }
261 };
262 
263 } // end namespace llvm
264 
265 namespace {
266 
267 // A virtual call site. VTable is the loaded virtual table pointer, and CS is
268 // the indirect virtual call.
269 struct VirtualCallSite {
270   Value *VTable;
271   CallSite CS;
272 
273   // If non-null, this field points to the associated unsafe use count stored in
274   // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
275   // of that field for details.
276   unsigned *NumUnsafeUses;
277 
278   void emitRemark(const Twine &OptName, const Twine &TargetName) {
279     Function *F = CS.getCaller();
280     emitOptimizationRemark(
281         F->getContext(), DEBUG_TYPE, *F,
282         CS.getInstruction()->getDebugLoc(),
283         OptName + ": devirtualized a call to " + TargetName);
284   }
285 
286   void replaceAndErase(const Twine &OptName, const Twine &TargetName,
287                        bool RemarksEnabled, Value *New) {
288     if (RemarksEnabled)
289       emitRemark(OptName, TargetName);
290     CS->replaceAllUsesWith(New);
291     if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
292       BranchInst::Create(II->getNormalDest(), CS.getInstruction());
293       II->getUnwindDest()->removePredecessor(II->getParent());
294     }
295     CS->eraseFromParent();
296     // This use is no longer unsafe.
297     if (NumUnsafeUses)
298       --*NumUnsafeUses;
299   }
300 };
301 
302 // Call site information collected for a specific VTableSlot and possibly a list
303 // of constant integer arguments. The grouping by arguments is handled by the
304 // VTableSlotInfo class.
305 struct CallSiteInfo {
306   /// The set of call sites for this slot. Used during regular LTO and the
307   /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
308   /// call sites that appear in the merged module itself); in each of these
309   /// cases we are directly operating on the call sites at the IR level.
310   std::vector<VirtualCallSite> CallSites;
311 
312   // These fields are used during the export phase of ThinLTO and reflect
313   // information collected from function summaries.
314 
315   /// Whether any function summary contains an llvm.assume(llvm.type.test) for
316   /// this slot.
317   bool SummaryHasTypeTestAssumeUsers;
318 
319   /// CFI-specific: a vector containing the list of function summaries that use
320   /// the llvm.type.checked.load intrinsic and therefore will require
321   /// resolutions for llvm.type.test in order to implement CFI checks if
322   /// devirtualization was unsuccessful. If devirtualization was successful, the
323   /// pass will clear this vector. If at the end of the pass the vector is
324   /// non-empty, we will need to add a use of llvm.type.test to each of the
325   /// function summaries in the vector.
326   std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
327 
328   bool isExported() const {
329     return SummaryHasTypeTestAssumeUsers ||
330            !SummaryTypeCheckedLoadUsers.empty();
331   }
332 };
333 
334 // Call site information collected for a specific VTableSlot.
335 struct VTableSlotInfo {
336   // The set of call sites which do not have all constant integer arguments
337   // (excluding "this").
338   CallSiteInfo CSInfo;
339 
340   // The set of call sites with all constant integer arguments (excluding
341   // "this"), grouped by argument list.
342   std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
343 
344   void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
345 
346 private:
347   CallSiteInfo &findCallSiteInfo(CallSite CS);
348 };
349 
350 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
351   std::vector<uint64_t> Args;
352   auto *CI = dyn_cast<IntegerType>(CS.getType());
353   if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
354     return CSInfo;
355   for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
356     auto *CI = dyn_cast<ConstantInt>(Arg);
357     if (!CI || CI->getBitWidth() > 64)
358       return CSInfo;
359     Args.push_back(CI->getZExtValue());
360   }
361   return ConstCSInfo[Args];
362 }
363 
364 void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
365                                  unsigned *NumUnsafeUses) {
366   findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
367 }
368 
369 struct DevirtModule {
370   Module &M;
371   function_ref<AAResults &(Function &)> AARGetter;
372 
373   PassSummaryAction Action;
374   ModuleSummaryIndex *Summary;
375 
376   IntegerType *Int8Ty;
377   PointerType *Int8PtrTy;
378   IntegerType *Int32Ty;
379   IntegerType *Int64Ty;
380 
381   bool RemarksEnabled;
382 
383   MapVector<VTableSlot, VTableSlotInfo> CallSlots;
384 
385   // This map keeps track of the number of "unsafe" uses of a loaded function
386   // pointer. The key is the associated llvm.type.test intrinsic call generated
387   // by this pass. An unsafe use is one that calls the loaded function pointer
388   // directly. Every time we eliminate an unsafe use (for example, by
389   // devirtualizing it or by applying virtual constant propagation), we
390   // decrement the value stored in this map. If a value reaches zero, we can
391   // eliminate the type check by RAUWing the associated llvm.type.test call with
392   // true.
393   std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
394 
395   DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
396                PassSummaryAction Action, ModuleSummaryIndex *Summary)
397       : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary),
398         Int8Ty(Type::getInt8Ty(M.getContext())),
399         Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
400         Int32Ty(Type::getInt32Ty(M.getContext())),
401         Int64Ty(Type::getInt64Ty(M.getContext())),
402         RemarksEnabled(areRemarksEnabled()) {}
403 
404   bool areRemarksEnabled();
405 
406   void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
407   void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
408 
409   void buildTypeIdentifierMap(
410       std::vector<VTableBits> &Bits,
411       DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
412   Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
413   bool
414   tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
415                             const std::set<TypeMemberInfo> &TypeMemberInfos,
416                             uint64_t ByteOffset);
417 
418   void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
419                              bool &IsExported);
420   bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
421                            VTableSlotInfo &SlotInfo,
422                            WholeProgramDevirtResolution *Res);
423 
424   bool tryEvaluateFunctionsWithArgs(
425       MutableArrayRef<VirtualCallTarget> TargetsForSlot,
426       ArrayRef<uint64_t> Args);
427 
428   void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
429                              uint64_t TheRetVal);
430   bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
431                            CallSiteInfo &CSInfo,
432                            WholeProgramDevirtResolution::ByArg *Res);
433 
434   void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
435                             Constant *UniqueMemberAddr);
436   bool tryUniqueRetValOpt(unsigned BitWidth,
437                           MutableArrayRef<VirtualCallTarget> TargetsForSlot,
438                           CallSiteInfo &CSInfo);
439 
440   void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
441                              Constant *Byte, Constant *Bit);
442   bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
443                            VTableSlotInfo &SlotInfo,
444                            WholeProgramDevirtResolution *Res);
445 
446   void rebuildGlobal(VTableBits &B);
447 
448   bool run();
449 
450   // Lower the module using the action and summary passed as command line
451   // arguments. For testing purposes only.
452   static bool runForTesting(Module &M,
453                             function_ref<AAResults &(Function &)> AARGetter);
454 };
455 
456 struct WholeProgramDevirt : public ModulePass {
457   static char ID;
458 
459   bool UseCommandLine = false;
460 
461   PassSummaryAction Action;
462   ModuleSummaryIndex *Summary;
463 
464   WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
465     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
466   }
467 
468   WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary)
469       : ModulePass(ID), Action(Action), Summary(Summary) {
470     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
471   }
472 
473   bool runOnModule(Module &M) override {
474     if (skipModule(M))
475       return false;
476     if (UseCommandLine)
477       return DevirtModule::runForTesting(M, LegacyAARGetter(*this));
478     return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run();
479   }
480 
481   void getAnalysisUsage(AnalysisUsage &AU) const override {
482     AU.addRequired<AssumptionCacheTracker>();
483     AU.addRequired<TargetLibraryInfoWrapperPass>();
484   }
485 };
486 
487 } // end anonymous namespace
488 
489 INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
490                       "Whole program devirtualization", false, false)
491 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
492 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
493 INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
494                     "Whole program devirtualization", false, false)
495 char WholeProgramDevirt::ID = 0;
496 
497 ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action,
498                                                ModuleSummaryIndex *Summary) {
499   return new WholeProgramDevirt(Action, Summary);
500 }
501 
502 PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
503                                               ModuleAnalysisManager &AM) {
504   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
505   auto AARGetter = [&](Function &F) -> AAResults & {
506     return FAM.getResult<AAManager>(F);
507   };
508   if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run())
509     return PreservedAnalyses::all();
510   return PreservedAnalyses::none();
511 }
512 
513 bool DevirtModule::runForTesting(
514     Module &M, function_ref<AAResults &(Function &)> AARGetter) {
515   ModuleSummaryIndex Summary;
516 
517   // Handle the command-line summary arguments. This code is for testing
518   // purposes only, so we handle errors directly.
519   if (!ClReadSummary.empty()) {
520     ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
521                           ": ");
522     auto ReadSummaryFile =
523         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
524 
525     yaml::Input In(ReadSummaryFile->getBuffer());
526     In >> Summary;
527     ExitOnErr(errorCodeToError(In.error()));
528   }
529 
530   bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run();
531 
532   if (!ClWriteSummary.empty()) {
533     ExitOnError ExitOnErr(
534         "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
535     std::error_code EC;
536     raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
537     ExitOnErr(errorCodeToError(EC));
538 
539     yaml::Output Out(OS);
540     Out << Summary;
541   }
542 
543   return Changed;
544 }
545 
546 void DevirtModule::buildTypeIdentifierMap(
547     std::vector<VTableBits> &Bits,
548     DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
549   DenseMap<GlobalVariable *, VTableBits *> GVToBits;
550   Bits.reserve(M.getGlobalList().size());
551   SmallVector<MDNode *, 2> Types;
552   for (GlobalVariable &GV : M.globals()) {
553     Types.clear();
554     GV.getMetadata(LLVMContext::MD_type, Types);
555     if (Types.empty())
556       continue;
557 
558     VTableBits *&BitsPtr = GVToBits[&GV];
559     if (!BitsPtr) {
560       Bits.emplace_back();
561       Bits.back().GV = &GV;
562       Bits.back().ObjectSize =
563           M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
564       BitsPtr = &Bits.back();
565     }
566 
567     for (MDNode *Type : Types) {
568       auto TypeID = Type->getOperand(1).get();
569 
570       uint64_t Offset =
571           cast<ConstantInt>(
572               cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
573               ->getZExtValue();
574 
575       TypeIdMap[TypeID].insert({BitsPtr, Offset});
576     }
577   }
578 }
579 
580 Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
581   if (I->getType()->isPointerTy()) {
582     if (Offset == 0)
583       return I;
584     return nullptr;
585   }
586 
587   const DataLayout &DL = M.getDataLayout();
588 
589   if (auto *C = dyn_cast<ConstantStruct>(I)) {
590     const StructLayout *SL = DL.getStructLayout(C->getType());
591     if (Offset >= SL->getSizeInBytes())
592       return nullptr;
593 
594     unsigned Op = SL->getElementContainingOffset(Offset);
595     return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
596                               Offset - SL->getElementOffset(Op));
597   }
598   if (auto *C = dyn_cast<ConstantArray>(I)) {
599     ArrayType *VTableTy = C->getType();
600     uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
601 
602     unsigned Op = Offset / ElemSize;
603     if (Op >= C->getNumOperands())
604       return nullptr;
605 
606     return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
607                               Offset % ElemSize);
608   }
609   return nullptr;
610 }
611 
612 bool DevirtModule::tryFindVirtualCallTargets(
613     std::vector<VirtualCallTarget> &TargetsForSlot,
614     const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
615   for (const TypeMemberInfo &TM : TypeMemberInfos) {
616     if (!TM.Bits->GV->isConstant())
617       return false;
618 
619     Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
620                                        TM.Offset + ByteOffset);
621     if (!Ptr)
622       return false;
623 
624     auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
625     if (!Fn)
626       return false;
627 
628     // We can disregard __cxa_pure_virtual as a possible call target, as
629     // calls to pure virtuals are UB.
630     if (Fn->getName() == "__cxa_pure_virtual")
631       continue;
632 
633     TargetsForSlot.push_back({Fn, &TM});
634   }
635 
636   // Give up if we couldn't find any targets.
637   return !TargetsForSlot.empty();
638 }
639 
640 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
641                                          Constant *TheFn, bool &IsExported) {
642   auto Apply = [&](CallSiteInfo &CSInfo) {
643     for (auto &&VCallSite : CSInfo.CallSites) {
644       if (RemarksEnabled)
645         VCallSite.emitRemark("single-impl", TheFn->getName());
646       VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
647           TheFn, VCallSite.CS.getCalledValue()->getType()));
648       // This use is no longer unsafe.
649       if (VCallSite.NumUnsafeUses)
650         --*VCallSite.NumUnsafeUses;
651     }
652     if (CSInfo.isExported()) {
653       IsExported = true;
654       CSInfo.SummaryTypeCheckedLoadUsers.clear();
655     }
656   };
657   Apply(SlotInfo.CSInfo);
658   for (auto &P : SlotInfo.ConstCSInfo)
659     Apply(P.second);
660 }
661 
662 bool DevirtModule::trySingleImplDevirt(
663     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
664     VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
665   // See if the program contains a single implementation of this virtual
666   // function.
667   Function *TheFn = TargetsForSlot[0].Fn;
668   for (auto &&Target : TargetsForSlot)
669     if (TheFn != Target.Fn)
670       return false;
671 
672   // If so, update each call site to call that implementation directly.
673   if (RemarksEnabled)
674     TargetsForSlot[0].WasDevirt = true;
675 
676   bool IsExported = false;
677   applySingleImplDevirt(SlotInfo, TheFn, IsExported);
678   if (!IsExported)
679     return false;
680 
681   // If the only implementation has local linkage, we must promote to external
682   // to make it visible to thin LTO objects. We can only get here during the
683   // ThinLTO export phase.
684   if (TheFn->hasLocalLinkage()) {
685     TheFn->setLinkage(GlobalValue::ExternalLinkage);
686     TheFn->setVisibility(GlobalValue::HiddenVisibility);
687     TheFn->setName(TheFn->getName() + "$merged");
688   }
689 
690   Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
691   Res->SingleImplName = TheFn->getName();
692 
693   return true;
694 }
695 
696 bool DevirtModule::tryEvaluateFunctionsWithArgs(
697     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
698     ArrayRef<uint64_t> Args) {
699   // Evaluate each function and store the result in each target's RetVal
700   // field.
701   for (VirtualCallTarget &Target : TargetsForSlot) {
702     if (Target.Fn->arg_size() != Args.size() + 1)
703       return false;
704 
705     Evaluator Eval(M.getDataLayout(), nullptr);
706     SmallVector<Constant *, 2> EvalArgs;
707     EvalArgs.push_back(
708         Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
709     for (unsigned I = 0; I != Args.size(); ++I) {
710       auto *ArgTy = dyn_cast<IntegerType>(
711           Target.Fn->getFunctionType()->getParamType(I + 1));
712       if (!ArgTy)
713         return false;
714       EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
715     }
716 
717     Constant *RetVal;
718     if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
719         !isa<ConstantInt>(RetVal))
720       return false;
721     Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
722   }
723   return true;
724 }
725 
726 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
727                                          uint64_t TheRetVal) {
728   for (auto Call : CSInfo.CallSites)
729     Call.replaceAndErase(
730         "uniform-ret-val", FnName, RemarksEnabled,
731         ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
732   CSInfo.SummaryTypeCheckedLoadUsers.clear();
733 }
734 
735 bool DevirtModule::tryUniformRetValOpt(
736     MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
737     WholeProgramDevirtResolution::ByArg *Res) {
738   // Uniform return value optimization. If all functions return the same
739   // constant, replace all calls with that constant.
740   uint64_t TheRetVal = TargetsForSlot[0].RetVal;
741   for (const VirtualCallTarget &Target : TargetsForSlot)
742     if (Target.RetVal != TheRetVal)
743       return false;
744 
745   if (CSInfo.isExported()) {
746     Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
747     Res->Info = TheRetVal;
748   }
749 
750   applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
751   if (RemarksEnabled)
752     for (auto &&Target : TargetsForSlot)
753       Target.WasDevirt = true;
754   return true;
755 }
756 
757 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
758                                         bool IsOne,
759                                         Constant *UniqueMemberAddr) {
760   for (auto &&Call : CSInfo.CallSites) {
761     IRBuilder<> B(Call.CS.getInstruction());
762     Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
763                               Call.VTable, UniqueMemberAddr);
764     Cmp = B.CreateZExt(Cmp, Call.CS->getType());
765     Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp);
766   }
767 }
768 
769 bool DevirtModule::tryUniqueRetValOpt(
770     unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
771     CallSiteInfo &CSInfo) {
772   // IsOne controls whether we look for a 0 or a 1.
773   auto tryUniqueRetValOptFor = [&](bool IsOne) {
774     const TypeMemberInfo *UniqueMember = nullptr;
775     for (const VirtualCallTarget &Target : TargetsForSlot) {
776       if (Target.RetVal == (IsOne ? 1 : 0)) {
777         if (UniqueMember)
778           return false;
779         UniqueMember = Target.TM;
780       }
781     }
782 
783     // We should have found a unique member or bailed out by now. We already
784     // checked for a uniform return value in tryUniformRetValOpt.
785     assert(UniqueMember);
786 
787     // Replace each call with the comparison.
788     Constant *UniqueMemberAddr =
789         ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
790     UniqueMemberAddr = ConstantExpr::getGetElementPtr(
791         Int8Ty, UniqueMemberAddr,
792         ConstantInt::get(Int64Ty, UniqueMember->Offset));
793 
794     applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
795                          UniqueMemberAddr);
796 
797     // Update devirtualization statistics for targets.
798     if (RemarksEnabled)
799       for (auto &&Target : TargetsForSlot)
800         Target.WasDevirt = true;
801 
802     return true;
803   };
804 
805   if (BitWidth == 1) {
806     if (tryUniqueRetValOptFor(true))
807       return true;
808     if (tryUniqueRetValOptFor(false))
809       return true;
810   }
811   return false;
812 }
813 
814 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
815                                          Constant *Byte, Constant *Bit) {
816   for (auto Call : CSInfo.CallSites) {
817     auto *RetType = cast<IntegerType>(Call.CS.getType());
818     IRBuilder<> B(Call.CS.getInstruction());
819     Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte);
820     if (RetType->getBitWidth() == 1) {
821       Value *Bits = B.CreateLoad(Addr);
822       Value *BitsAndBit = B.CreateAnd(Bits, Bit);
823       auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
824       Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
825                            IsBitSet);
826     } else {
827       Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
828       Value *Val = B.CreateLoad(RetType, ValAddr);
829       Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val);
830     }
831   }
832 }
833 
834 bool DevirtModule::tryVirtualConstProp(
835     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
836     VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
837   // This only works if the function returns an integer.
838   auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
839   if (!RetType)
840     return false;
841   unsigned BitWidth = RetType->getBitWidth();
842   if (BitWidth > 64)
843     return false;
844 
845   // Make sure that each function is defined, does not access memory, takes at
846   // least one argument, does not use its first argument (which we assume is
847   // 'this'), and has the same return type.
848   //
849   // Note that we test whether this copy of the function is readnone, rather
850   // than testing function attributes, which must hold for any copy of the
851   // function, even a less optimized version substituted at link time. This is
852   // sound because the virtual constant propagation optimizations effectively
853   // inline all implementations of the virtual function into each call site,
854   // rather than using function attributes to perform local optimization.
855   for (VirtualCallTarget &Target : TargetsForSlot) {
856     if (Target.Fn->isDeclaration() ||
857         computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
858             MAK_ReadNone ||
859         Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
860         Target.Fn->getReturnType() != RetType)
861       return false;
862   }
863 
864   for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
865     if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
866       continue;
867 
868     WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
869     if (Res)
870       ResByArg = &Res->ResByArg[CSByConstantArg.first];
871 
872     if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
873       continue;
874 
875     if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second))
876       continue;
877 
878     // Find an allocation offset in bits in all vtables associated with the
879     // type.
880     uint64_t AllocBefore =
881         findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
882     uint64_t AllocAfter =
883         findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
884 
885     // Calculate the total amount of padding needed to store a value at both
886     // ends of the object.
887     uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
888     for (auto &&Target : TargetsForSlot) {
889       TotalPaddingBefore += std::max<int64_t>(
890           (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
891       TotalPaddingAfter += std::max<int64_t>(
892           (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
893     }
894 
895     // If the amount of padding is too large, give up.
896     // FIXME: do something smarter here.
897     if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
898       continue;
899 
900     // Calculate the offset to the value as a (possibly negative) byte offset
901     // and (if applicable) a bit offset, and store the values in the targets.
902     int64_t OffsetByte;
903     uint64_t OffsetBit;
904     if (TotalPaddingBefore <= TotalPaddingAfter)
905       setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
906                             OffsetBit);
907     else
908       setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
909                            OffsetBit);
910 
911     if (RemarksEnabled)
912       for (auto &&Target : TargetsForSlot)
913         Target.WasDevirt = true;
914 
915     // Rewrite each call to a load from OffsetByte/OffsetBit.
916     Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
917     Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
918     applyVirtualConstProp(CSByConstantArg.second,
919                           TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
920   }
921   return true;
922 }
923 
924 void DevirtModule::rebuildGlobal(VTableBits &B) {
925   if (B.Before.Bytes.empty() && B.After.Bytes.empty())
926     return;
927 
928   // Align each byte array to pointer width.
929   unsigned PointerSize = M.getDataLayout().getPointerSize();
930   B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
931   B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
932 
933   // Before was stored in reverse order; flip it now.
934   for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
935     std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
936 
937   // Build an anonymous global containing the before bytes, followed by the
938   // original initializer, followed by the after bytes.
939   auto NewInit = ConstantStruct::getAnon(
940       {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
941        B.GV->getInitializer(),
942        ConstantDataArray::get(M.getContext(), B.After.Bytes)});
943   auto NewGV =
944       new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
945                          GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
946   NewGV->setSection(B.GV->getSection());
947   NewGV->setComdat(B.GV->getComdat());
948 
949   // Copy the original vtable's metadata to the anonymous global, adjusting
950   // offsets as required.
951   NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
952 
953   // Build an alias named after the original global, pointing at the second
954   // element (the original initializer).
955   auto Alias = GlobalAlias::create(
956       B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
957       ConstantExpr::getGetElementPtr(
958           NewInit->getType(), NewGV,
959           ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
960                                ConstantInt::get(Int32Ty, 1)}),
961       &M);
962   Alias->setVisibility(B.GV->getVisibility());
963   Alias->takeName(B.GV);
964 
965   B.GV->replaceAllUsesWith(Alias);
966   B.GV->eraseFromParent();
967 }
968 
969 bool DevirtModule::areRemarksEnabled() {
970   const auto &FL = M.getFunctionList();
971   if (FL.empty())
972     return false;
973   const Function &Fn = FL.front();
974 
975   const auto &BBL = Fn.getBasicBlockList();
976   if (BBL.empty())
977     return false;
978   auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
979   return DI.isEnabled();
980 }
981 
982 void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
983                                      Function *AssumeFunc) {
984   // Find all virtual calls via a virtual table pointer %p under an assumption
985   // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
986   // points to a member of the type identifier %md. Group calls by (type ID,
987   // offset) pair (effectively the identity of the virtual function) and store
988   // to CallSlots.
989   DenseSet<Value *> SeenPtrs;
990   for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
991        I != E;) {
992     auto CI = dyn_cast<CallInst>(I->getUser());
993     ++I;
994     if (!CI)
995       continue;
996 
997     // Search for virtual calls based on %p and add them to DevirtCalls.
998     SmallVector<DevirtCallSite, 1> DevirtCalls;
999     SmallVector<CallInst *, 1> Assumes;
1000     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
1001 
1002     // If we found any, add them to CallSlots. Only do this if we haven't seen
1003     // the vtable pointer before, as it may have been CSE'd with pointers from
1004     // other call sites, and we don't want to process call sites multiple times.
1005     if (!Assumes.empty()) {
1006       Metadata *TypeId =
1007           cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1008       Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
1009       if (SeenPtrs.insert(Ptr).second) {
1010         for (DevirtCallSite Call : DevirtCalls) {
1011           CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0),
1012                                                        Call.CS, nullptr);
1013         }
1014       }
1015     }
1016 
1017     // We no longer need the assumes or the type test.
1018     for (auto Assume : Assumes)
1019       Assume->eraseFromParent();
1020     // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1021     // may use the vtable argument later.
1022     if (CI->use_empty())
1023       CI->eraseFromParent();
1024   }
1025 }
1026 
1027 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1028   Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1029 
1030   for (auto I = TypeCheckedLoadFunc->use_begin(),
1031             E = TypeCheckedLoadFunc->use_end();
1032        I != E;) {
1033     auto CI = dyn_cast<CallInst>(I->getUser());
1034     ++I;
1035     if (!CI)
1036       continue;
1037 
1038     Value *Ptr = CI->getArgOperand(0);
1039     Value *Offset = CI->getArgOperand(1);
1040     Value *TypeIdValue = CI->getArgOperand(2);
1041     Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1042 
1043     SmallVector<DevirtCallSite, 1> DevirtCalls;
1044     SmallVector<Instruction *, 1> LoadedPtrs;
1045     SmallVector<Instruction *, 1> Preds;
1046     bool HasNonCallUses = false;
1047     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1048                                                HasNonCallUses, CI);
1049 
1050     // Start by generating "pessimistic" code that explicitly loads the function
1051     // pointer from the vtable and performs the type check. If possible, we will
1052     // eliminate the load and the type check later.
1053 
1054     // If possible, only generate the load at the point where it is used.
1055     // This helps avoid unnecessary spills.
1056     IRBuilder<> LoadB(
1057         (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1058     Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1059     Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1060     Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1061 
1062     for (Instruction *LoadedPtr : LoadedPtrs) {
1063       LoadedPtr->replaceAllUsesWith(LoadedValue);
1064       LoadedPtr->eraseFromParent();
1065     }
1066 
1067     // Likewise for the type test.
1068     IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1069     CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1070 
1071     for (Instruction *Pred : Preds) {
1072       Pred->replaceAllUsesWith(TypeTestCall);
1073       Pred->eraseFromParent();
1074     }
1075 
1076     // We have already erased any extractvalue instructions that refer to the
1077     // intrinsic call, but the intrinsic may have other non-extractvalue uses
1078     // (although this is unlikely). In that case, explicitly build a pair and
1079     // RAUW it.
1080     if (!CI->use_empty()) {
1081       Value *Pair = UndefValue::get(CI->getType());
1082       IRBuilder<> B(CI);
1083       Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1084       Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1085       CI->replaceAllUsesWith(Pair);
1086     }
1087 
1088     // The number of unsafe uses is initially the number of uses.
1089     auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1090     NumUnsafeUses = DevirtCalls.size();
1091 
1092     // If the function pointer has a non-call user, we cannot eliminate the type
1093     // check, as one of those users may eventually call the pointer. Increment
1094     // the unsafe use count to make sure it cannot reach zero.
1095     if (HasNonCallUses)
1096       ++NumUnsafeUses;
1097     for (DevirtCallSite Call : DevirtCalls) {
1098       CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1099                                                    &NumUnsafeUses);
1100     }
1101 
1102     CI->eraseFromParent();
1103   }
1104 }
1105 
1106 bool DevirtModule::run() {
1107   Function *TypeTestFunc =
1108       M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1109   Function *TypeCheckedLoadFunc =
1110       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1111   Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1112 
1113   // Normally if there are no users of the devirtualization intrinsics in the
1114   // module, this pass has nothing to do. But if we are exporting, we also need
1115   // to handle any users that appear only in the function summaries.
1116   if (Action != PassSummaryAction::Export &&
1117       (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
1118        AssumeFunc->use_empty()) &&
1119       (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1120     return false;
1121 
1122   if (TypeTestFunc && AssumeFunc)
1123     scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1124 
1125   if (TypeCheckedLoadFunc)
1126     scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
1127 
1128   // Rebuild type metadata into a map for easy lookup.
1129   std::vector<VTableBits> Bits;
1130   DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1131   buildTypeIdentifierMap(Bits, TypeIdMap);
1132   if (TypeIdMap.empty())
1133     return true;
1134 
1135   // Collect information from summary about which calls to try to devirtualize.
1136   if (Action == PassSummaryAction::Export) {
1137     DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1138     for (auto &P : TypeIdMap) {
1139       if (auto *TypeId = dyn_cast<MDString>(P.first))
1140         MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1141             TypeId);
1142     }
1143 
1144     for (auto &P : *Summary) {
1145       for (auto &S : P.second) {
1146         auto *FS = dyn_cast<FunctionSummary>(S.get());
1147         if (!FS)
1148           continue;
1149         // FIXME: Only add live functions.
1150         for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls())
1151           for (Metadata *MD : MetadataByGUID[VF.GUID])
1152             CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1153                 true;
1154         for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls())
1155           for (Metadata *MD : MetadataByGUID[VF.GUID])
1156             CallSlots[{MD, VF.Offset}]
1157                 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
1158         for (const FunctionSummary::ConstVCall &VC :
1159              FS->type_test_assume_const_vcalls())
1160           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1161             CallSlots[{MD, VC.VFunc.Offset}]
1162                 .ConstCSInfo[VC.Args].SummaryHasTypeTestAssumeUsers = true;
1163         for (const FunctionSummary::ConstVCall &VC :
1164              FS->type_checked_load_const_vcalls())
1165           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID])
1166             CallSlots[{MD, VC.VFunc.Offset}]
1167                 .ConstCSInfo[VC.Args]
1168                 .SummaryTypeCheckedLoadUsers.push_back(FS);
1169       }
1170     }
1171   }
1172 
1173   // For each (type, offset) pair:
1174   bool DidVirtualConstProp = false;
1175   std::map<std::string, Function*> DevirtTargets;
1176   for (auto &S : CallSlots) {
1177     // Search each of the members of the type identifier for the virtual
1178     // function implementation at offset S.first.ByteOffset, and add to
1179     // TargetsForSlot.
1180     std::vector<VirtualCallTarget> TargetsForSlot;
1181     if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1182                                   S.first.ByteOffset)) {
1183       WholeProgramDevirtResolution *Res = nullptr;
1184       if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID))
1185         Res =
1186             &Summary
1187                  ->getTypeIdSummary(cast<MDString>(S.first.TypeID)->getString())
1188                  .WPDRes[S.first.ByteOffset];
1189 
1190       if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
1191           tryVirtualConstProp(TargetsForSlot, S.second, Res))
1192         DidVirtualConstProp = true;
1193 
1194       // Collect functions devirtualized at least for one call site for stats.
1195       if (RemarksEnabled)
1196         for (const auto &T : TargetsForSlot)
1197           if (T.WasDevirt)
1198             DevirtTargets[T.Fn->getName()] = T.Fn;
1199     }
1200 
1201     // CFI-specific: if we are exporting and any llvm.type.checked.load
1202     // intrinsics were *not* devirtualized, we need to add the resulting
1203     // llvm.type.test intrinsics to the function summaries so that the
1204     // LowerTypeTests pass will export them.
1205     if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) {
1206       auto GUID =
1207           GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1208       for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1209         FS->addTypeTest(GUID);
1210       for (auto &CCS : S.second.ConstCSInfo)
1211         for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1212           FS->addTypeTest(GUID);
1213     }
1214   }
1215 
1216   if (RemarksEnabled) {
1217     // Generate remarks for each devirtualized function.
1218     for (const auto &DT : DevirtTargets) {
1219       Function *F = DT.second;
1220       DISubprogram *SP = F->getSubprogram();
1221       emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP,
1222                              Twine("devirtualized ") + F->getName());
1223     }
1224   }
1225 
1226   // If we were able to eliminate all unsafe uses for a type checked load,
1227   // eliminate the type test by replacing it with true.
1228   if (TypeCheckedLoadFunc) {
1229     auto True = ConstantInt::getTrue(M.getContext());
1230     for (auto &&U : NumUnsafeUsesForTypeTest) {
1231       if (U.second == 0) {
1232         U.first->replaceAllUsesWith(True);
1233         U.first->eraseFromParent();
1234       }
1235     }
1236   }
1237 
1238   // Rebuild each global we touched as part of virtual constant propagation to
1239   // include the before and after bytes.
1240   if (DidVirtualConstProp)
1241     for (VTableBits &B : Bits)
1242       rebuildGlobal(B);
1243 
1244   return true;
1245 }
1246