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   // Lower the module using the action and summary passed as command line
682   // arguments. For testing purposes only.
683   static bool
684   runForTesting(Module &M, function_ref<AAResults &(Function &)> AARGetter,
685                 function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
686                 function_ref<DominatorTree &(Function &)> LookupDomTree);
687 };
688 
689 struct DevirtIndex {
690   ModuleSummaryIndex &ExportSummary;
691   // The set in which to record GUIDs exported from their module by
692   // devirtualization, used by client to ensure they are not internalized.
693   std::set<GlobalValue::GUID> &ExportedGUIDs;
694   // A map in which to record the information necessary to locate the WPD
695   // resolution for local targets in case they are exported by cross module
696   // importing.
697   std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
698 
699   MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
700 
701   PatternList FunctionsToSkip;
702 
703   DevirtIndex(
704       ModuleSummaryIndex &ExportSummary,
705       std::set<GlobalValue::GUID> &ExportedGUIDs,
706       std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap)
707       : ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
708         LocalWPDTargetsMap(LocalWPDTargetsMap) {
709     FunctionsToSkip.init(SkipFunctionNames);
710   }
711 
712   bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
713                                  const TypeIdCompatibleVtableInfo TIdInfo,
714                                  uint64_t ByteOffset);
715 
716   bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
717                            VTableSlotSummary &SlotSummary,
718                            VTableSlotInfo &SlotInfo,
719                            WholeProgramDevirtResolution *Res,
720                            std::set<ValueInfo> &DevirtTargets);
721 
722   void run();
723 };
724 
725 struct WholeProgramDevirt : public ModulePass {
726   static char ID;
727 
728   bool UseCommandLine = false;
729 
730   ModuleSummaryIndex *ExportSummary = nullptr;
731   const ModuleSummaryIndex *ImportSummary = nullptr;
732 
733   WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) {
734     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
735   }
736 
737   WholeProgramDevirt(ModuleSummaryIndex *ExportSummary,
738                      const ModuleSummaryIndex *ImportSummary)
739       : ModulePass(ID), ExportSummary(ExportSummary),
740         ImportSummary(ImportSummary) {
741     initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry());
742   }
743 
744   bool runOnModule(Module &M) override {
745     if (skipModule(M))
746       return false;
747 
748     // In the new pass manager, we can request the optimization
749     // remark emitter pass on a per-function-basis, which the
750     // OREGetter will do for us.
751     // In the old pass manager, this is harder, so we just build
752     // an optimization remark emitter on the fly, when we need it.
753     std::unique_ptr<OptimizationRemarkEmitter> ORE;
754     auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
755       ORE = std::make_unique<OptimizationRemarkEmitter>(F);
756       return *ORE;
757     };
758 
759     auto LookupDomTree = [this](Function &F) -> DominatorTree & {
760       return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
761     };
762 
763     if (UseCommandLine)
764       return DevirtModule::runForTesting(M, LegacyAARGetter(*this), OREGetter,
765                                          LookupDomTree);
766 
767     return DevirtModule(M, LegacyAARGetter(*this), OREGetter, LookupDomTree,
768                         ExportSummary, ImportSummary)
769         .run();
770   }
771 
772   void getAnalysisUsage(AnalysisUsage &AU) const override {
773     AU.addRequired<AssumptionCacheTracker>();
774     AU.addRequired<TargetLibraryInfoWrapperPass>();
775     AU.addRequired<DominatorTreeWrapperPass>();
776   }
777 };
778 
779 } // end anonymous namespace
780 
781 INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt",
782                       "Whole program devirtualization", false, false)
783 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
784 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
785 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
786 INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt",
787                     "Whole program devirtualization", false, false)
788 char WholeProgramDevirt::ID = 0;
789 
790 ModulePass *
791 llvm::createWholeProgramDevirtPass(ModuleSummaryIndex *ExportSummary,
792                                    const ModuleSummaryIndex *ImportSummary) {
793   return new WholeProgramDevirt(ExportSummary, ImportSummary);
794 }
795 
796 PreservedAnalyses WholeProgramDevirtPass::run(Module &M,
797                                               ModuleAnalysisManager &AM) {
798   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
799   auto AARGetter = [&](Function &F) -> AAResults & {
800     return FAM.getResult<AAManager>(F);
801   };
802   auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
803     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
804   };
805   auto LookupDomTree = [&FAM](Function &F) -> DominatorTree & {
806     return FAM.getResult<DominatorTreeAnalysis>(F);
807   };
808   if (UseCommandLine) {
809     if (DevirtModule::runForTesting(M, AARGetter, OREGetter, LookupDomTree))
810       return PreservedAnalyses::all();
811     return PreservedAnalyses::none();
812   }
813   if (!DevirtModule(M, AARGetter, OREGetter, LookupDomTree, ExportSummary,
814                     ImportSummary)
815            .run())
816     return PreservedAnalyses::all();
817   return PreservedAnalyses::none();
818 }
819 
820 // Enable whole program visibility if enabled by client (e.g. linker) or
821 // internal option, and not force disabled.
822 static bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO) {
823   return (WholeProgramVisibilityEnabledInLTO || WholeProgramVisibility) &&
824          !DisableWholeProgramVisibility;
825 }
826 
827 namespace llvm {
828 
829 /// If whole program visibility asserted, then upgrade all public vcall
830 /// visibility metadata on vtable definitions to linkage unit visibility in
831 /// Module IR (for regular or hybrid LTO).
832 void updateVCallVisibilityInModule(
833     Module &M, bool WholeProgramVisibilityEnabledInLTO,
834     const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) {
835   if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
836     return;
837   for (GlobalVariable &GV : M.globals())
838     // Add linkage unit visibility to any variable with type metadata, which are
839     // the vtable definitions. We won't have an existing vcall_visibility
840     // metadata on vtable definitions with public visibility.
841     if (GV.hasMetadata(LLVMContext::MD_type) &&
842         GV.getVCallVisibility() == GlobalObject::VCallVisibilityPublic &&
843         // Don't upgrade the visibility for symbols exported to the dynamic
844         // linker, as we have no information on their eventual use.
845         !DynamicExportSymbols.count(GV.getGUID()))
846       GV.setVCallVisibilityMetadata(GlobalObject::VCallVisibilityLinkageUnit);
847 }
848 
849 /// If whole program visibility asserted, then upgrade all public vcall
850 /// visibility metadata on vtable definition summaries to linkage unit
851 /// visibility in Module summary index (for ThinLTO).
852 void updateVCallVisibilityInIndex(
853     ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO,
854     const DenseSet<GlobalValue::GUID> &DynamicExportSymbols) {
855   if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
856     return;
857   for (auto &P : Index) {
858     for (auto &S : P.second.SummaryList) {
859       auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
860       if (!GVar ||
861           GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic ||
862           // Don't upgrade the visibility for symbols exported to the dynamic
863           // linker, as we have no information on their eventual use.
864           DynamicExportSymbols.count(P.first))
865         continue;
866       GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
867     }
868   }
869 }
870 
871 void runWholeProgramDevirtOnIndex(
872     ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
873     std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
874   DevirtIndex(Summary, ExportedGUIDs, LocalWPDTargetsMap).run();
875 }
876 
877 void updateIndexWPDForExports(
878     ModuleSummaryIndex &Summary,
879     function_ref<bool(StringRef, ValueInfo)> isExported,
880     std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap) {
881   for (auto &T : LocalWPDTargetsMap) {
882     auto &VI = T.first;
883     // This was enforced earlier during trySingleImplDevirt.
884     assert(VI.getSummaryList().size() == 1 &&
885            "Devirt of local target has more than one copy");
886     auto &S = VI.getSummaryList()[0];
887     if (!isExported(S->modulePath(), VI))
888       continue;
889 
890     // It's been exported by a cross module import.
891     for (auto &SlotSummary : T.second) {
892       auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
893       assert(TIdSum);
894       auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
895       assert(WPDRes != TIdSum->WPDRes.end());
896       WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
897           WPDRes->second.SingleImplName,
898           Summary.getModuleHash(S->modulePath()));
899     }
900   }
901 }
902 
903 } // end namespace llvm
904 
905 static Error checkCombinedSummaryForTesting(ModuleSummaryIndex *Summary) {
906   // Check that summary index contains regular LTO module when performing
907   // export to prevent occasional use of index from pure ThinLTO compilation
908   // (-fno-split-lto-module). This kind of summary index is passed to
909   // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
910   const auto &ModPaths = Summary->modulePaths();
911   if (ClSummaryAction != PassSummaryAction::Import &&
912       ModPaths.find(ModuleSummaryIndex::getRegularLTOModuleName()) ==
913           ModPaths.end())
914     return createStringError(
915         errc::invalid_argument,
916         "combined summary should contain Regular LTO module");
917   return ErrorSuccess();
918 }
919 
920 bool DevirtModule::runForTesting(
921     Module &M, function_ref<AAResults &(Function &)> AARGetter,
922     function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter,
923     function_ref<DominatorTree &(Function &)> LookupDomTree) {
924   std::unique_ptr<ModuleSummaryIndex> Summary =
925       std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
926 
927   // Handle the command-line summary arguments. This code is for testing
928   // purposes only, so we handle errors directly.
929   if (!ClReadSummary.empty()) {
930     ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary +
931                           ": ");
932     auto ReadSummaryFile =
933         ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary)));
934     if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
935             getModuleSummaryIndex(*ReadSummaryFile)) {
936       Summary = std::move(*SummaryOrErr);
937       ExitOnErr(checkCombinedSummaryForTesting(Summary.get()));
938     } else {
939       // Try YAML if we've failed with bitcode.
940       consumeError(SummaryOrErr.takeError());
941       yaml::Input In(ReadSummaryFile->getBuffer());
942       In >> *Summary;
943       ExitOnErr(errorCodeToError(In.error()));
944     }
945   }
946 
947   bool Changed =
948       DevirtModule(M, AARGetter, OREGetter, LookupDomTree,
949                    ClSummaryAction == PassSummaryAction::Export ? Summary.get()
950                                                                 : nullptr,
951                    ClSummaryAction == PassSummaryAction::Import ? Summary.get()
952                                                                 : nullptr)
953           .run();
954 
955   if (!ClWriteSummary.empty()) {
956     ExitOnError ExitOnErr(
957         "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": ");
958     std::error_code EC;
959     if (StringRef(ClWriteSummary).endswith(".bc")) {
960       raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_None);
961       ExitOnErr(errorCodeToError(EC));
962       WriteIndexToFile(*Summary, OS);
963     } else {
964       raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::OF_TextWithCRLF);
965       ExitOnErr(errorCodeToError(EC));
966       yaml::Output Out(OS);
967       Out << *Summary;
968     }
969   }
970 
971   return Changed;
972 }
973 
974 void DevirtModule::buildTypeIdentifierMap(
975     std::vector<VTableBits> &Bits,
976     DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
977   DenseMap<GlobalVariable *, VTableBits *> GVToBits;
978   Bits.reserve(M.getGlobalList().size());
979   SmallVector<MDNode *, 2> Types;
980   for (GlobalVariable &GV : M.globals()) {
981     Types.clear();
982     GV.getMetadata(LLVMContext::MD_type, Types);
983     if (GV.isDeclaration() || Types.empty())
984       continue;
985 
986     VTableBits *&BitsPtr = GVToBits[&GV];
987     if (!BitsPtr) {
988       Bits.emplace_back();
989       Bits.back().GV = &GV;
990       Bits.back().ObjectSize =
991           M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
992       BitsPtr = &Bits.back();
993     }
994 
995     for (MDNode *Type : Types) {
996       auto TypeID = Type->getOperand(1).get();
997 
998       uint64_t Offset =
999           cast<ConstantInt>(
1000               cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
1001               ->getZExtValue();
1002 
1003       TypeIdMap[TypeID].insert({BitsPtr, Offset});
1004     }
1005   }
1006 }
1007 
1008 bool DevirtModule::tryFindVirtualCallTargets(
1009     std::vector<VirtualCallTarget> &TargetsForSlot,
1010     const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset,
1011     ModuleSummaryIndex *ExportSummary) {
1012   for (const TypeMemberInfo &TM : TypeMemberInfos) {
1013     if (!TM.Bits->GV->isConstant())
1014       return false;
1015 
1016     // We cannot perform whole program devirtualization analysis on a vtable
1017     // with public LTO visibility.
1018     if (TM.Bits->GV->getVCallVisibility() ==
1019         GlobalObject::VCallVisibilityPublic)
1020       return false;
1021 
1022     Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(),
1023                                        TM.Offset + ByteOffset, M);
1024     if (!Ptr)
1025       return false;
1026 
1027     auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts());
1028     if (!Fn)
1029       return false;
1030 
1031     if (FunctionsToSkip.match(Fn->getName()))
1032       return false;
1033 
1034     // We can disregard __cxa_pure_virtual as a possible call target, as
1035     // calls to pure virtuals are UB.
1036     if (Fn->getName() == "__cxa_pure_virtual")
1037       continue;
1038 
1039     // We can disregard unreachable functions as possible call targets, as
1040     // unreachable functions shouldn't be called.
1041     if (ExportSummary && (mustBeUnreachableFunction(
1042                              lookUpFunctionValueInfo(Fn, ExportSummary)))) {
1043       continue;
1044     }
1045 
1046     TargetsForSlot.push_back({Fn, &TM});
1047   }
1048 
1049   // Give up if we couldn't find any targets.
1050   return !TargetsForSlot.empty();
1051 }
1052 
1053 bool DevirtIndex::tryFindVirtualCallTargets(
1054     std::vector<ValueInfo> &TargetsForSlot, const TypeIdCompatibleVtableInfo TIdInfo,
1055     uint64_t ByteOffset) {
1056   for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
1057     // Find a representative copy of the vtable initializer.
1058     // We can have multiple available_externally, linkonce_odr and weak_odr
1059     // vtable initializers. We can also have multiple external vtable
1060     // initializers in the case of comdats, which we cannot check here.
1061     // The linker should give an error in this case.
1062     //
1063     // Also, handle the case of same-named local Vtables with the same path
1064     // and therefore the same GUID. This can happen if there isn't enough
1065     // distinguishing path when compiling the source file. In that case we
1066     // conservatively return false early.
1067     const GlobalVarSummary *VS = nullptr;
1068     bool LocalFound = false;
1069     for (auto &S : P.VTableVI.getSummaryList()) {
1070       if (GlobalValue::isLocalLinkage(S->linkage())) {
1071         if (LocalFound)
1072           return false;
1073         LocalFound = true;
1074       }
1075       auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject());
1076       if (!CurVS->vTableFuncs().empty() ||
1077           // Previously clang did not attach the necessary type metadata to
1078           // available_externally vtables, in which case there would not
1079           // be any vtable functions listed in the summary and we need
1080           // to treat this case conservatively (in case the bitcode is old).
1081           // However, we will also not have any vtable functions in the
1082           // case of a pure virtual base class. In that case we do want
1083           // to set VS to avoid treating it conservatively.
1084           !GlobalValue::isAvailableExternallyLinkage(S->linkage())) {
1085         VS = CurVS;
1086         // We cannot perform whole program devirtualization analysis on a vtable
1087         // with public LTO visibility.
1088         if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic)
1089           return false;
1090       }
1091     }
1092     // There will be no VS if all copies are available_externally having no
1093     // type metadata. In that case we can't safely perform WPD.
1094     if (!VS)
1095       return false;
1096     if (!VS->isLive())
1097       continue;
1098     for (auto VTP : VS->vTableFuncs()) {
1099       if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
1100         continue;
1101 
1102       TargetsForSlot.push_back(VTP.FuncVI);
1103     }
1104   }
1105 
1106   // Give up if we couldn't find any targets.
1107   return !TargetsForSlot.empty();
1108 }
1109 
1110 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
1111                                          Constant *TheFn, bool &IsExported) {
1112   // Don't devirtualize function if we're told to skip it
1113   // in -wholeprogramdevirt-skip.
1114   if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName()))
1115     return;
1116   auto Apply = [&](CallSiteInfo &CSInfo) {
1117     for (auto &&VCallSite : CSInfo.CallSites) {
1118       if (!OptimizedCalls.insert(&VCallSite.CB).second)
1119         continue;
1120 
1121       if (RemarksEnabled)
1122         VCallSite.emitRemark("single-impl",
1123                              TheFn->stripPointerCasts()->getName(), OREGetter);
1124       auto &CB = VCallSite.CB;
1125       assert(!CB.getCalledFunction() && "devirtualizing direct call?");
1126       IRBuilder<> Builder(&CB);
1127       Value *Callee =
1128           Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType());
1129 
1130       // If checking is enabled, add support to compare the virtual function
1131       // pointer to the devirtualized target. In case of a mismatch, perform a
1132       // debug trap.
1133       if (CheckDevirt) {
1134         auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee);
1135         Instruction *ThenTerm =
1136             SplitBlockAndInsertIfThen(Cond, &CB, /*Unreachable=*/false);
1137         Builder.SetInsertPoint(ThenTerm);
1138         Function *TrapFn = Intrinsic::getDeclaration(&M, Intrinsic::debugtrap);
1139         auto *CallTrap = Builder.CreateCall(TrapFn);
1140         CallTrap->setDebugLoc(CB.getDebugLoc());
1141       }
1142 
1143       // Devirtualize.
1144       CB.setCalledOperand(Callee);
1145 
1146       // This use is no longer unsafe.
1147       if (VCallSite.NumUnsafeUses)
1148         --*VCallSite.NumUnsafeUses;
1149     }
1150     if (CSInfo.isExported())
1151       IsExported = true;
1152     CSInfo.markDevirt();
1153   };
1154   Apply(SlotInfo.CSInfo);
1155   for (auto &P : SlotInfo.ConstCSInfo)
1156     Apply(P.second);
1157 }
1158 
1159 static bool AddCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
1160   // We can't add calls if we haven't seen a definition
1161   if (Callee.getSummaryList().empty())
1162     return false;
1163 
1164   // Insert calls into the summary index so that the devirtualized targets
1165   // are eligible for import.
1166   // FIXME: Annotate type tests with hotness. For now, mark these as hot
1167   // to better ensure we have the opportunity to inline them.
1168   bool IsExported = false;
1169   auto &S = Callee.getSummaryList()[0];
1170   CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* RelBF = */ 0);
1171   auto AddCalls = [&](CallSiteInfo &CSInfo) {
1172     for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
1173       FS->addCall({Callee, CI});
1174       IsExported |= S->modulePath() != FS->modulePath();
1175     }
1176     for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
1177       FS->addCall({Callee, CI});
1178       IsExported |= S->modulePath() != FS->modulePath();
1179     }
1180   };
1181   AddCalls(SlotInfo.CSInfo);
1182   for (auto &P : SlotInfo.ConstCSInfo)
1183     AddCalls(P.second);
1184   return IsExported;
1185 }
1186 
1187 bool DevirtModule::trySingleImplDevirt(
1188     ModuleSummaryIndex *ExportSummary,
1189     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1190     WholeProgramDevirtResolution *Res) {
1191   // See if the program contains a single implementation of this virtual
1192   // function.
1193   Function *TheFn = TargetsForSlot[0].Fn;
1194   for (auto &&Target : TargetsForSlot)
1195     if (TheFn != Target.Fn)
1196       return false;
1197 
1198   // If so, update each call site to call that implementation directly.
1199   if (RemarksEnabled)
1200     TargetsForSlot[0].WasDevirt = true;
1201 
1202   bool IsExported = false;
1203   applySingleImplDevirt(SlotInfo, TheFn, IsExported);
1204   if (!IsExported)
1205     return false;
1206 
1207   // If the only implementation has local linkage, we must promote to external
1208   // to make it visible to thin LTO objects. We can only get here during the
1209   // ThinLTO export phase.
1210   if (TheFn->hasLocalLinkage()) {
1211     std::string NewName = (TheFn->getName() + ".llvm.merged").str();
1212 
1213     // Since we are renaming the function, any comdats with the same name must
1214     // also be renamed. This is required when targeting COFF, as the comdat name
1215     // must match one of the names of the symbols in the comdat.
1216     if (Comdat *C = TheFn->getComdat()) {
1217       if (C->getName() == TheFn->getName()) {
1218         Comdat *NewC = M.getOrInsertComdat(NewName);
1219         NewC->setSelectionKind(C->getSelectionKind());
1220         for (GlobalObject &GO : M.global_objects())
1221           if (GO.getComdat() == C)
1222             GO.setComdat(NewC);
1223       }
1224     }
1225 
1226     TheFn->setLinkage(GlobalValue::ExternalLinkage);
1227     TheFn->setVisibility(GlobalValue::HiddenVisibility);
1228     TheFn->setName(NewName);
1229   }
1230   if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
1231     // Any needed promotion of 'TheFn' has already been done during
1232     // LTO unit split, so we can ignore return value of AddCalls.
1233     AddCalls(SlotInfo, TheFnVI);
1234 
1235   Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1236   Res->SingleImplName = std::string(TheFn->getName());
1237 
1238   return true;
1239 }
1240 
1241 bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
1242                                       VTableSlotSummary &SlotSummary,
1243                                       VTableSlotInfo &SlotInfo,
1244                                       WholeProgramDevirtResolution *Res,
1245                                       std::set<ValueInfo> &DevirtTargets) {
1246   // See if the program contains a single implementation of this virtual
1247   // function.
1248   auto TheFn = TargetsForSlot[0];
1249   for (auto &&Target : TargetsForSlot)
1250     if (TheFn != Target)
1251       return false;
1252 
1253   // Don't devirtualize if we don't have target definition.
1254   auto Size = TheFn.getSummaryList().size();
1255   if (!Size)
1256     return false;
1257 
1258   // Don't devirtualize function if we're told to skip it
1259   // in -wholeprogramdevirt-skip.
1260   if (FunctionsToSkip.match(TheFn.name()))
1261     return false;
1262 
1263   // If the summary list contains multiple summaries where at least one is
1264   // a local, give up, as we won't know which (possibly promoted) name to use.
1265   for (auto &S : TheFn.getSummaryList())
1266     if (GlobalValue::isLocalLinkage(S->linkage()) && Size > 1)
1267       return false;
1268 
1269   // Collect functions devirtualized at least for one call site for stats.
1270   if (PrintSummaryDevirt)
1271     DevirtTargets.insert(TheFn);
1272 
1273   auto &S = TheFn.getSummaryList()[0];
1274   bool IsExported = AddCalls(SlotInfo, TheFn);
1275   if (IsExported)
1276     ExportedGUIDs.insert(TheFn.getGUID());
1277 
1278   // Record in summary for use in devirtualization during the ThinLTO import
1279   // step.
1280   Res->TheKind = WholeProgramDevirtResolution::SingleImpl;
1281   if (GlobalValue::isLocalLinkage(S->linkage())) {
1282     if (IsExported)
1283       // If target is a local function and we are exporting it by
1284       // devirtualizing a call in another module, we need to record the
1285       // promoted name.
1286       Res->SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
1287           TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
1288     else {
1289       LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1290       Res->SingleImplName = std::string(TheFn.name());
1291     }
1292   } else
1293     Res->SingleImplName = std::string(TheFn.name());
1294 
1295   // Name will be empty if this thin link driven off of serialized combined
1296   // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
1297   // legacy LTO API anyway.
1298   assert(!Res->SingleImplName.empty());
1299 
1300   return true;
1301 }
1302 
1303 void DevirtModule::tryICallBranchFunnel(
1304     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1305     WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1306   Triple T(M.getTargetTriple());
1307   if (T.getArch() != Triple::x86_64)
1308     return;
1309 
1310   if (TargetsForSlot.size() > ClThreshold)
1311     return;
1312 
1313   bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1314   if (!HasNonDevirt)
1315     for (auto &P : SlotInfo.ConstCSInfo)
1316       if (!P.second.AllCallSitesDevirted) {
1317         HasNonDevirt = true;
1318         break;
1319       }
1320 
1321   if (!HasNonDevirt)
1322     return;
1323 
1324   FunctionType *FT =
1325       FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
1326   Function *JT;
1327   if (isa<MDString>(Slot.TypeID)) {
1328     JT = Function::Create(FT, Function::ExternalLinkage,
1329                           M.getDataLayout().getProgramAddressSpace(),
1330                           getGlobalName(Slot, {}, "branch_funnel"), &M);
1331     JT->setVisibility(GlobalValue::HiddenVisibility);
1332   } else {
1333     JT = Function::Create(FT, Function::InternalLinkage,
1334                           M.getDataLayout().getProgramAddressSpace(),
1335                           "branch_funnel", &M);
1336   }
1337   JT->addParamAttr(0, Attribute::Nest);
1338 
1339   std::vector<Value *> JTArgs;
1340   JTArgs.push_back(JT->arg_begin());
1341   for (auto &T : TargetsForSlot) {
1342     JTArgs.push_back(getMemberAddr(T.TM));
1343     JTArgs.push_back(T.Fn);
1344   }
1345 
1346   BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
1347   Function *Intr =
1348       Intrinsic::getDeclaration(&M, llvm::Intrinsic::icall_branch_funnel, {});
1349 
1350   auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
1351   CI->setTailCallKind(CallInst::TCK_MustTail);
1352   ReturnInst::Create(M.getContext(), nullptr, BB);
1353 
1354   bool IsExported = false;
1355   applyICallBranchFunnel(SlotInfo, JT, IsExported);
1356   if (IsExported)
1357     Res->TheKind = WholeProgramDevirtResolution::BranchFunnel;
1358 }
1359 
1360 void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1361                                           Constant *JT, bool &IsExported) {
1362   auto Apply = [&](CallSiteInfo &CSInfo) {
1363     if (CSInfo.isExported())
1364       IsExported = true;
1365     if (CSInfo.AllCallSitesDevirted)
1366       return;
1367     for (auto &&VCallSite : CSInfo.CallSites) {
1368       CallBase &CB = VCallSite.CB;
1369 
1370       // Jump tables are only profitable if the retpoline mitigation is enabled.
1371       Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features");
1372       if (!FSAttr.isValid() ||
1373           !FSAttr.getValueAsString().contains("+retpoline"))
1374         continue;
1375 
1376       if (RemarksEnabled)
1377         VCallSite.emitRemark("branch-funnel",
1378                              JT->stripPointerCasts()->getName(), OREGetter);
1379 
1380       // Pass the address of the vtable in the nest register, which is r10 on
1381       // x86_64.
1382       std::vector<Type *> NewArgs;
1383       NewArgs.push_back(Int8PtrTy);
1384       append_range(NewArgs, CB.getFunctionType()->params());
1385       FunctionType *NewFT =
1386           FunctionType::get(CB.getFunctionType()->getReturnType(), NewArgs,
1387                             CB.getFunctionType()->isVarArg());
1388       PointerType *NewFTPtr = PointerType::getUnqual(NewFT);
1389 
1390       IRBuilder<> IRB(&CB);
1391       std::vector<Value *> Args;
1392       Args.push_back(IRB.CreateBitCast(VCallSite.VTable, Int8PtrTy));
1393       llvm::append_range(Args, CB.args());
1394 
1395       CallBase *NewCS = nullptr;
1396       if (isa<CallInst>(CB))
1397         NewCS = IRB.CreateCall(NewFT, IRB.CreateBitCast(JT, NewFTPtr), Args);
1398       else
1399         NewCS = IRB.CreateInvoke(NewFT, IRB.CreateBitCast(JT, NewFTPtr),
1400                                  cast<InvokeInst>(CB).getNormalDest(),
1401                                  cast<InvokeInst>(CB).getUnwindDest(), Args);
1402       NewCS->setCallingConv(CB.getCallingConv());
1403 
1404       AttributeList Attrs = CB.getAttributes();
1405       std::vector<AttributeSet> NewArgAttrs;
1406       NewArgAttrs.push_back(AttributeSet::get(
1407           M.getContext(), ArrayRef<Attribute>{Attribute::get(
1408                               M.getContext(), Attribute::Nest)}));
1409       for (unsigned I = 0; I + 2 <  Attrs.getNumAttrSets(); ++I)
1410         NewArgAttrs.push_back(Attrs.getParamAttrs(I));
1411       NewCS->setAttributes(
1412           AttributeList::get(M.getContext(), Attrs.getFnAttrs(),
1413                              Attrs.getRetAttrs(), NewArgAttrs));
1414 
1415       CB.replaceAllUsesWith(NewCS);
1416       CB.eraseFromParent();
1417 
1418       // This use is no longer unsafe.
1419       if (VCallSite.NumUnsafeUses)
1420         --*VCallSite.NumUnsafeUses;
1421     }
1422     // Don't mark as devirtualized because there may be callers compiled without
1423     // retpoline mitigation, which would mean that they are lowered to
1424     // llvm.type.test and therefore require an llvm.type.test resolution for the
1425     // type identifier.
1426   };
1427   Apply(SlotInfo.CSInfo);
1428   for (auto &P : SlotInfo.ConstCSInfo)
1429     Apply(P.second);
1430 }
1431 
1432 bool DevirtModule::tryEvaluateFunctionsWithArgs(
1433     MutableArrayRef<VirtualCallTarget> TargetsForSlot,
1434     ArrayRef<uint64_t> Args) {
1435   // Evaluate each function and store the result in each target's RetVal
1436   // field.
1437   for (VirtualCallTarget &Target : TargetsForSlot) {
1438     if (Target.Fn->arg_size() != Args.size() + 1)
1439       return false;
1440 
1441     Evaluator Eval(M.getDataLayout(), nullptr);
1442     SmallVector<Constant *, 2> EvalArgs;
1443     EvalArgs.push_back(
1444         Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0)));
1445     for (unsigned I = 0; I != Args.size(); ++I) {
1446       auto *ArgTy = dyn_cast<IntegerType>(
1447           Target.Fn->getFunctionType()->getParamType(I + 1));
1448       if (!ArgTy)
1449         return false;
1450       EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
1451     }
1452 
1453     Constant *RetVal;
1454     if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) ||
1455         !isa<ConstantInt>(RetVal))
1456       return false;
1457     Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
1458   }
1459   return true;
1460 }
1461 
1462 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1463                                          uint64_t TheRetVal) {
1464   for (auto Call : CSInfo.CallSites) {
1465     if (!OptimizedCalls.insert(&Call.CB).second)
1466       continue;
1467     Call.replaceAndErase(
1468         "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
1469         ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal));
1470   }
1471   CSInfo.markDevirt();
1472 }
1473 
1474 bool DevirtModule::tryUniformRetValOpt(
1475     MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1476     WholeProgramDevirtResolution::ByArg *Res) {
1477   // Uniform return value optimization. If all functions return the same
1478   // constant, replace all calls with that constant.
1479   uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1480   for (const VirtualCallTarget &Target : TargetsForSlot)
1481     if (Target.RetVal != TheRetVal)
1482       return false;
1483 
1484   if (CSInfo.isExported()) {
1485     Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
1486     Res->Info = TheRetVal;
1487   }
1488 
1489   applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
1490   if (RemarksEnabled)
1491     for (auto &&Target : TargetsForSlot)
1492       Target.WasDevirt = true;
1493   return true;
1494 }
1495 
1496 std::string DevirtModule::getGlobalName(VTableSlot Slot,
1497                                         ArrayRef<uint64_t> Args,
1498                                         StringRef Name) {
1499   std::string FullName = "__typeid_";
1500   raw_string_ostream OS(FullName);
1501   OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1502   for (uint64_t Arg : Args)
1503     OS << '_' << Arg;
1504   OS << '_' << Name;
1505   return OS.str();
1506 }
1507 
1508 bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1509   Triple T(M.getTargetTriple());
1510   return T.isX86() && T.getObjectFormat() == Triple::ELF;
1511 }
1512 
1513 void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1514                                 StringRef Name, Constant *C) {
1515   GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1516                                         getGlobalName(Slot, Args, Name), C, &M);
1517   GA->setVisibility(GlobalValue::HiddenVisibility);
1518 }
1519 
1520 void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1521                                   StringRef Name, uint32_t Const,
1522                                   uint32_t &Storage) {
1523   if (shouldExportConstantsAsAbsoluteSymbols()) {
1524     exportGlobal(
1525         Slot, Args, Name,
1526         ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1527     return;
1528   }
1529 
1530   Storage = Const;
1531 }
1532 
1533 Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1534                                      StringRef Name) {
1535   Constant *C =
1536       M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
1537   auto *GV = dyn_cast<GlobalVariable>(C);
1538   if (GV)
1539     GV->setVisibility(GlobalValue::HiddenVisibility);
1540   return C;
1541 }
1542 
1543 Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1544                                        StringRef Name, IntegerType *IntTy,
1545                                        uint32_t Storage) {
1546   if (!shouldExportConstantsAsAbsoluteSymbols())
1547     return ConstantInt::get(IntTy, Storage);
1548 
1549   Constant *C = importGlobal(Slot, Args, Name);
1550   auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1551   C = ConstantExpr::getPtrToInt(C, IntTy);
1552 
1553   // We only need to set metadata if the global is newly created, in which
1554   // case it would not have hidden visibility.
1555   if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
1556     return C;
1557 
1558   auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1559     auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1560     auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1561     GV->setMetadata(LLVMContext::MD_absolute_symbol,
1562                     MDNode::get(M.getContext(), {MinC, MaxC}));
1563   };
1564   unsigned AbsWidth = IntTy->getBitWidth();
1565   if (AbsWidth == IntPtrTy->getBitWidth())
1566     SetAbsRange(~0ull, ~0ull); // Full set.
1567   else
1568     SetAbsRange(0, 1ull << AbsWidth);
1569   return C;
1570 }
1571 
1572 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1573                                         bool IsOne,
1574                                         Constant *UniqueMemberAddr) {
1575   for (auto &&Call : CSInfo.CallSites) {
1576     if (!OptimizedCalls.insert(&Call.CB).second)
1577       continue;
1578     IRBuilder<> B(&Call.CB);
1579     Value *Cmp =
1580         B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable,
1581                      B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType()));
1582     Cmp = B.CreateZExt(Cmp, Call.CB.getType());
1583     Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1584                          Cmp);
1585   }
1586   CSInfo.markDevirt();
1587 }
1588 
1589 Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1590   Constant *C = ConstantExpr::getBitCast(M->Bits->GV, Int8PtrTy);
1591   return ConstantExpr::getGetElementPtr(Int8Ty, C,
1592                                         ConstantInt::get(Int64Ty, M->Offset));
1593 }
1594 
1595 bool DevirtModule::tryUniqueRetValOpt(
1596     unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
1597     CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1598     VTableSlot Slot, ArrayRef<uint64_t> Args) {
1599   // IsOne controls whether we look for a 0 or a 1.
1600   auto tryUniqueRetValOptFor = [&](bool IsOne) {
1601     const TypeMemberInfo *UniqueMember = nullptr;
1602     for (const VirtualCallTarget &Target : TargetsForSlot) {
1603       if (Target.RetVal == (IsOne ? 1 : 0)) {
1604         if (UniqueMember)
1605           return false;
1606         UniqueMember = Target.TM;
1607       }
1608     }
1609 
1610     // We should have found a unique member or bailed out by now. We already
1611     // checked for a uniform return value in tryUniformRetValOpt.
1612     assert(UniqueMember);
1613 
1614     Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
1615     if (CSInfo.isExported()) {
1616       Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
1617       Res->Info = IsOne;
1618 
1619       exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1620     }
1621 
1622     // Replace each call with the comparison.
1623     applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1624                          UniqueMemberAddr);
1625 
1626     // Update devirtualization statistics for targets.
1627     if (RemarksEnabled)
1628       for (auto &&Target : TargetsForSlot)
1629         Target.WasDevirt = true;
1630 
1631     return true;
1632   };
1633 
1634   if (BitWidth == 1) {
1635     if (tryUniqueRetValOptFor(true))
1636       return true;
1637     if (tryUniqueRetValOptFor(false))
1638       return true;
1639   }
1640   return false;
1641 }
1642 
1643 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1644                                          Constant *Byte, Constant *Bit) {
1645   for (auto Call : CSInfo.CallSites) {
1646     if (!OptimizedCalls.insert(&Call.CB).second)
1647       continue;
1648     auto *RetType = cast<IntegerType>(Call.CB.getType());
1649     IRBuilder<> B(&Call.CB);
1650     Value *Addr =
1651         B.CreateGEP(Int8Ty, B.CreateBitCast(Call.VTable, Int8PtrTy), Byte);
1652     if (RetType->getBitWidth() == 1) {
1653       Value *Bits = B.CreateLoad(Int8Ty, Addr);
1654       Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1655       auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1656       Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
1657                            OREGetter, IsBitSet);
1658     } else {
1659       Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo());
1660       Value *Val = B.CreateLoad(RetType, ValAddr);
1661       Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1662                            OREGetter, Val);
1663     }
1664   }
1665   CSInfo.markDevirt();
1666 }
1667 
1668 bool DevirtModule::tryVirtualConstProp(
1669     MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1670     WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1671   // This only works if the function returns an integer.
1672   auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType());
1673   if (!RetType)
1674     return false;
1675   unsigned BitWidth = RetType->getBitWidth();
1676   if (BitWidth > 64)
1677     return false;
1678 
1679   // Make sure that each function is defined, does not access memory, takes at
1680   // least one argument, does not use its first argument (which we assume is
1681   // 'this'), and has the same return type.
1682   //
1683   // Note that we test whether this copy of the function is readnone, rather
1684   // than testing function attributes, which must hold for any copy of the
1685   // function, even a less optimized version substituted at link time. This is
1686   // sound because the virtual constant propagation optimizations effectively
1687   // inline all implementations of the virtual function into each call site,
1688   // rather than using function attributes to perform local optimization.
1689   for (VirtualCallTarget &Target : TargetsForSlot) {
1690     if (Target.Fn->isDeclaration() ||
1691         computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) !=
1692             MAK_ReadNone ||
1693         Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() ||
1694         Target.Fn->getReturnType() != RetType)
1695       return false;
1696   }
1697 
1698   for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1699     if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1700       continue;
1701 
1702     WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1703     if (Res)
1704       ResByArg = &Res->ResByArg[CSByConstantArg.first];
1705 
1706     if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1707       continue;
1708 
1709     if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1710                            ResByArg, Slot, CSByConstantArg.first))
1711       continue;
1712 
1713     // Find an allocation offset in bits in all vtables associated with the
1714     // type.
1715     uint64_t AllocBefore =
1716         findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1717     uint64_t AllocAfter =
1718         findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1719 
1720     // Calculate the total amount of padding needed to store a value at both
1721     // ends of the object.
1722     uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1723     for (auto &&Target : TargetsForSlot) {
1724       TotalPaddingBefore += std::max<int64_t>(
1725           (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1726       TotalPaddingAfter += std::max<int64_t>(
1727           (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1728     }
1729 
1730     // If the amount of padding is too large, give up.
1731     // FIXME: do something smarter here.
1732     if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1733       continue;
1734 
1735     // Calculate the offset to the value as a (possibly negative) byte offset
1736     // and (if applicable) a bit offset, and store the values in the targets.
1737     int64_t OffsetByte;
1738     uint64_t OffsetBit;
1739     if (TotalPaddingBefore <= TotalPaddingAfter)
1740       setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
1741                             OffsetBit);
1742     else
1743       setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
1744                            OffsetBit);
1745 
1746     if (RemarksEnabled)
1747       for (auto &&Target : TargetsForSlot)
1748         Target.WasDevirt = true;
1749 
1750 
1751     if (CSByConstantArg.second.isExported()) {
1752       ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
1753       exportConstant(Slot, CSByConstantArg.first, "byte", OffsetByte,
1754                      ResByArg->Byte);
1755       exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
1756                      ResByArg->Bit);
1757     }
1758 
1759     // Rewrite each call to a load from OffsetByte/OffsetBit.
1760     Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte);
1761     Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
1762     applyVirtualConstProp(CSByConstantArg.second,
1763                           TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
1764   }
1765   return true;
1766 }
1767 
1768 void DevirtModule::rebuildGlobal(VTableBits &B) {
1769   if (B.Before.Bytes.empty() && B.After.Bytes.empty())
1770     return;
1771 
1772   // Align the before byte array to the global's minimum alignment so that we
1773   // don't break any alignment requirements on the global.
1774   Align Alignment = M.getDataLayout().getValueOrABITypeAlignment(
1775       B.GV->getAlign(), B.GV->getValueType());
1776   B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
1777 
1778   // Before was stored in reverse order; flip it now.
1779   for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
1780     std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
1781 
1782   // Build an anonymous global containing the before bytes, followed by the
1783   // original initializer, followed by the after bytes.
1784   auto NewInit = ConstantStruct::getAnon(
1785       {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
1786        B.GV->getInitializer(),
1787        ConstantDataArray::get(M.getContext(), B.After.Bytes)});
1788   auto NewGV =
1789       new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
1790                          GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
1791   NewGV->setSection(B.GV->getSection());
1792   NewGV->setComdat(B.GV->getComdat());
1793   NewGV->setAlignment(B.GV->getAlign());
1794 
1795   // Copy the original vtable's metadata to the anonymous global, adjusting
1796   // offsets as required.
1797   NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
1798 
1799   // Build an alias named after the original global, pointing at the second
1800   // element (the original initializer).
1801   auto Alias = GlobalAlias::create(
1802       B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
1803       ConstantExpr::getGetElementPtr(
1804           NewInit->getType(), NewGV,
1805           ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0),
1806                                ConstantInt::get(Int32Ty, 1)}),
1807       &M);
1808   Alias->setVisibility(B.GV->getVisibility());
1809   Alias->takeName(B.GV);
1810 
1811   B.GV->replaceAllUsesWith(Alias);
1812   B.GV->eraseFromParent();
1813 }
1814 
1815 bool DevirtModule::areRemarksEnabled() {
1816   const auto &FL = M.getFunctionList();
1817   for (const Function &Fn : FL) {
1818     const auto &BBL = Fn.getBasicBlockList();
1819     if (BBL.empty())
1820       continue;
1821     auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front());
1822     return DI.isEnabled();
1823   }
1824   return false;
1825 }
1826 
1827 void DevirtModule::scanTypeTestUsers(
1828     Function *TypeTestFunc,
1829     DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
1830   // Find all virtual calls via a virtual table pointer %p under an assumption
1831   // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p
1832   // points to a member of the type identifier %md. Group calls by (type ID,
1833   // offset) pair (effectively the identity of the virtual function) and store
1834   // to CallSlots.
1835   for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) {
1836     auto *CI = dyn_cast<CallInst>(U.getUser());
1837     if (!CI)
1838       continue;
1839 
1840     // Search for virtual calls based on %p and add them to DevirtCalls.
1841     SmallVector<DevirtCallSite, 1> DevirtCalls;
1842     SmallVector<CallInst *, 1> Assumes;
1843     auto &DT = LookupDomTree(*CI->getFunction());
1844     findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
1845 
1846     Metadata *TypeId =
1847         cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
1848     // If we found any, add them to CallSlots.
1849     if (!Assumes.empty()) {
1850       Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
1851       for (DevirtCallSite Call : DevirtCalls)
1852         CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr);
1853     }
1854 
1855     auto RemoveTypeTestAssumes = [&]() {
1856       // We no longer need the assumes or the type test.
1857       for (auto Assume : Assumes)
1858         Assume->eraseFromParent();
1859       // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
1860       // may use the vtable argument later.
1861       if (CI->use_empty())
1862         CI->eraseFromParent();
1863     };
1864 
1865     // At this point we could remove all type test assume sequences, as they
1866     // were originally inserted for WPD. However, we can keep these in the
1867     // code stream for later analysis (e.g. to help drive more efficient ICP
1868     // sequences). They will eventually be removed by a second LowerTypeTests
1869     // invocation that cleans them up. In order to do this correctly, the first
1870     // LowerTypeTests invocation needs to know that they have "Unknown" type
1871     // test resolution, so that they aren't treated as Unsat and lowered to
1872     // False, which will break any uses on assumes. Below we remove any type
1873     // test assumes that will not be treated as Unknown by LTT.
1874 
1875     // The type test assumes will be treated by LTT as Unsat if the type id is
1876     // not used on a global (in which case it has no entry in the TypeIdMap).
1877     if (!TypeIdMap.count(TypeId))
1878       RemoveTypeTestAssumes();
1879 
1880     // For ThinLTO importing, we need to remove the type test assumes if this is
1881     // an MDString type id without a corresponding TypeIdSummary. Any
1882     // non-MDString type ids are ignored and treated as Unknown by LTT, so their
1883     // type test assumes can be kept. If the MDString type id is missing a
1884     // TypeIdSummary (e.g. because there was no use on a vcall, preventing the
1885     // exporting phase of WPD from analyzing it), then it would be treated as
1886     // Unsat by LTT and we need to remove its type test assumes here. If not
1887     // used on a vcall we don't need them for later optimization use in any
1888     // case.
1889     else if (ImportSummary && isa<MDString>(TypeId)) {
1890       const TypeIdSummary *TidSummary =
1891           ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString());
1892       if (!TidSummary)
1893         RemoveTypeTestAssumes();
1894       else
1895         // If one was created it should not be Unsat, because if we reached here
1896         // the type id was used on a global.
1897         assert(TidSummary->TTRes.TheKind != TypeTestResolution::Unsat);
1898     }
1899   }
1900 }
1901 
1902 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
1903   Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test);
1904 
1905   for (Use &U : llvm::make_early_inc_range(TypeCheckedLoadFunc->uses())) {
1906     auto *CI = dyn_cast<CallInst>(U.getUser());
1907     if (!CI)
1908       continue;
1909 
1910     Value *Ptr = CI->getArgOperand(0);
1911     Value *Offset = CI->getArgOperand(1);
1912     Value *TypeIdValue = CI->getArgOperand(2);
1913     Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
1914 
1915     SmallVector<DevirtCallSite, 1> DevirtCalls;
1916     SmallVector<Instruction *, 1> LoadedPtrs;
1917     SmallVector<Instruction *, 1> Preds;
1918     bool HasNonCallUses = false;
1919     auto &DT = LookupDomTree(*CI->getFunction());
1920     findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
1921                                                HasNonCallUses, CI, DT);
1922 
1923     // Start by generating "pessimistic" code that explicitly loads the function
1924     // pointer from the vtable and performs the type check. If possible, we will
1925     // eliminate the load and the type check later.
1926 
1927     // If possible, only generate the load at the point where it is used.
1928     // This helps avoid unnecessary spills.
1929     IRBuilder<> LoadB(
1930         (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
1931     Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset);
1932     Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy));
1933     Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr);
1934 
1935     for (Instruction *LoadedPtr : LoadedPtrs) {
1936       LoadedPtr->replaceAllUsesWith(LoadedValue);
1937       LoadedPtr->eraseFromParent();
1938     }
1939 
1940     // Likewise for the type test.
1941     IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
1942     CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
1943 
1944     for (Instruction *Pred : Preds) {
1945       Pred->replaceAllUsesWith(TypeTestCall);
1946       Pred->eraseFromParent();
1947     }
1948 
1949     // We have already erased any extractvalue instructions that refer to the
1950     // intrinsic call, but the intrinsic may have other non-extractvalue uses
1951     // (although this is unlikely). In that case, explicitly build a pair and
1952     // RAUW it.
1953     if (!CI->use_empty()) {
1954       Value *Pair = UndefValue::get(CI->getType());
1955       IRBuilder<> B(CI);
1956       Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
1957       Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
1958       CI->replaceAllUsesWith(Pair);
1959     }
1960 
1961     // The number of unsafe uses is initially the number of uses.
1962     auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
1963     NumUnsafeUses = DevirtCalls.size();
1964 
1965     // If the function pointer has a non-call user, we cannot eliminate the type
1966     // check, as one of those users may eventually call the pointer. Increment
1967     // the unsafe use count to make sure it cannot reach zero.
1968     if (HasNonCallUses)
1969       ++NumUnsafeUses;
1970     for (DevirtCallSite Call : DevirtCalls) {
1971       CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB,
1972                                                    &NumUnsafeUses);
1973     }
1974 
1975     CI->eraseFromParent();
1976   }
1977 }
1978 
1979 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
1980   auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
1981   if (!TypeId)
1982     return;
1983   const TypeIdSummary *TidSummary =
1984       ImportSummary->getTypeIdSummary(TypeId->getString());
1985   if (!TidSummary)
1986     return;
1987   auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
1988   if (ResI == TidSummary->WPDRes.end())
1989     return;
1990   const WholeProgramDevirtResolution &Res = ResI->second;
1991 
1992   if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) {
1993     assert(!Res.SingleImplName.empty());
1994     // The type of the function in the declaration is irrelevant because every
1995     // call site will cast it to the correct type.
1996     Constant *SingleImpl =
1997         cast<Constant>(M.getOrInsertFunction(Res.SingleImplName,
1998                                              Type::getVoidTy(M.getContext()))
1999                            .getCallee());
2000 
2001     // This is the import phase so we should not be exporting anything.
2002     bool IsExported = false;
2003     applySingleImplDevirt(SlotInfo, SingleImpl, IsExported);
2004     assert(!IsExported);
2005   }
2006 
2007   for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
2008     auto I = Res.ResByArg.find(CSByConstantArg.first);
2009     if (I == Res.ResByArg.end())
2010       continue;
2011     auto &ResByArg = I->second;
2012     // FIXME: We should figure out what to do about the "function name" argument
2013     // to the apply* functions, as the function names are unavailable during the
2014     // importing phase. For now we just pass the empty string. This does not
2015     // impact correctness because the function names are just used for remarks.
2016     switch (ResByArg.TheKind) {
2017     case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2018       applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
2019       break;
2020     case WholeProgramDevirtResolution::ByArg::UniqueRetVal: {
2021       Constant *UniqueMemberAddr =
2022           importGlobal(Slot, CSByConstantArg.first, "unique_member");
2023       applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
2024                            UniqueMemberAddr);
2025       break;
2026     }
2027     case WholeProgramDevirtResolution::ByArg::VirtualConstProp: {
2028       Constant *Byte = importConstant(Slot, CSByConstantArg.first, "byte",
2029                                       Int32Ty, ResByArg.Byte);
2030       Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
2031                                      ResByArg.Bit);
2032       applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
2033       break;
2034     }
2035     default:
2036       break;
2037     }
2038   }
2039 
2040   if (Res.TheKind == WholeProgramDevirtResolution::BranchFunnel) {
2041     // The type of the function is irrelevant, because it's bitcast at calls
2042     // anyhow.
2043     Constant *JT = cast<Constant>(
2044         M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
2045                               Type::getVoidTy(M.getContext()))
2046             .getCallee());
2047     bool IsExported = false;
2048     applyICallBranchFunnel(SlotInfo, JT, IsExported);
2049     assert(!IsExported);
2050   }
2051 }
2052 
2053 void DevirtModule::removeRedundantTypeTests() {
2054   auto True = ConstantInt::getTrue(M.getContext());
2055   for (auto &&U : NumUnsafeUsesForTypeTest) {
2056     if (U.second == 0) {
2057       U.first->replaceAllUsesWith(True);
2058       U.first->eraseFromParent();
2059     }
2060   }
2061 }
2062 
2063 ValueInfo
2064 DevirtModule::lookUpFunctionValueInfo(Function *TheFn,
2065                                       ModuleSummaryIndex *ExportSummary) {
2066   assert((ExportSummary != nullptr) &&
2067          "Caller guarantees ExportSummary is not nullptr");
2068 
2069   const auto TheFnGUID = TheFn->getGUID();
2070   const auto TheFnGUIDWithExportedName = GlobalValue::getGUID(TheFn->getName());
2071   // Look up ValueInfo with the GUID in the current linkage.
2072   ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFnGUID);
2073   // If no entry is found and GUID is different from GUID computed using
2074   // exported name, look up ValueInfo with the exported name unconditionally.
2075   // This is a fallback.
2076   //
2077   // The reason to have a fallback:
2078   // 1. LTO could enable global value internalization via
2079   // `enable-lto-internalization`.
2080   // 2. The GUID in ExportedSummary is computed using exported name.
2081   if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) {
2082     TheFnVI = ExportSummary->getValueInfo(TheFnGUIDWithExportedName);
2083   }
2084   return TheFnVI;
2085 }
2086 
2087 bool DevirtModule::run() {
2088   // If only some of the modules were split, we cannot correctly perform
2089   // this transformation. We already checked for the presense of type tests
2090   // with partially split modules during the thin link, and would have emitted
2091   // an error if any were found, so here we can simply return.
2092   if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
2093       (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
2094     return false;
2095 
2096   Function *TypeTestFunc =
2097       M.getFunction(Intrinsic::getName(Intrinsic::type_test));
2098   Function *TypeCheckedLoadFunc =
2099       M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
2100   Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume));
2101 
2102   // Normally if there are no users of the devirtualization intrinsics in the
2103   // module, this pass has nothing to do. But if we are exporting, we also need
2104   // to handle any users that appear only in the function summaries.
2105   if (!ExportSummary &&
2106       (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc ||
2107        AssumeFunc->use_empty()) &&
2108       (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
2109     return false;
2110 
2111   // Rebuild type metadata into a map for easy lookup.
2112   std::vector<VTableBits> Bits;
2113   DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
2114   buildTypeIdentifierMap(Bits, TypeIdMap);
2115 
2116   if (TypeTestFunc && AssumeFunc)
2117     scanTypeTestUsers(TypeTestFunc, TypeIdMap);
2118 
2119   if (TypeCheckedLoadFunc)
2120     scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
2121 
2122   if (ImportSummary) {
2123     for (auto &S : CallSlots)
2124       importResolution(S.first, S.second);
2125 
2126     removeRedundantTypeTests();
2127 
2128     // We have lowered or deleted the type instrinsics, so we will no
2129     // longer have enough information to reason about the liveness of virtual
2130     // function pointers in GlobalDCE.
2131     for (GlobalVariable &GV : M.globals())
2132       GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2133 
2134     // The rest of the code is only necessary when exporting or during regular
2135     // LTO, so we are done.
2136     return true;
2137   }
2138 
2139   if (TypeIdMap.empty())
2140     return true;
2141 
2142   // Collect information from summary about which calls to try to devirtualize.
2143   if (ExportSummary) {
2144     DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2145     for (auto &P : TypeIdMap) {
2146       if (auto *TypeId = dyn_cast<MDString>(P.first))
2147         MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back(
2148             TypeId);
2149     }
2150 
2151     for (auto &P : *ExportSummary) {
2152       for (auto &S : P.second.SummaryList) {
2153         auto *FS = dyn_cast<FunctionSummary>(S.get());
2154         if (!FS)
2155           continue;
2156         // FIXME: Only add live functions.
2157         for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2158           for (Metadata *MD : MetadataByGUID[VF.GUID]) {
2159             CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2160           }
2161         }
2162         for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2163           for (Metadata *MD : MetadataByGUID[VF.GUID]) {
2164             CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2165           }
2166         }
2167         for (const FunctionSummary::ConstVCall &VC :
2168              FS->type_test_assume_const_vcalls()) {
2169           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2170             CallSlots[{MD, VC.VFunc.Offset}]
2171                 .ConstCSInfo[VC.Args]
2172                 .addSummaryTypeTestAssumeUser(FS);
2173           }
2174         }
2175         for (const FunctionSummary::ConstVCall &VC :
2176              FS->type_checked_load_const_vcalls()) {
2177           for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2178             CallSlots[{MD, VC.VFunc.Offset}]
2179                 .ConstCSInfo[VC.Args]
2180                 .addSummaryTypeCheckedLoadUser(FS);
2181           }
2182         }
2183       }
2184     }
2185   }
2186 
2187   // For each (type, offset) pair:
2188   bool DidVirtualConstProp = false;
2189   std::map<std::string, Function*> DevirtTargets;
2190   for (auto &S : CallSlots) {
2191     // Search each of the members of the type identifier for the virtual
2192     // function implementation at offset S.first.ByteOffset, and add to
2193     // TargetsForSlot.
2194     std::vector<VirtualCallTarget> TargetsForSlot;
2195     WholeProgramDevirtResolution *Res = nullptr;
2196     const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID];
2197     if (ExportSummary && isa<MDString>(S.first.TypeID) &&
2198         TypeMemberInfos.size())
2199       // For any type id used on a global's type metadata, create the type id
2200       // summary resolution regardless of whether we can devirtualize, so that
2201       // lower type tests knows the type id is not Unsat. If it was not used on
2202       // a global's type metadata, the TypeIdMap entry set will be empty, and
2203       // we don't want to create an entry (with the default Unknown type
2204       // resolution), which can prevent detection of the Unsat.
2205       Res = &ExportSummary
2206                  ->getOrInsertTypeIdSummary(
2207                      cast<MDString>(S.first.TypeID)->getString())
2208                  .WPDRes[S.first.ByteOffset];
2209     if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
2210                                   S.first.ByteOffset, ExportSummary)) {
2211 
2212       if (!trySingleImplDevirt(ExportSummary, TargetsForSlot, S.second, Res)) {
2213         DidVirtualConstProp |=
2214             tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
2215 
2216         tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
2217       }
2218 
2219       // Collect functions devirtualized at least for one call site for stats.
2220       if (RemarksEnabled)
2221         for (const auto &T : TargetsForSlot)
2222           if (T.WasDevirt)
2223             DevirtTargets[std::string(T.Fn->getName())] = T.Fn;
2224     }
2225 
2226     // CFI-specific: if we are exporting and any llvm.type.checked.load
2227     // intrinsics were *not* devirtualized, we need to add the resulting
2228     // llvm.type.test intrinsics to the function summaries so that the
2229     // LowerTypeTests pass will export them.
2230     if (ExportSummary && isa<MDString>(S.first.TypeID)) {
2231       auto GUID =
2232           GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString());
2233       for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers)
2234         FS->addTypeTest(GUID);
2235       for (auto &CCS : S.second.ConstCSInfo)
2236         for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers)
2237           FS->addTypeTest(GUID);
2238     }
2239   }
2240 
2241   if (RemarksEnabled) {
2242     // Generate remarks for each devirtualized function.
2243     for (const auto &DT : DevirtTargets) {
2244       Function *F = DT.second;
2245 
2246       using namespace ore;
2247       OREGetter(F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
2248                         << "devirtualized "
2249                         << NV("FunctionName", DT.first));
2250     }
2251   }
2252 
2253   removeRedundantTypeTests();
2254 
2255   // Rebuild each global we touched as part of virtual constant propagation to
2256   // include the before and after bytes.
2257   if (DidVirtualConstProp)
2258     for (VTableBits &B : Bits)
2259       rebuildGlobal(B);
2260 
2261   // We have lowered or deleted the type instrinsics, so we will no
2262   // longer have enough information to reason about the liveness of virtual
2263   // function pointers in GlobalDCE.
2264   for (GlobalVariable &GV : M.globals())
2265     GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2266 
2267   return true;
2268 }
2269 
2270 void DevirtIndex::run() {
2271   if (ExportSummary.typeIdCompatibleVtableMap().empty())
2272     return;
2273 
2274   DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
2275   for (auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
2276     NameByGUID[GlobalValue::getGUID(P.first)].push_back(P.first);
2277   }
2278 
2279   // Collect information from summary about which calls to try to devirtualize.
2280   for (auto &P : ExportSummary) {
2281     for (auto &S : P.second.SummaryList) {
2282       auto *FS = dyn_cast<FunctionSummary>(S.get());
2283       if (!FS)
2284         continue;
2285       // FIXME: Only add live functions.
2286       for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2287         for (StringRef Name : NameByGUID[VF.GUID]) {
2288           CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2289         }
2290       }
2291       for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2292         for (StringRef Name : NameByGUID[VF.GUID]) {
2293           CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2294         }
2295       }
2296       for (const FunctionSummary::ConstVCall &VC :
2297            FS->type_test_assume_const_vcalls()) {
2298         for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2299           CallSlots[{Name, VC.VFunc.Offset}]
2300               .ConstCSInfo[VC.Args]
2301               .addSummaryTypeTestAssumeUser(FS);
2302         }
2303       }
2304       for (const FunctionSummary::ConstVCall &VC :
2305            FS->type_checked_load_const_vcalls()) {
2306         for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2307           CallSlots[{Name, VC.VFunc.Offset}]
2308               .ConstCSInfo[VC.Args]
2309               .addSummaryTypeCheckedLoadUser(FS);
2310         }
2311       }
2312     }
2313   }
2314 
2315   std::set<ValueInfo> DevirtTargets;
2316   // For each (type, offset) pair:
2317   for (auto &S : CallSlots) {
2318     // Search each of the members of the type identifier for the virtual
2319     // function implementation at offset S.first.ByteOffset, and add to
2320     // TargetsForSlot.
2321     std::vector<ValueInfo> TargetsForSlot;
2322     auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2323     assert(TidSummary);
2324     // Create the type id summary resolution regardlness of whether we can
2325     // devirtualize, so that lower type tests knows the type id is used on
2326     // a global and not Unsat.
2327     WholeProgramDevirtResolution *Res =
2328         &ExportSummary.getOrInsertTypeIdSummary(S.first.TypeID)
2329              .WPDRes[S.first.ByteOffset];
2330     if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2331                                   S.first.ByteOffset)) {
2332 
2333       if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2334                                DevirtTargets))
2335         continue;
2336     }
2337   }
2338 
2339   // Optionally have the thin link print message for each devirtualized
2340   // function.
2341   if (PrintSummaryDevirt)
2342     for (const auto &DT : DevirtTargets)
2343       errs() << "Devirtualized call to " << DT << "\n";
2344 }
2345