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/OptimizationDiagnosticInfo.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/DebugInfoMetadata.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.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
279   emitRemark(const StringRef OptName, const StringRef TargetName,
280              function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
281     Function *F = CS.getCaller();
282     DebugLoc DLoc = CS->getDebugLoc();
283     BasicBlock *Block = CS.getParent();
284 
285     // In the new pass manager, we can request the optimization
286     // remark emitter pass on a per-function-basis, which the
287     // OREGetter will do for us.
288     // In the old pass manager, this is harder, so we just build
289     // a optimization remark emitter on the fly, when we need it.
290     std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
291     OptimizationRemarkEmitter *ORE;
292     if (OREGetter)
293       ORE = &OREGetter(F);
294     else {
295       OwnedORE = make_unique<OptimizationRemarkEmitter>(F);
296       ORE = OwnedORE.get();
297     }
298 
299     using namespace ore;
300     ORE->emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
301               << NV("Optimization", OptName) << ": devirtualized a call to "
302               << NV("FunctionName", TargetName));
303   }
304 
305   void replaceAndErase(
306       const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
307       function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
308       Value *New) {
309     if (RemarksEnabled)
310       emitRemark(OptName, TargetName, OREGetter);
311     CS->replaceAllUsesWith(New);
312     if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) {
313       BranchInst::Create(II->getNormalDest(), CS.getInstruction());
314       II->getUnwindDest()->removePredecessor(II->getParent());
315     }
316     CS->eraseFromParent();
317     // This use is no longer unsafe.
318     if (NumUnsafeUses)
319       --*NumUnsafeUses;
320   }
321 };
322 
323 // Call site information collected for a specific VTableSlot and possibly a list
324 // of constant integer arguments. The grouping by arguments is handled by the
325 // VTableSlotInfo class.
326 struct CallSiteInfo {
327   /// The set of call sites for this slot. Used during regular LTO and the
328   /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
329   /// call sites that appear in the merged module itself); in each of these
330   /// cases we are directly operating on the call sites at the IR level.
331   std::vector<VirtualCallSite> CallSites;
332 
333   // These fields are used during the export phase of ThinLTO and reflect
334   // information collected from function summaries.
335 
336   /// Whether any function summary contains an llvm.assume(llvm.type.test) for
337   /// this slot.
338   bool SummaryHasTypeTestAssumeUsers;
339 
340   /// CFI-specific: a vector containing the list of function summaries that use
341   /// the llvm.type.checked.load intrinsic and therefore will require
342   /// resolutions for llvm.type.test in order to implement CFI checks if
343   /// devirtualization was unsuccessful. If devirtualization was successful, the
344   /// pass will clear this vector by calling markDevirt(). If at the end of the
345   /// pass the vector is non-empty, we will need to add a use of llvm.type.test
346   /// to each of the function summaries in the vector.
347   std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
348 
349   bool isExported() const {
350     return SummaryHasTypeTestAssumeUsers ||
351            !SummaryTypeCheckedLoadUsers.empty();
352   }
353 
354   /// As explained in the comment for SummaryTypeCheckedLoadUsers.
355   void markDevirt() { SummaryTypeCheckedLoadUsers.clear(); }
356 };
357 
358 // Call site information collected for a specific VTableSlot.
359 struct VTableSlotInfo {
360   // The set of call sites which do not have all constant integer arguments
361   // (excluding "this").
362   CallSiteInfo CSInfo;
363 
364   // The set of call sites with all constant integer arguments (excluding
365   // "this"), grouped by argument list.
366   std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
367 
368   void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses);
369 
370 private:
371   CallSiteInfo &findCallSiteInfo(CallSite CS);
372 };
373 
374 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) {
375   std::vector<uint64_t> Args;
376   auto *CI = dyn_cast<IntegerType>(CS.getType());
377   if (!CI || CI->getBitWidth() > 64 || CS.arg_empty())
378     return CSInfo;
379   for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) {
380     auto *CI = dyn_cast<ConstantInt>(Arg);
381     if (!CI || CI->getBitWidth() > 64)
382       return CSInfo;
383     Args.push_back(CI->getZExtValue());
384   }
385   return ConstCSInfo[Args];
386 }
387 
388 void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS,
389                                  unsigned *NumUnsafeUses) {
390   findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses});
391 }
392 
393 struct DevirtModule {
394   Module &M;
395   function_ref<AAResults &(Function &)> AARGetter;
396 
397   ModuleSummaryIndex *ExportSummary;
398   const ModuleSummaryIndex *ImportSummary;
399 
400   IntegerType *Int8Ty;
401   PointerType *Int8PtrTy;
402   IntegerType *Int32Ty;
403   IntegerType *Int64Ty;
404   IntegerType *IntPtrTy;
405 
406   bool RemarksEnabled;
407   function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
408 
409   MapVector<VTableSlot, VTableSlotInfo> CallSlots;
410 
411   // This map keeps track of the number of "unsafe" uses of a loaded function
412   // pointer. The key is the associated llvm.type.test intrinsic call generated
413   // by this pass. An unsafe use is one that calls the loaded function pointer
414   // directly. Every time we eliminate an unsafe use (for example, by
415   // devirtualizing it or by applying virtual constant propagation), we
416   // decrement the value stored in this map. If a value reaches zero, we can
417   // eliminate the type check by RAUWing the associated llvm.type.test call with
418   // true.
419   std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
420 
421   DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter,
422                function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
423                ModuleSummaryIndex *ExportSummary,
424                const ModuleSummaryIndex *ImportSummary)
425       : M(M), AARGetter(AARGetter), ExportSummary(ExportSummary),
426         ImportSummary(ImportSummary), Int8Ty(Type::getInt8Ty(M.getContext())),
427         Int8PtrTy(Type::getInt8PtrTy(M.getContext())),
428         Int32Ty(Type::getInt32Ty(M.getContext())),
429         Int64Ty(Type::getInt64Ty(M.getContext())),
430         IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
431         RemarksEnabled(areRemarksEnabled()), OREGetter(OREGetter) {
432     assert(!(ExportSummary && ImportSummary));
433   }
434 
435   bool areRemarksEnabled();
436 
437   void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc);
438   void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
439 
440   void buildTypeIdentifierMap(
441       std::vector<VTableBits> &Bits,
442       DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
443   Constant *getPointerAtOffset(Constant *I, uint64_t Offset);
444   bool
445   tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot,
446                             const std::set<TypeMemberInfo> &TypeMemberInfos,
447                             uint64_t ByteOffset);
448 
449   void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
450                              bool &IsExported);
451   bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
452                            VTableSlotInfo &SlotInfo,
453                            WholeProgramDevirtResolution *Res);
454 
455   bool tryEvaluateFunctionsWithArgs(
456       MutableArrayRef<VirtualCallTarget> TargetsForSlot,
457       ArrayRef<uint64_t> Args);
458 
459   void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
460                              uint64_t TheRetVal);
461   bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
462                            CallSiteInfo &CSInfo,
463                            WholeProgramDevirtResolution::ByArg *Res);
464 
465   // Returns the global symbol name that is used to export information about the
466   // given vtable slot and list of arguments.
467   std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
468                             StringRef Name);
469 
470   // This function is called during the export phase to create a symbol
471   // definition containing information about the given vtable slot and list of
472   // arguments.
473   void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
474                     Constant *C);
475 
476   // This function is called during the import phase to create a reference to
477   // the symbol definition created during the export phase.
478   Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
479                          StringRef Name, unsigned AbsWidth = 0);
480 
481   void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
482                             Constant *UniqueMemberAddr);
483   bool tryUniqueRetValOpt(unsigned BitWidth,
484                           MutableArrayRef<VirtualCallTarget> TargetsForSlot,
485                           CallSiteInfo &CSInfo,
486                           WholeProgramDevirtResolution::ByArg *Res,
487                           VTableSlot Slot, ArrayRef<uint64_t> Args);
488 
489   void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
490                              Constant *Byte, Constant *Bit);
491   bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
492                            VTableSlotInfo &SlotInfo,
493                            WholeProgramDevirtResolution *Res, VTableSlot Slot);
494 
495   void rebuildGlobal(VTableBits &B);
496 
497   // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
498   void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
499 
500   // If we were able to eliminate all unsafe uses for a type checked load,
501   // eliminate the associated type tests by replacing them with true.
502   void removeRedundantTypeTests();
503 
504   bool run();
505 
506   // Lower the module using the action and summary passed as command line
507   // arguments. For testing purposes only.
508   static bool runForTesting(
509       Module &M, function_ref<AAResults &(Function &)> AARGetter,
510       function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
511 };
512 
513 struct WholeProgramDevirt : public ModulePass {
514   static char ID;
515 
516   bool UseCommandLine = false;
517 
518   ModuleSummaryIndex *ExportSummary;
519   const ModuleSummaryIndex *ImportSummary;
520 
521   WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
522     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
523   }
524 
525   WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
526                      const ModuleSummaryIndex *ImportSummary)
527       : ModulePass(ID), ExportSummary(ExportSummary),
528         ImportSummary(ImportSummary) {
529     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
530   }
531 
532   bool runOnModule(Module &M) override {
533     if (skipModule(M))
534       return false;
535 
536     auto OREGetter = function_ref<OptimizationRemarkEmitter &(Function *)>();
537 
538     if (UseCommandLine)
539       return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter);
540 
541     return DevirtModule(M, LegacyAARGetter(*this), OREGetter, ExportSummary,
542                         ImportSummary)
543         .run();
544   }
545 
546   void getAnalysisUsage(AnalysisUsage &AU) const override {
547     AU.addRequired<AssumptionCacheTracker>();
548     AU.addRequired<TargetLibraryInfoWrapperPass>();
549   }
550 };
551 
552 } // end anonymous namespace
553 
554 INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
555                       "Whole program devirtualization", false, false)
556 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
557 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
558 INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
559                     "Whole program devirtualization", false, false)
560 char WholeProgramDevirt::ID = 0;
561 
562 ModulePass *
563 llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
564                                    const ModuleSummaryIndex *ImportSummary) {
565   return new WholeProgramDevirt(ExportSummary, ImportSummary);
566 }
567 
568 PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
569                                               ModuleAnalysisManager &AM) {
570   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
571   auto AARGetter = [&](Function &F) -> AAResults & {
572     return FAM.getResult<AAManager>(F);
573   };
574   auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
575     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
576   };
577   if (!DevirtModule(M, AARGetter, OREGetter, nullptr, nullptr).run())
578     return PreservedAnalyses::all();
579   return PreservedAnalyses::none();
580 }
581 
582 bool DevirtModule::runForTesting(
583     Module &M, function_ref<AAResults &(Function &)> AARGetter,
584     function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
585   ModuleSummaryIndex Summary;
586 
587   // Handle the command-line summary arguments. This code is for testing
588   // purposes only, so we handle errors directly.
589   if (!ClReadSummary.empty()) {
590     ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
591                           ": ");
592     auto ReadSummaryFile =
593         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
594 
595     yaml::Input In(ReadSummaryFile->getBuffer());
596     In >> Summary;
597     ExitOnErr(errorCodeToError(In.error()));
598   }
599 
600   bool Changed =
601       DevirtModule(
602           M, AARGetter, OREGetter,
603           ClSummaryAction == PassSummaryAction::Export ? &Summary : nullptr,
604           ClSummaryAction == PassSummaryAction::Import ? &Summary : nullptr)
605           .run();
606 
607   if (!ClWriteSummary.empty()) {
608     ExitOnError ExitOnErr(
609         "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
610     std::error_code EC;
611     raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text);
612     ExitOnErr(errorCodeToError(EC));
613 
614     yaml::Output Out(OS);
615     Out << Summary;
616   }
617 
618   return Changed;
619 }
620 
621 void DevirtModule::buildTypeIdentifierMap(
622     std::vector<VTableBits> &Bits,
623     DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
624   DenseMap<GlobalVariable *, VTableBits *> GVToBits;
625   Bits.reserve(M.getGlobalList().size());
626   SmallVector<MDNode *, 2> Types;
627   for (GlobalVariable &GV : M.globals()) {
628     Types.clear();
629     GV.getMetadata(LLVMContext::MD_type, Types);
630     if (Types.empty())
631       continue;
632 
633     VTableBits *&BitsPtr = GVToBits[&GV];
634     if (!BitsPtr) {
635       Bits.emplace_back();
636       Bits.back().GV = &GV;
637       Bits.back().ObjectSize =
638           M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
639       BitsPtr = &Bits.back();
640     }
641 
642     for (MDNode *Type : Types) {
643       auto TypeID = Type->getOperand(1).get();
644 
645       uint64_t Offset =
646           cast<ConstantInt>(
647               cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
648               ->getZExtValue();
649 
650       TypeIdMap[TypeID].insert({BitsPtr, Offset});
651     }
652   }
653 }
654 
655 Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) {
656   if (I->getType()->isPointerTy()) {
657     if (Offset == 0)
658       return I;
659     return nullptr;
660   }
661 
662   const DataLayout &DL = M.getDataLayout();
663 
664   if (auto *C = dyn_cast<ConstantStruct>(I)) {
665     const StructLayout *SL = DL.getStructLayout(C->getType());
666     if (Offset >= SL->getSizeInBytes())
667       return nullptr;
668 
669     unsigned Op = SL->getElementContainingOffset(Offset);
670     return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
671                               Offset - SL->getElementOffset(Op));
672   }
673   if (auto *C = dyn_cast<ConstantArray>(I)) {
674     ArrayType *VTableTy = C->getType();
675     uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType());
676 
677     unsigned Op = Offset / ElemSize;
678     if (Op >= C->getNumOperands())
679       return nullptr;
680 
681     return getPointerAtOffset(cast<Constant>(I->getOperand(Op)),
682                               Offset % ElemSize);
683   }
684   return nullptr;
685 }
686 
687 bool DevirtModule::tryFindVirtualCallTargets(
688     std::vector<VirtualCallTarget> &TargetsForSlot,
689     const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) {
690   for (const TypeMemberInfo &TM : TypeMemberInfos) {
691     if (!TM.Bits->GV->isConstant())
692       return false;
693 
694     Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
695                                        TM.Offset + ByteOffset);
696     if (!Ptr)
697       return false;
698 
699     auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
700     if (!Fn)
701       return false;
702 
703     // We can disregard __cxa_pure_virtual as a possible call target, as
704     // calls to pure virtuals are UB.
705     if (Fn->getName() == "__cxa_pure_virtual")
706       continue;
707 
708     TargetsForSlot.push_back({Fn, &TM});
709   }
710 
711   // Give up if we couldn't find any targets.
712   return !TargetsForSlot.empty();
713 }
714 
715 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
716                                          Constant *TheFn, bool &IsExported) {
717   auto Apply = [&](CallSiteInfo &CSInfo) {
718     for (auto &&VCallSite : CSInfo.CallSites) {
719       if (RemarksEnabled)
720         VCallSite.emitRemark("single-impl", TheFn->getName(), OREGetter);
721       VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast(
722           TheFn, VCallSite.CS.getCalledValue()->getType()));
723       // This use is no longer unsafe.
724       if (VCallSite.NumUnsafeUses)
725         --*VCallSite.NumUnsafeUses;
726     }
727     if (CSInfo.isExported()) {
728       IsExported = true;
729       CSInfo.markDevirt();
730     }
731   };
732   Apply(SlotInfo.CSInfo);
733   for (auto &P : SlotInfo.ConstCSInfo)
734     Apply(P.second);
735 }
736 
737 bool DevirtModule::trySingleImplDevirt(
738     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
739     VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) {
740   // See if the program contains a single implementation of this virtual
741   // function.
742   Function *TheFn = TargetsForSlot[0].Fn;
743   for (auto &&Target : TargetsForSlot)
744     if (TheFn != Target.Fn)
745       return false;
746 
747   // If so, update each call site to call that implementation directly.
748   if (RemarksEnabled)
749     TargetsForSlot[0].WasDevirt = true;
750 
751   bool IsExported = false;
752   applySingleImplDevirt(SlotInfo, TheFn, IsExported);
753   if (!IsExported)
754     return false;
755 
756   // If the only implementation has local linkage, we must promote to external
757   // to make it visible to thin LTO objects. We can only get here during the
758   // ThinLTO export phase.
759   if (TheFn->hasLocalLinkage()) {
760     std::string NewName = (TheFn->getName() + "$merged").str();
761 
762     // Since we are renaming the function, any comdats with the same name must
763     // also be renamed. This is required when targeting COFF, as the comdat name
764     // must match one of the names of the symbols in the comdat.
765     if (Comdat *C = TheFn->getComdat()) {
766       if (C->getName() == TheFn->getName()) {
767         Comdat *NewC = M.getOrInsertComdat(NewName);
768         NewC->setSelectionKind(C->getSelectionKind());
769         for (GlobalObject &GO : M.global_objects())
770           if (GO.getComdat() == C)
771             GO.setComdat(NewC);
772       }
773     }
774 
775     TheFn->setLinkage(GlobalValue::ExternalLinkage);
776     TheFn->setVisibility(GlobalValue::HiddenVisibility);
777     TheFn->setName(NewName);
778   }
779 
780   Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
781   Res->SingleImplName = TheFn->getName();
782 
783   return true;
784 }
785 
786 bool DevirtModule::tryEvaluateFunctionsWithArgs(
787     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
788     ArrayRef<uint64_t> Args) {
789   // Evaluate each function and store the result in each target's RetVal
790   // field.
791   for (VirtualCallTarget &Target : TargetsForSlot) {
792     if (Target.Fn->arg_size() != Args.size() + 1)
793       return false;
794 
795     Evaluator Eval(M.getDataLayout(), nullptr);
796     SmallVector<Constant *, 2> EvalArgs;
797     EvalArgs.push_back(
798         Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
799     for (unsigned I = 0; I != Args.size(); ++I) {
800       auto *ArgTy = dyn_cast<IntegerType>(
801           Target.Fn->getFunctionType()->getParamType(I + 1));
802       if (!ArgTy)
803         return false;
804       EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
805     }
806 
807     Constant *RetVal;
808     if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
809         !isa<ConstantInt>(RetVal))
810       return false;
811     Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
812   }
813   return true;
814 }
815 
816 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
817                                          uint64_t TheRetVal) {
818   for (auto Call : CSInfo.CallSites)
819     Call.replaceAndErase(
820         "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
821         ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal));
822   CSInfo.markDevirt();
823 }
824 
825 bool DevirtModule::tryUniformRetValOpt(
826     MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
827     WholeProgramDevirtResolution::ByArg *Res) {
828   // Uniform return value optimization. If all functions return the same
829   // constant, replace all calls with that constant.
830   uint64_t TheRetVal = TargetsForSlot[0].RetVal;
831   for (const VirtualCallTarget &Target : TargetsForSlot)
832     if (Target.RetVal != TheRetVal)
833       return false;
834 
835   if (CSInfo.isExported()) {
836     Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
837     Res->Info = TheRetVal;
838   }
839 
840   applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
841   if (RemarksEnabled)
842     for (auto &&Target : TargetsForSlot)
843       Target.WasDevirt = true;
844   return true;
845 }
846 
847 std::string DevirtModule::getGlobalName(VTableSlot Slot,
848                                         ArrayRef<uint64_t> Args,
849                                         StringRef Name) {
850   std::string FullName = "__typeid_";
851   raw_string_ostream OS(FullName);
852   OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
853   for (uint64_t Arg : Args)
854     OS << '_' << Arg;
855   OS << '_' << Name;
856   return OS.str();
857 }
858 
859 void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
860                                 StringRef Name, Constant *C) {
861   GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
862                                         getGlobalName(Slot, Args, Name), C, &M);
863   GA->setVisibility(GlobalValue::HiddenVisibility);
864 }
865 
866 Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
867                                      StringRef Name, unsigned AbsWidth) {
868   Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty);
869   auto *GV = dyn_cast<GlobalVariable>(C);
870   // We only need to set metadata if the global is newly created, in which
871   // case it would not have hidden visibility.
872   if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility)
873     return C;
874 
875   GV->setVisibility(GlobalValue::HiddenVisibility);
876   auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
877     auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
878     auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
879     GV->setMetadata(LLVMContext::MD_absolute_symbol,
880                     MDNode::get(M.getContext(), {MinC, MaxC}));
881   };
882   if (AbsWidth == IntPtrTy->getBitWidth())
883     SetAbsRange(~0ull, ~0ull); // Full set.
884   else if (AbsWidth)
885     SetAbsRange(0, 1ull << AbsWidth);
886   return GV;
887 }
888 
889 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
890                                         bool IsOne,
891                                         Constant *UniqueMemberAddr) {
892   for (auto &&Call : CSInfo.CallSites) {
893     IRBuilder<> B(Call.CS.getInstruction());
894     Value *Cmp =
895         B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
896                      B.CreateBitCast(Call.VTable, Int8PtrTy), UniqueMemberAddr);
897     Cmp = B.CreateZExt(Cmp, Call.CS->getType());
898     Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
899                          Cmp);
900   }
901   CSInfo.markDevirt();
902 }
903 
904 bool DevirtModule::tryUniqueRetValOpt(
905     unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
906     CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
907     VTableSlot Slot, ArrayRef<uint64_t> Args) {
908   // IsOne controls whether we look for a 0 or a 1.
909   auto tryUniqueRetValOptFor = [&](bool IsOne) {
910     const TypeMemberInfo *UniqueMember = nullptr;
911     for (const VirtualCallTarget &Target : TargetsForSlot) {
912       if (Target.RetVal == (IsOne ? 1 : 0)) {
913         if (UniqueMember)
914           return false;
915         UniqueMember = Target.TM;
916       }
917     }
918 
919     // We should have found a unique member or bailed out by now. We already
920     // checked for a uniform return value in tryUniformRetValOpt.
921     assert(UniqueMember);
922 
923     Constant *UniqueMemberAddr =
924         ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy);
925     UniqueMemberAddr = ConstantExpr::getGetElementPtr(
926         Int8Ty, UniqueMemberAddr,
927         ConstantInt::get(Int64Ty, UniqueMember->Offset));
928 
929     if (CSInfo.isExported()) {
930       Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
931       Res->Info = IsOne;
932 
933       exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
934     }
935 
936     // Replace each call with the comparison.
937     applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
938                          UniqueMemberAddr);
939 
940     // Update devirtualization statistics for targets.
941     if (RemarksEnabled)
942       for (auto &&Target : TargetsForSlot)
943         Target.WasDevirt = true;
944 
945     return true;
946   };
947 
948   if (BitWidth == 1) {
949     if (tryUniqueRetValOptFor(true))
950       return true;
951     if (tryUniqueRetValOptFor(false))
952       return true;
953   }
954   return false;
955 }
956 
957 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
958                                          Constant *Byte, Constant *Bit) {
959   for (auto Call : CSInfo.CallSites) {
960     auto *RetType = cast<IntegerType>(Call.CS.getType());
961     IRBuilder<> B(Call.CS.getInstruction());
962     Value *Addr =
963         B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
964     if (RetType->getBitWidth() == 1) {
965       Value *Bits = B.CreateLoad(Addr);
966       Value *BitsAndBit = B.CreateAnd(Bits, Bit);
967       auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
968       Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
969                            OREGetter, IsBitSet);
970     } else {
971       Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
972       Value *Val = B.CreateLoad(RetType, ValAddr);
973       Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
974                            OREGetter, Val);
975     }
976   }
977   CSInfo.markDevirt();
978 }
979 
980 bool DevirtModule::tryVirtualConstProp(
981     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
982     WholeProgramDevirtResolution *Res, VTableSlot Slot) {
983   // This only works if the function returns an integer.
984   auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
985   if (!RetType)
986     return false;
987   unsigned BitWidth = RetType->getBitWidth();
988   if (BitWidth > 64)
989     return false;
990 
991   // Make sure that each function is defined, does not access memory, takes at
992   // least one argument, does not use its first argument (which we assume is
993   // 'this'), and has the same return type.
994   //
995   // Note that we test whether this copy of the function is readnone, rather
996   // than testing function attributes, which must hold for any copy of the
997   // function, even a less optimized version substituted at link time. This is
998   // sound because the virtual constant propagation optimizations effectively
999   // inline all implementations of the virtual function into each call site,
1000   // rather than using function attributes to perform local optimization.
1001   for (VirtualCallTarget &Target : TargetsForSlot) {
1002     if (Target.Fn->isDeclaration() ||
1003         computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1004             MAK_ReadNone ||
1005         Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
1006         Target.Fn->getReturnType() != RetType)
1007       return false;
1008   }
1009 
1010   for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1011     if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1012       continue;
1013 
1014     WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1015     if (Res)
1016       ResByArg = &Res->ResByArg[CSByConstantArg.first];
1017 
1018     if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1019       continue;
1020 
1021     if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1022                            ResByArg, Slot, CSByConstantArg.first))
1023       continue;
1024 
1025     // Find an allocation offset in bits in all vtables associated with the
1026     // type.
1027     uint64_t AllocBefore =
1028         findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1029     uint64_t AllocAfter =
1030         findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1031 
1032     // Calculate the total amount of padding needed to store a value at both
1033     // ends of the object.
1034     uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1035     for (auto &&Target : TargetsForSlot) {
1036       TotalPaddingBefore += std::max<int64_t>(
1037           (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1038       TotalPaddingAfter += std::max<int64_t>(
1039           (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1040     }
1041 
1042     // If the amount of padding is too large, give up.
1043     // FIXME: do something smarter here.
1044     if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1045       continue;
1046 
1047     // Calculate the offset to the value as a (possibly negative) byte offset
1048     // and (if applicable) a bit offset, and store the values in the targets.
1049     int64_t OffsetByte;
1050     uint64_t OffsetBit;
1051     if (TotalPaddingBefore <= TotalPaddingAfter)
1052       setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1053                             OffsetBit);
1054     else
1055       setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1056                            OffsetBit);
1057 
1058     if (RemarksEnabled)
1059       for (auto &&Target : TargetsForSlot)
1060         Target.WasDevirt = true;
1061 
1062     Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1063     Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
1064 
1065     if (CSByConstantArg.second.isExported()) {
1066       ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
1067       exportGlobal(Slot, CSByConstantArg.first, "byte",
1068                    ConstantExpr::getIntToPtr(ByteConst, Int8PtrTy));
1069       exportGlobal(Slot, CSByConstantArg.first, "bit",
1070                    ConstantExpr::getIntToPtr(BitConst, Int8PtrTy));
1071     }
1072 
1073     // Rewrite each call to a load from OffsetByte/OffsetBit.
1074     applyVirtualConstProp(CSByConstantArg.second,
1075                           TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
1076   }
1077   return true;
1078 }
1079 
1080 void DevirtModule::rebuildGlobal(VTableBits &B) {
1081   if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1082     return;
1083 
1084   // Align each byte array to pointer width.
1085   unsigned PointerSize = M.getDataLayout().getPointerSize();
1086   B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize));
1087   B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize));
1088 
1089   // Before was stored in reverse order; flip it now.
1090   for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1091     std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1092 
1093   // Build an anonymous global containing the before bytes, followed by the
1094   // original initializer, followed by the after bytes.
1095   auto NewInit = ConstantStruct::getAnon(
1096       {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1097        B.GV->getInitializer(),
1098        ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1099   auto NewGV =
1100       new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1101                          GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1102   NewGV->setSection(B.GV->getSection());
1103   NewGV->setComdat(B.GV->getComdat());
1104 
1105   // Copy the original vtable's metadata to the anonymous global, adjusting
1106   // offsets as required.
1107   NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1108 
1109   // Build an alias named after the original global, pointing at the second
1110   // element (the original initializer).
1111   auto Alias = GlobalAlias::create(
1112       B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1113       ConstantExpr::getGetElementPtr(
1114           NewInit->getType(), NewGV,
1115           ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1116                                ConstantInt::get(Int32Ty, 1)}),
1117       &M);
1118   Alias->setVisibility(B.GV->getVisibility());
1119   Alias->takeName(B.GV);
1120 
1121   B.GV->replaceAllUsesWith(Alias);
1122   B.GV->eraseFromParent();
1123 }
1124 
1125 bool DevirtModule::areRemarksEnabled() {
1126   const auto &FL = M.getFunctionList();
1127   if (FL.empty())
1128     return false;
1129   const Function &Fn = FL.front();
1130 
1131   const auto &BBL = Fn.getBasicBlockList();
1132   if (BBL.empty())
1133     return false;
1134   auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
1135   return DI.isEnabled();
1136 }
1137 
1138 void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc,
1139                                      Function *AssumeFunc) {
1140   // Find all virtual calls via a virtual table pointer %p under an assumption
1141   // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1142   // points to a member of the type identifier %md. Group calls by (type ID,
1143   // offset) pair (effectively the identity of the virtual function) and store
1144   // to CallSlots.
1145   DenseSet<Value *> SeenPtrs;
1146   for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end();
1147        I != E;) {
1148     auto CI = dyn_cast<CallInst>(I->getUser());
1149     ++I;
1150     if (!CI)
1151       continue;
1152 
1153     // Search for virtual calls based on %p and add them to DevirtCalls.
1154     SmallVector<DevirtCallSite, 1> DevirtCalls;
1155     SmallVector<CallInst *, 1> Assumes;
1156     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI);
1157 
1158     // If we found any, add them to CallSlots. Only do this if we haven't seen
1159     // the vtable pointer before, as it may have been CSE'd with pointers from
1160     // other call sites, and we don't want to process call sites multiple times.
1161     if (!Assumes.empty()) {
1162       Metadata *TypeId =
1163           cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1164       Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
1165       if (SeenPtrs.insert(Ptr).second) {
1166         for (DevirtCallSite Call : DevirtCalls) {
1167           CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, nullptr);
1168         }
1169       }
1170     }
1171 
1172     // We no longer need the assumes or the type test.
1173     for (auto Assume : Assumes)
1174       Assume->eraseFromParent();
1175     // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1176     // may use the vtable argument later.
1177     if (CI->use_empty())
1178       CI->eraseFromParent();
1179   }
1180 }
1181 
1182 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1183   Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1184 
1185   for (auto I = TypeCheckedLoadFunc->use_begin(),
1186             E = TypeCheckedLoadFunc->use_end();
1187        I != E;) {
1188     auto CI = dyn_cast<CallInst>(I->getUser());
1189     ++I;
1190     if (!CI)
1191       continue;
1192 
1193     Value *Ptr = CI->getArgOperand(0);
1194     Value *Offset = CI->getArgOperand(1);
1195     Value *TypeIdValue = CI->getArgOperand(2);
1196     Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1197 
1198     SmallVector<DevirtCallSite, 1> DevirtCalls;
1199     SmallVector<Instruction *, 1> LoadedPtrs;
1200     SmallVector<Instruction *, 1> Preds;
1201     bool HasNonCallUses = false;
1202     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1203                                                HasNonCallUses, CI);
1204 
1205     // Start by generating "pessimistic" code that explicitly loads the function
1206     // pointer from the vtable and performs the type check. If possible, we will
1207     // eliminate the load and the type check later.
1208 
1209     // If possible, only generate the load at the point where it is used.
1210     // This helps avoid unnecessary spills.
1211     IRBuilder<> LoadB(
1212         (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1213     Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1214     Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1215     Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1216 
1217     for (Instruction *LoadedPtr : LoadedPtrs) {
1218       LoadedPtr->replaceAllUsesWith(LoadedValue);
1219       LoadedPtr->eraseFromParent();
1220     }
1221 
1222     // Likewise for the type test.
1223     IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1224     CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1225 
1226     for (Instruction *Pred : Preds) {
1227       Pred->replaceAllUsesWith(TypeTestCall);
1228       Pred->eraseFromParent();
1229     }
1230 
1231     // We have already erased any extractvalue instructions that refer to the
1232     // intrinsic call, but the intrinsic may have other non-extractvalue uses
1233     // (although this is unlikely). In that case, explicitly build a pair and
1234     // RAUW it.
1235     if (!CI->use_empty()) {
1236       Value *Pair = UndefValue::get(CI->getType());
1237       IRBuilder<> B(CI);
1238       Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1239       Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1240       CI->replaceAllUsesWith(Pair);
1241     }
1242 
1243     // The number of unsafe uses is initially the number of uses.
1244     auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1245     NumUnsafeUses = DevirtCalls.size();
1246 
1247     // If the function pointer has a non-call user, we cannot eliminate the type
1248     // check, as one of those users may eventually call the pointer. Increment
1249     // the unsafe use count to make sure it cannot reach zero.
1250     if (HasNonCallUses)
1251       ++NumUnsafeUses;
1252     for (DevirtCallSite Call : DevirtCalls) {
1253       CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS,
1254                                                    &NumUnsafeUses);
1255     }
1256 
1257     CI->eraseFromParent();
1258   }
1259 }
1260 
1261 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
1262   const TypeIdSummary *TidSummary =
1263       ImportSummary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString());
1264   if (!TidSummary)
1265     return;
1266   auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1267   if (ResI == TidSummary->WPDRes.end())
1268     return;
1269   const WholeProgramDevirtResolution &Res = ResI->second;
1270 
1271   if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1272     // The type of the function in the declaration is irrelevant because every
1273     // call site will cast it to the correct type.
1274     auto *SingleImpl = M.getOrInsertFunction(
1275         Res.SingleImplName, Type::getVoidTy(M.getContext()));
1276 
1277     // This is the import phase so we should not be exporting anything.
1278     bool IsExported = false;
1279     applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
1280     assert(!IsExported);
1281   }
1282 
1283   for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
1284     auto I = Res.ResByArg.find(CSByConstantArg.first);
1285     if (I == Res.ResByArg.end())
1286       continue;
1287     auto &ResByArg = I->second;
1288     // FIXME: We should figure out what to do about the "function name" argument
1289     // to the apply* functions, as the function names are unavailable during the
1290     // importing phase. For now we just pass the empty string. This does not
1291     // impact correctness because the function names are just used for remarks.
1292     switch (ResByArg.TheKind) {
1293     case WholeProgramDevirtResolution::ByArg::UniformRetVal:
1294       applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
1295       break;
1296     case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
1297       Constant *UniqueMemberAddr =
1298           importGlobal(Slot, CSByConstantArg.first, "unique_member");
1299       applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
1300                            UniqueMemberAddr);
1301       break;
1302     }
1303     case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
1304       Constant *Byte = importGlobal(Slot, CSByConstantArg.first, "byte", 32);
1305       Byte = ConstantExpr::getPtrToInt(Byte, Int32Ty);
1306       Constant *Bit = importGlobal(Slot, CSByConstantArg.first, "bit", 8);
1307       Bit = ConstantExpr::getPtrToInt(Bit, Int8Ty);
1308       applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
1309     }
1310     default:
1311       break;
1312     }
1313   }
1314 }
1315 
1316 void DevirtModule::removeRedundantTypeTests() {
1317   auto True = ConstantInt::getTrue(M.getContext());
1318   for (auto &&U : NumUnsafeUsesForTypeTest) {
1319     if (U.second == 0) {
1320       U.first->replaceAllUsesWith(True);
1321       U.first->eraseFromParent();
1322     }
1323   }
1324 }
1325 
1326 bool DevirtModule::run() {
1327   Function *TypeTestFunc =
1328       M.getFunction(Intrinsic::getName(Intrinsic::type_test));
1329   Function *TypeCheckedLoadFunc =
1330       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
1331   Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
1332 
1333   // Normally if there are no users of the devirtualization intrinsics in the
1334   // module, this pass has nothing to do. But if we are exporting, we also need
1335   // to handle any users that appear only in the function summaries.
1336   if (!ExportSummary &&
1337       (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
1338        AssumeFunc->use_empty()) &&
1339       (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
1340     return false;
1341 
1342   if (TypeTestFunc && AssumeFunc)
1343     scanTypeTestUsers(TypeTestFunc, AssumeFunc);
1344 
1345   if (TypeCheckedLoadFunc)
1346     scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
1347 
1348   if (ImportSummary) {
1349     for (auto &S : CallSlots)
1350       importResolution(S.first, S.second);
1351 
1352     removeRedundantTypeTests();
1353 
1354     // The rest of the code is only necessary when exporting or during regular
1355     // LTO, so we are done.
1356     return true;
1357   }
1358 
1359   // Rebuild type metadata into a map for easy lookup.
1360   std::vector<VTableBits> Bits;
1361   DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
1362   buildTypeIdentifierMap(Bits, TypeIdMap);
1363   if (TypeIdMap.empty())
1364     return true;
1365 
1366   // Collect information from summary about which calls to try to devirtualize.
1367   if (ExportSummary) {
1368     DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
1369     for (auto &P : TypeIdMap) {
1370       if (auto *TypeId = dyn_cast<MDString>(P.first))
1371         MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
1372             TypeId);
1373     }
1374 
1375     for (auto &P : *ExportSummary) {
1376       for (auto &S : P.second.SummaryList) {
1377         auto *FS = dyn_cast<FunctionSummary>(S.get());
1378         if (!FS)
1379           continue;
1380         // FIXME: Only add live functions.
1381         for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
1382           for (Metadata *MD : MetadataByGUID[VF.GUID]) {
1383             CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers =
1384                 true;
1385           }
1386         }
1387         for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
1388           for (Metadata *MD : MetadataByGUID[VF.GUID]) {
1389             CallSlots[{MD, VF.Offset}]
1390                 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS);
1391           }
1392         }
1393         for (const FunctionSummary::ConstVCall &VC :
1394              FS->type_test_assume_const_vcalls()) {
1395           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
1396             CallSlots[{MD, VC.VFunc.Offset}]
1397                 .ConstCSInfo[VC.Args]
1398                 .SummaryHasTypeTestAssumeUsers = true;
1399           }
1400         }
1401         for (const FunctionSummary::ConstVCall &VC :
1402              FS->type_checked_load_const_vcalls()) {
1403           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
1404             CallSlots[{MD, VC.VFunc.Offset}]
1405                 .ConstCSInfo[VC.Args]
1406                 .SummaryTypeCheckedLoadUsers.push_back(FS);
1407           }
1408         }
1409       }
1410     }
1411   }
1412 
1413   // For each (type, offset) pair:
1414   bool DidVirtualConstProp = false;
1415   std::map<std::string, Function*> DevirtTargets;
1416   for (auto &S : CallSlots) {
1417     // Search each of the members of the type identifier for the virtual
1418     // function implementation at offset S.first.ByteOffset, and add to
1419     // TargetsForSlot.
1420     std::vector<VirtualCallTarget> TargetsForSlot;
1421     if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID],
1422                                   S.first.ByteOffset)) {
1423       WholeProgramDevirtResolution *Res = nullptr;
1424       if (ExportSummary && isa<MDString>(S.first.TypeID))
1425         Res = &ExportSummary
1426                    ->getOrInsertTypeIdSummary(
1427                        cast<MDString>(S.first.TypeID)->getString())
1428                    .WPDRes[S.first.ByteOffset];
1429 
1430       if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) &&
1431           tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first))
1432         DidVirtualConstProp = true;
1433 
1434       // Collect functions devirtualized at least for one call site for stats.
1435       if (RemarksEnabled)
1436         for (const auto &T : TargetsForSlot)
1437           if (T.WasDevirt)
1438             DevirtTargets[T.Fn->getName()] = T.Fn;
1439     }
1440 
1441     // CFI-specific: if we are exporting and any llvm.type.checked.load
1442     // intrinsics were *not* devirtualized, we need to add the resulting
1443     // llvm.type.test intrinsics to the function summaries so that the
1444     // LowerTypeTests pass will export them.
1445     if (ExportSummary && isa<MDString>(S.first.TypeID)) {
1446       auto GUID =
1447           GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
1448       for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
1449         FS->addTypeTest(GUID);
1450       for (auto &CCS : S.second.ConstCSInfo)
1451         for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
1452           FS->addTypeTest(GUID);
1453     }
1454   }
1455 
1456   if (RemarksEnabled) {
1457     // Generate remarks for each devirtualized function.
1458     for (const auto &DT : DevirtTargets) {
1459       Function *F = DT.second;
1460 
1461       // In the new pass manager, we can request the optimization
1462       // remark emitter pass on a per-function-basis, which the
1463       // OREGetter will do for us.
1464       // In the old pass manager, this is harder, so we just build
1465       // a optimization remark emitter on the fly, when we need it.
1466       std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1467       OptimizationRemarkEmitter *ORE;
1468       if (OREGetter)
1469         ORE = &OREGetter(F);
1470       else {
1471         OwnedORE = make_unique<OptimizationRemarkEmitter>(F);
1472         ORE = OwnedORE.get();
1473       }
1474 
1475       using namespace ore;
1476       ORE->emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
1477                 << "devirtualized " << NV("FunctionName", F->getName()));
1478     }
1479   }
1480 
1481   removeRedundantTypeTests();
1482 
1483   // Rebuild each global we touched as part of virtual constant propagation to
1484   // include the before and after bytes.
1485   if (DidVirtualConstProp)
1486     for (VTableBits &B : Bits)
1487       rebuildGlobal(B);
1488 
1489   return true;
1490 }
1491