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