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