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