LLVM 24.0.0git
WholeProgramDevirt.cpp
Go to the documentation of this file.
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/thin and non-LTO
28// pipelines:
29//
30// During regular LTO, the pass determines the best optimization for each
31// virtual call and applies the resolutions directly to virtual calls that are
32// eligible for virtual call optimization (i.e. calls that use either of the
33// llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics).
34//
35// During hybrid Regular/ThinLTO, the pass operates in two phases:
36// - Export phase: this is run during the thin link over a single merged module
37// that contains all vtables with !type metadata that participate in the link.
38// The pass computes a resolution for each virtual call and stores it in the
39// type identifier summary.
40// - Import phase: this is run during the thin backends over the individual
41// modules. The pass applies the resolutions previously computed during the
42// import phase to each eligible virtual call.
43//
44// During ThinLTO, the pass operates in two phases:
45// - Export phase: this is run during the thin link over the index which
46// contains a summary of all vtables with !type metadata that participate in
47// the link. It computes a resolution for each virtual call and stores it in
48// the type identifier summary. Only single implementation devirtualization
49// is supported.
50// - Import phase: (same as with hybrid case above).
51//
52// During Speculative devirtualization mode -not restricted to LTO-:
53// - The pass applies speculative devirtualization without requiring any type of
54// visibility.
55// - Skips other features like virtual constant propagation, uniform return
56// value optimization, unique return value optimization and branch funnels as
57// they need LTO.
58// - This mode is enabled via 'devirtualize-speculatively' flag.
59//
60//===----------------------------------------------------------------------===//
61
63#include "IPOOptions.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/MapVector.h"
69#include "llvm/ADT/STLExtras.h"
72#include "llvm/ADT/Statistic.h"
82#include "llvm/IR/Constants.h"
83#include "llvm/IR/DataLayout.h"
84#include "llvm/IR/DebugLoc.h"
87#include "llvm/IR/Dominators.h"
88#include "llvm/IR/Function.h"
89#include "llvm/IR/GlobalAlias.h"
91#include "llvm/IR/IRBuilder.h"
92#include "llvm/IR/InstrTypes.h"
93#include "llvm/IR/Instruction.h"
95#include "llvm/IR/Intrinsics.h"
96#include "llvm/IR/LLVMContext.h"
97#include "llvm/IR/MDBuilder.h"
98#include "llvm/IR/Metadata.h"
99#include "llvm/IR/Module.h"
101#include "llvm/IR/PassManager.h"
104#include "llvm/Support/Casting.h"
106#include "llvm/Support/Errc.h"
107#include "llvm/Support/Error.h"
112#include "llvm/Transforms/IPO.h"
117#include <algorithm>
118#include <cmath>
119#include <cstddef>
120#include <limits>
121#include <map>
122#include <set>
123#include <string>
124
125using namespace llvm;
126using namespace wholeprogramdevirt;
127
128#define DEBUG_TYPE "wholeprogramdevirt"
129
130STATISTIC(NumDevirtTargets, "Number of whole program devirtualization targets");
131STATISTIC(NumSingleImpl, "Number of single implementation devirtualizations");
132STATISTIC(NumBranchFunnel, "Number of branch funnels");
133STATISTIC(NumUniformRetVal, "Number of uniform return value optimizations");
134STATISTIC(NumUniqueRetVal, "Number of unique return value optimizations");
135STATISTIC(NumVirtConstProp1Bit,
136 "Number of 1 bit virtual constant propagations");
137STATISTIC(NumVirtConstProp, "Number of virtual constant propagations");
138DEBUG_COUNTER(CallsToDevirt, "calls-to-devirt",
139 "Controls how many calls should be devirtualized.");
140
141namespace {
142struct PatternList {
143 std::vector<GlobPattern> Patterns;
144 template <class T> void init(const T &StringList) {
145 for (const auto &S : StringList)
147 Patterns.push_back(std::move(*Pat));
148 }
149 bool match(StringRef S) {
150 for (const GlobPattern &P : Patterns)
151 if (P.match(S))
152 return true;
153 return false;
154 }
155};
156} // namespace
157
158// Find the minimum offset that we may store a value of size Size bits at. If
159// IsAfter is set, look for an offset before the object, otherwise look for an
160// offset after the object.
163 bool IsAfter, uint64_t Size) {
164 // Find a minimum offset taking into account only vtable sizes.
165 uint64_t MinByte = 0;
166 for (const VirtualCallTarget &Target : Targets) {
167 if (IsAfter)
168 MinByte = std::max(MinByte, Target.minAfterBytes());
169 else
170 MinByte = std::max(MinByte, Target.minBeforeBytes());
171 }
172
173 // Build a vector of arrays of bytes covering, for each target, a slice of the
174 // used region (see AccumBitVector::BytesUsed in
175 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively,
176 // this aligns the used regions to start at MinByte.
177 //
178 // In this example, A, B and C are vtables, # is a byte already allocated for
179 // a virtual function pointer, AAAA... (etc.) are the used regions for the
180 // vtables and Offset(X) is the value computed for the Offset variable below
181 // for X.
182 //
183 // Offset(A)
184 // | |
185 // |MinByte
186 // A: ################AAAAAAAA|AAAAAAAA
187 // B: ########BBBBBBBBBBBBBBBB|BBBB
188 // C: ########################|CCCCCCCCCCCCCCCC
189 // | Offset(B) |
190 //
191 // This code produces the slices of A, B and C that appear after the divider
192 // at MinByte.
193 std::vector<ArrayRef<uint8_t>> Used;
194 for (const VirtualCallTarget &Target : Targets) {
195 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed
196 : Target.TM->Bits->Before.BytesUsed;
197 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes()
198 : MinByte - Target.minBeforeBytes();
199
200 // Disregard used regions that are smaller than Offset. These are
201 // effectively all-free regions that do not need to be checked.
202 if (VTUsed.size() > Offset)
203 Used.push_back(VTUsed.slice(Offset));
204 }
205
206 if (Size == 1) {
207 // Find a free bit in each member of Used.
208 for (unsigned I = 0;; ++I) {
209 uint8_t BitsUsed = 0;
210 for (auto &&B : Used)
211 if (I < B.size())
212 BitsUsed |= B[I];
213 if (BitsUsed != 0xff)
214 return (MinByte + I) * 8 + llvm::countr_zero(uint8_t(~BitsUsed));
215 }
216 } else {
217 // Find a free (Size/8) byte region in each member of Used.
218 // FIXME: see if alignment helps.
219 for (unsigned I = 0;; ++I) {
220 for (auto &&B : Used) {
221 unsigned Byte = 0;
222 while ((I + Byte) < B.size() && Byte < (Size / 8)) {
223 if (B[I + Byte])
224 goto NextI;
225 ++Byte;
226 }
227 }
228 // Rounding up ensures the constant is always stored at address we
229 // can directly load from without misalignment.
230 return alignTo((MinByte + I) * 8, Size);
231 NextI:;
232 }
233 }
234}
235
237 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore,
238 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
239 if (BitWidth == 1)
240 OffsetByte = -(AllocBefore / 8 + 1);
241 else
242 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8);
243 OffsetBit = AllocBefore % 8;
244
245 for (VirtualCallTarget &Target : Targets) {
246 if (BitWidth == 1)
247 Target.setBeforeBit(AllocBefore);
248 else
249 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8);
250 }
251}
252
254 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter,
255 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) {
256 if (BitWidth == 1)
257 OffsetByte = AllocAfter / 8;
258 else
259 OffsetByte = (AllocAfter + 7) / 8;
260 OffsetBit = AllocAfter % 8;
261
262 for (VirtualCallTarget &Target : Targets) {
263 if (BitWidth == 1)
264 Target.setAfterBit(AllocAfter);
265 else
266 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8);
267 }
268}
269
274
275namespace {
276
277// A slot in a set of virtual tables. The TypeID identifies the set of virtual
278// tables, and the ByteOffset is the offset in bytes from the address point to
279// the virtual function pointer.
280struct VTableSlot {
281 Metadata *TypeID;
282 uint64_t ByteOffset;
283};
284
285} // end anonymous namespace
286
287template <> struct llvm::DenseMapInfo<VTableSlot> {
288 static unsigned getHashValue(const VTableSlot &I) {
291 }
292 static bool isEqual(const VTableSlot &LHS,
293 const VTableSlot &RHS) {
294 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
295 }
296};
297
299 static unsigned getHashValue(const VTableSlotSummary &I) {
302 }
303 static bool isEqual(const VTableSlotSummary &LHS,
304 const VTableSlotSummary &RHS) {
305 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset;
306 }
307};
308
309// Returns true if the function must be unreachable based on ValueInfo.
310//
311// In particular, identifies a function as unreachable in the following
312// conditions
313// 1) All summaries are live.
314// 2) All function summaries indicate it's unreachable
315// 3) There is no non-function with the same GUID (which is rare)
317 if ((!TheFnVI) || TheFnVI.getSummaryList().empty()) {
318 // Returns false if ValueInfo is absent, or the summary list is empty
319 // (e.g., function declarations).
320 return false;
321 }
322
323 for (const auto &Summary : TheFnVI.getSummaryList()) {
324 // Conservatively returns false if any non-live functions are seen.
325 // In general either all summaries should be live or all should be dead.
326 if (!Summary->isLive())
327 return false;
328 if (auto *FS = dyn_cast<FunctionSummary>(Summary->getBaseObject())) {
329 if (!FS->fflags().MustBeUnreachable)
330 return false;
331 }
332 // Be conservative if a non-function has the same GUID (which is rare).
333 else
334 return false;
335 }
336 // All function summaries are live and all of them agree that the function is
337 // unreachble.
338 return true;
339}
340
341namespace {
342// A virtual call site. VTable is the loaded virtual table pointer, and CS is
343// the indirect virtual call.
344struct VirtualCallSite {
345 Value *VTable = nullptr;
346 CallBase &CB;
347
348 // If non-null, this field points to the associated unsafe use count stored in
349 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description
350 // of that field for details.
351 unsigned *NumUnsafeUses = nullptr;
352
353 void
354 emitRemark(const StringRef OptName, const StringRef TargetName,
355 function_ref<OptimizationRemarkEmitter &(Function &)> OREGetter) {
356 Function *F = CB.getCaller();
357 DebugLoc DLoc = CB.getDebugLoc();
358 BasicBlock *Block = CB.getParent();
359
360 using namespace ore;
361 OREGetter(*F).emit(OptimizationRemark(DEBUG_TYPE, OptName, DLoc, Block)
362 << NV("Optimization", OptName)
363 << ": devirtualized a call to "
364 << NV("FunctionName", TargetName));
365 }
366
367 void replaceAndErase(
368 const StringRef OptName, const StringRef TargetName, bool RemarksEnabled,
369 function_ref<OptimizationRemarkEmitter &(Function &)> OREGetter,
370 Value *New) {
371 if (RemarksEnabled)
372 emitRemark(OptName, TargetName, OREGetter);
373 CB.replaceAllUsesWith(New);
374 if (auto *II = dyn_cast<InvokeInst>(&CB)) {
375 UncondBrInst::Create(II->getNormalDest(), CB.getIterator());
376 II->getUnwindDest()->removePredecessor(II->getParent());
377 }
378 CB.eraseFromParent();
379 // This use is no longer unsafe.
380 if (NumUnsafeUses)
381 --*NumUnsafeUses;
382 }
383};
384
385// Call site information collected for a specific VTableSlot and possibly a list
386// of constant integer arguments. The grouping by arguments is handled by the
387// VTableSlotInfo class.
388struct CallSiteInfo {
389 /// The set of call sites for this slot. Used during regular LTO and the
390 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any
391 /// call sites that appear in the merged module itself); in each of these
392 /// cases we are directly operating on the call sites at the IR level.
393 std::vector<VirtualCallSite> CallSites;
394
395 /// Whether all call sites represented by this CallSiteInfo, including those
396 /// in summaries, have been devirtualized. This starts off as true because a
397 /// default constructed CallSiteInfo represents no call sites.
398 ///
399 /// If at the end of the pass there are still undevirtualized calls, we will
400 /// need to add a use of llvm.type.test to each of the function summaries in
401 /// the vector.
402 bool AllCallSitesDevirted = true;
403
404 // These fields are used during the export phase of ThinLTO and reflect
405 // information collected from function summaries.
406
407 /// CFI-specific: a vector containing the list of function summaries that use
408 /// the llvm.type.checked.load intrinsic and therefore will require
409 /// resolutions for llvm.type.test in order to implement CFI checks if
410 /// devirtualization was unsuccessful.
411 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers;
412
413 /// A vector containing the list of function summaries that use
414 /// assume(llvm.type.test).
415 std::vector<FunctionSummary *> SummaryTypeTestAssumeUsers;
416
417 bool isExported() const {
418 return !SummaryTypeCheckedLoadUsers.empty() ||
419 !SummaryTypeTestAssumeUsers.empty();
420 }
421
422 void addSummaryTypeCheckedLoadUser(FunctionSummary *FS) {
423 SummaryTypeCheckedLoadUsers.push_back(FS);
424 AllCallSitesDevirted = false;
425 }
426
427 void addSummaryTypeTestAssumeUser(FunctionSummary *FS) {
428 SummaryTypeTestAssumeUsers.push_back(FS);
429 AllCallSitesDevirted = false;
430 }
431
432 void markDevirt() { AllCallSitesDevirted = true; }
433};
434
435// Call site information collected for a specific VTableSlot.
436struct VTableSlotInfo {
437 // The set of call sites which do not have all constant integer arguments
438 // (excluding "this").
439 CallSiteInfo CSInfo;
440
441 // The set of call sites with all constant integer arguments (excluding
442 // "this"), grouped by argument list.
443 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo;
444
445 void addCallSite(Value *VTable, CallBase &CB, unsigned *NumUnsafeUses);
446
447private:
448 CallSiteInfo &findCallSiteInfo(CallBase &CB);
449};
450
451CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallBase &CB) {
452 std::vector<uint64_t> Args;
453 auto *CBType = dyn_cast<IntegerType>(CB.getType());
454 if (!CBType || CBType->getBitWidth() > 64 || CB.arg_empty())
455 return CSInfo;
456 for (auto &&Arg : drop_begin(CB.args())) {
457 auto *CI = dyn_cast<ConstantInt>(Arg);
458 if (!CI || CI->getBitWidth() > 64)
459 return CSInfo;
460 Args.push_back(CI->getZExtValue());
461 }
462 return ConstCSInfo[Args];
463}
464
465void VTableSlotInfo::addCallSite(Value *VTable, CallBase &CB,
466 unsigned *NumUnsafeUses) {
467 auto &CSI = findCallSiteInfo(CB);
468 CSI.AllCallSitesDevirted = false;
469 CSI.CallSites.push_back({VTable, CB, NumUnsafeUses});
470}
471
472struct DevirtModule {
473 const IPOOptions &Opts;
474 Module &M;
477
478 ModuleSummaryIndex *const ExportSummary;
479 const ModuleSummaryIndex *const ImportSummary;
480
481 IntegerType *const Int8Ty;
482 PointerType *const Int8PtrTy;
483 IntegerType *const Int32Ty;
484 IntegerType *const Int64Ty;
485 IntegerType *const IntPtrTy;
486 /// Sizeless array type, used for imported vtables. This provides a signal
487 /// to analyzers that these imports may alias, as they do for example
488 /// when multiple unique return values occur in the same vtable.
489 ArrayType *const Int8Arr0Ty;
490
491 const bool RemarksEnabled;
492 std::function<OptimizationRemarkEmitter &(Function &)> OREGetter;
493 MapVector<VTableSlot, VTableSlotInfo> CallSlots;
494
495 // Calls that have already been optimized. We may add a call to multiple
496 // VTableSlotInfos if vtable loads are coalesced and need to make sure not to
497 // optimize a call more than once.
498 SmallPtrSet<CallBase *, 8> OptimizedCalls;
499
500 // Store calls that had their ptrauth bundle removed. They are to be deleted
501 // at the end of the optimization.
502 SmallVector<CallBase *, 8> CallsWithPtrAuthBundleRemoved;
503
504 // This map keeps track of the number of "unsafe" uses of a loaded function
505 // pointer. The key is the associated llvm.type.test intrinsic call generated
506 // by this pass. An unsafe use is one that calls the loaded function pointer
507 // directly. Every time we eliminate an unsafe use (for example, by
508 // devirtualizing it or by applying virtual constant propagation), we
509 // decrement the value stored in this map. If a value reaches zero, we can
510 // eliminate the type check by RAUWing the associated llvm.type.test call with
511 // true.
512 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest;
513 PatternList FunctionsToSkip;
514
515 const bool DevirtSpeculatively;
516 DevirtModule(Module &M, ModuleAnalysisManager &MAM,
517 ModuleSummaryIndex *ExportSummary,
518 const ModuleSummaryIndex *ImportSummary,
519 bool DevirtSpeculatively)
520 : Opts(getIPOOptions(M)), M(M), MAM(MAM),
521 FAM(MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager()),
522 ExportSummary(ExportSummary), ImportSummary(ImportSummary),
523 Int8Ty(Type::getInt8Ty(M.getContext())),
524 Int8PtrTy(PointerType::getUnqual(M.getContext())),
525 Int32Ty(Type::getInt32Ty(M.getContext())),
526 Int64Ty(Type::getInt64Ty(M.getContext())),
527 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)),
528 Int8Arr0Ty(ArrayType::get(Type::getInt8Ty(M.getContext()), 0)),
529 RemarksEnabled(areRemarksEnabled()),
530 OREGetter([&](Function &F) -> OptimizationRemarkEmitter & {
531 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
532 }),
533 DevirtSpeculatively(
534 DevirtSpeculatively ||
535 (ImportSummary && ImportSummary->withSpeculativeDevirt())) {
536 assert(!(ExportSummary && ImportSummary));
537 FunctionsToSkip.init(Opts.wholeprogramdevirt_skip);
538 }
539
540 bool areRemarksEnabled();
541
542 void
543 scanTypeTestUsers(Function *TypeTestFunc,
544 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
545 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc);
546
547 void buildTypeIdentifierMap(
548 std::vector<VTableBits> &Bits,
549 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap);
550
551 bool tryFindVirtualCallTargets(
552 std::vector<VirtualCallTarget> &TargetsForSlot,
553 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset,
554 ModuleSummaryIndex *ExportSummary, bool &HasPublicTarget);
555
556 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn,
557 bool HasPublicTarget, bool &IsExported);
558 bool trySingleImplDevirt(ModuleSummaryIndex *ExportSummary,
560 VTableSlotInfo &SlotInfo,
561 WholeProgramDevirtResolution *Res,
562 bool HasPublicTarget);
563
564 void applyICallBranchFunnel(VTableSlotInfo &SlotInfo, Function &JT,
565 bool &IsExported);
566 void tryICallBranchFunnel(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
567 VTableSlotInfo &SlotInfo,
568 WholeProgramDevirtResolution *Res, VTableSlot Slot);
569
570 bool tryEvaluateFunctionsWithArgs(
572 ArrayRef<uint64_t> Args);
573
574 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
575 uint64_t TheRetVal);
576 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
577 CallSiteInfo &CSInfo,
578 WholeProgramDevirtResolution::ByArg *Res);
579
580 // Returns the global symbol name that is used to export information about the
581 // given vtable slot and list of arguments.
582 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args,
583 StringRef Name);
584
585 bool shouldExportConstantsAsAbsoluteSymbols();
586
587 // This function is called during the export phase to create a symbol
588 // definition containing information about the given vtable slot and list of
589 // arguments.
590 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
591 Constant *C);
592 void exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name,
593 uint32_t Const, uint32_t &Storage);
594
595 // This function is called during the import phase to create a reference to
596 // the symbol definition created during the export phase.
597 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
598 StringRef Name);
599 Constant *importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
600 StringRef Name, IntegerType *IntTy,
601 uint32_t Storage);
602
603 Constant *getMemberAddr(const TypeMemberInfo *M);
604
605 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne,
606 Constant *UniqueMemberAddr);
607 bool tryUniqueRetValOpt(unsigned BitWidth,
609 CallSiteInfo &CSInfo,
610 WholeProgramDevirtResolution::ByArg *Res,
611 VTableSlot Slot, ArrayRef<uint64_t> Args);
612
613 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
614 Constant *Byte, Constant *Bit);
615 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot,
616 VTableSlotInfo &SlotInfo,
617 WholeProgramDevirtResolution *Res, VTableSlot Slot);
618
619 void rebuildGlobal(VTableBits &B);
620
621 // Apply the summary resolution for Slot to all virtual calls in SlotInfo.
622 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo);
623
624 // If we were able to eliminate all unsafe uses for a type checked load,
625 // eliminate the associated type tests by replacing them with true.
626 void removeRedundantTypeTests();
627
628 bool run();
629
630 // Look up the corresponding ValueInfo entry of `TheFn` in `ExportSummary`.
631 //
632 // Caller guarantees that `ExportSummary` is not nullptr.
633 static ValueInfo lookUpFunctionValueInfo(Function *TheFn,
634 ModuleSummaryIndex *ExportSummary);
635
636 // Returns true if the function definition must be unreachable.
637 //
638 // Note if this helper function returns true, `F` is guaranteed
639 // to be unreachable; if it returns false, `F` might still
640 // be unreachable but not covered by this helper function.
641 //
642 // Implementation-wise, if function definition is present, IR is analyzed; if
643 // not, look up function flags from ExportSummary as a fallback.
644 static bool mustBeUnreachableFunction(Function *const F,
645 ModuleSummaryIndex *ExportSummary);
646
647 // Lower the module using the action and summary passed as command line
648 // arguments. For testing purposes only.
649 static bool runForTesting(Module &M, ModuleAnalysisManager &MAM,
650 bool DevirtSpeculatively);
651};
652
653struct DevirtIndex {
654 const IPOOptions &Opts;
655 ModuleSummaryIndex &ExportSummary;
656 // The set in which to record GUIDs exported from their module by
657 // devirtualization, used by client to ensure they are not internalized.
658 std::set<GlobalValue::GUID> &ExportedGUIDs;
659 // A map in which to record the information necessary to locate the WPD
660 // resolution for local targets in case they are exported by cross module
661 // importing.
662 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap;
663 // We have hardcoded the promoted and renamed function name in the WPD
664 // summary, so we need to ensure that they will be renamed. Note this and
665 // that adding the current names to this set ensures we continue to rename
666 // them.
667 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr;
668
669 MapVector<VTableSlotSummary, VTableSlotInfo> CallSlots;
670
671 PatternList FunctionsToSkip;
672
673 // Whether speculative devirtualization is enabled, as recorded in the
674 // combined index by runWholeProgramDevirtOnIndex.
675 const bool DevirtSpeculatively;
676
677 DevirtIndex(
678 const IPOOptions &Opts, ModuleSummaryIndex &ExportSummary,
679 std::set<GlobalValue::GUID> &ExportedGUIDs,
680 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
681 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr)
682 : Opts(Opts), ExportSummary(ExportSummary), ExportedGUIDs(ExportedGUIDs),
683 LocalWPDTargetsMap(LocalWPDTargetsMap),
684 ExternallyVisibleSymbolNamesPtr(ExternallyVisibleSymbolNamesPtr),
685 DevirtSpeculatively(ExportSummary.withSpeculativeDevirt()) {
686 FunctionsToSkip.init(Opts.wholeprogramdevirt_skip);
687 }
688
689 bool tryFindVirtualCallTargets(std::vector<ValueInfo> &TargetsForSlot,
690 const TypeIdCompatibleVtableInfo TIdInfo,
691 uint64_t ByteOffset, bool &HasPublicTarget);
692
693 bool trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
694 VTableSlotSummary &SlotSummary,
695 VTableSlotInfo &SlotInfo,
696 WholeProgramDevirtResolution *Res,
697 std::set<ValueInfo> &DevirtTargets,
698 bool HasPublicTarget);
699
700 void run();
701};
702} // end anonymous namespace
703
706 const bool DevirtualizeSpeculatively =
707 DevirtSpeculatively || getIPOOptions(M).devirtualize_speculatively;
708
709 // Preserving the proxy invalidates each function individually, which keeps
710 // analyses like TargetLibraryInfo.
711 PreservedAnalyses ChangedPA;
713
714 if (UseCommandLine) {
715 if (!DevirtModule::runForTesting(M, MAM, DevirtualizeSpeculatively))
716 return PreservedAnalyses::all();
717 return ChangedPA;
718 }
719
720 // FIXME: The state of a run should not be kept in the pass. A more resilient
721 // design would create an object in run() that holds the values the run
722 // needs, such as the module, the analyses and the summaries.
723 std::optional<ModuleSummaryIndex> Index;
725 if (!ExportSummary && !ImportSummary && DevirtualizeSpeculatively) {
726 // Build the ExportSummary from the module.
727 ProfileSummaryInfo PSI(M);
728 Index.emplace(buildModuleSummaryIndex(M, nullptr, &PSI));
729 Export = &*Index;
730 }
731 if (!DevirtModule(M, MAM, Export, ImportSummary, DevirtualizeSpeculatively)
732 .run())
733 return PreservedAnalyses::all();
734 return ChangedPA;
735}
736
737// Enable whole program visibility if enabled by client (e.g. linker) or
738// internal option, and not force disabled.
740 const cl::LibraryOptionsContext &LibraryOptions,
741 bool WholeProgramVisibilityEnabledInLTO) {
742 const IPOOptions &Opts = LibraryOptions.get<IPOOptions>();
743 return (WholeProgramVisibilityEnabledInLTO ||
744 Opts.whole_program_visibility) &&
745 !Opts.disable_whole_program_visibility;
746}
747
748static bool
750 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
751 // TypeID for member function pointer type is an internal construct
752 // and won't exist in IsVisibleToRegularObj. The full TypeID
753 // will be present and participate in invalidation.
754 if (TypeID.ends_with(".virtual"))
755 return false;
756
757 // TypeID that doesn't start with Itanium mangling (_ZTS) will be
758 // non-externally visible types which cannot interact with
759 // external native files. See CodeGenModule::CreateMetadataIdentifierImpl.
760 if (!TypeID.consume_front("_ZTS"))
761 return false;
762
763 // TypeID is keyed off the type name symbol (_ZTS). However, the native
764 // object may not contain this symbol if it does not contain a key
765 // function for the base type and thus only contains a reference to the
766 // type info (_ZTI). To catch this case we query using the type info
767 // symbol corresponding to the TypeID.
768 std::string TypeInfo = ("_ZTI" + TypeID).str();
769 return IsVisibleToRegularObj(TypeInfo);
770}
771
772static bool
774 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
776 GV.getMetadata(LLVMContext::MD_type, Types);
777
778 for (auto *Type : Types)
779 if (auto *TypeID = dyn_cast<MDString>(Type->getOperand(1).get()))
780 return typeIDVisibleToRegularObj(TypeID->getString(),
781 IsVisibleToRegularObj);
782
783 return false;
784}
785
786/// If whole program visibility asserted, then upgrade all public vcall
787/// visibility metadata on vtable definitions to linkage unit visibility in
788/// Module IR (for regular or hybrid LTO).
790 Module &M, bool WholeProgramVisibilityEnabledInLTO,
791 const DenseSet<GlobalValue::GUID> &DynamicExportSymbols,
792 bool ValidateAllVtablesHaveTypeInfos,
793 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
794 if (!hasWholeProgramVisibility(M.getContext().getLibraryOptions(),
795 WholeProgramVisibilityEnabledInLTO))
796 return;
797
798 for (GlobalVariable &GV : M.globals()) {
799 // Add linkage unit visibility to any variable with type metadata, which are
800 // the vtable definitions. We won't have an existing vcall_visibility
801 // metadata on vtable definitions with public visibility.
802 if (GV.hasMetadata(LLVMContext::MD_type) &&
804 // Don't upgrade the visibility for symbols exported to the dynamic
805 // linker, as we have no information on their eventual use.
806 !DynamicExportSymbols.count(GV.getGUID()) &&
807 // With validation enabled, we want to exclude symbols visible to
808 // regular objects. Local symbols will be in this group due to the
809 // current implementation but those with VCallVisibilityTranslationUnit
810 // will have already been marked in clang so are unaffected.
811 !(ValidateAllVtablesHaveTypeInfos &&
812 skipUpdateDueToValidation(GV, IsVisibleToRegularObj)))
814 }
815}
816
818 bool WholeProgramVisibilityEnabledInLTO,
819 bool DevirtSpeculativelyInIndex) {
820 llvm::TimeTraceScope timeScope("Update public type test calls");
821 Function *PublicTypeTestFunc =
822 Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test);
823 if (!PublicTypeTestFunc)
824 return;
825 if (hasWholeProgramVisibility(M.getContext().getLibraryOptions(),
826 WholeProgramVisibilityEnabledInLTO)) {
827 Function *TypeTestFunc =
828 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::type_test);
829 for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
830 auto *CI = cast<CallInst>(U.getUser());
831 auto *NewCI = CallInst::Create(
832 TypeTestFunc, {CI->getArgOperand(0), CI->getArgOperand(1)}, {}, "",
833 CI->getIterator());
834 CI->replaceAllUsesWith(NewCI);
835 CI->eraseFromParent();
836 }
837 } else if (!DevirtSpeculativelyInIndex &&
838 !getIPOOptions(M).devirtualize_speculatively) {
839 // Keep the public type tests when speculative devirtualization is enabled,
840 // either via the option or as recorded in the combined index by the thin
841 // link (needed by distributed ThinLTO backends, which don't see the
842 // option), since WPD uses them to find the call sites to devirtualize.
843 auto *True = ConstantInt::getTrue(M.getContext());
844 for (Use &U : make_early_inc_range(PublicTypeTestFunc->uses())) {
845 auto *CI = cast<CallInst>(U.getUser());
846 CI->replaceAllUsesWith(True);
847 CI->eraseFromParent();
848 }
849 }
850}
851
852/// Based on typeID string, get all associated vtable GUIDS that are
853/// visible to regular objects.
855 ModuleSummaryIndex &Index,
856 DenseSet<GlobalValue::GUID> &VisibleToRegularObjSymbols,
857 function_ref<bool(StringRef)> IsVisibleToRegularObj) {
858 for (const auto &TypeID : Index.typeIdCompatibleVtableMap()) {
859 if (typeIDVisibleToRegularObj(TypeID.first, IsVisibleToRegularObj))
860 for (const TypeIdOffsetVtableInfo &P : TypeID.second)
861 VisibleToRegularObjSymbols.insert(P.VTableVI.getGUID());
862 }
863}
864
865/// If whole program visibility asserted, then upgrade all public vcall
866/// visibility metadata on vtable definition summaries to linkage unit
867/// visibility in Module summary index (for ThinLTO).
869 const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index,
870 bool WholeProgramVisibilityEnabledInLTO,
871 const DenseSet<GlobalValue::GUID> &DynamicExportSymbols,
872 const DenseSet<GlobalValue::GUID> &VisibleToRegularObjSymbols) {
873 if (!hasWholeProgramVisibility(LibraryOptions,
874 WholeProgramVisibilityEnabledInLTO))
875 return;
876 for (auto &P : Index) {
877 // Don't upgrade the visibility for symbols exported to the dynamic
878 // linker, as we have no information on their eventual use.
879 if (DynamicExportSymbols.count(P.first))
880 continue;
881 // With validation enabled, we want to exclude symbols visible to regular
882 // objects. Local symbols will be in this group due to the current
883 // implementation but those with VCallVisibilityTranslationUnit will have
884 // already been marked in clang so are unaffected.
885 if (VisibleToRegularObjSymbols.count(P.first))
886 continue;
887 for (auto &S : P.second.getSummaryList()) {
888 auto *GVar = dyn_cast<GlobalVarSummary>(S.get());
889 if (!GVar ||
890 GVar->getVCallVisibility() != GlobalObject::VCallVisibilityPublic)
891 continue;
892 GVar->setVCallVisibility(GlobalObject::VCallVisibilityLinkageUnit);
893 }
894 }
895}
896
898 const cl::LibraryOptionsContext &LibraryOptions,
899 ModuleSummaryIndex &Summary, std::set<GlobalValue::GUID> &ExportedGUIDs,
900 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
901 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
902 const IPOOptions &Opts = LibraryOptions.get<IPOOptions>();
903 // Record in the combined index whether speculative devirtualization is
904 // enabled. This is consulted by the index-based WPD below, and by the
905 // backends (in particular distributed ThinLTO backends, which do not see the
906 // option) so that they apply the speculative resolutions.
907 if (Opts.devirtualize_speculatively)
908 Summary.setWithSpeculativeDevirt();
909 DevirtIndex(Opts, Summary, ExportedGUIDs, LocalWPDTargetsMap,
910 ExternallyVisibleSymbolNamesPtr)
911 .run();
912}
913
915 ModuleSummaryIndex &Summary,
916 function_ref<bool(StringRef, ValueInfo)> IsExported,
917 std::map<ValueInfo, std::vector<VTableSlotSummary>> &LocalWPDTargetsMap,
918 DenseSet<StringRef> *ExternallyVisibleSymbolNamesPtr) {
919 for (auto &T : LocalWPDTargetsMap) {
920 auto &VI = T.first;
921 // This was enforced earlier during trySingleImplDevirt.
922 assert(VI.getSummaryList().size() == 1 &&
923 "Devirt of local target has more than one copy");
924 auto &S = VI.getSummaryList()[0];
925 if (!IsExported(S->modulePath(), VI))
926 continue;
927
928 // It's been exported by a cross module import.
929 for (auto &SlotSummary : T.second) {
930 auto *TIdSum = Summary.getTypeIdSummary(SlotSummary.TypeID);
931 assert(TIdSum);
932 auto WPDRes = TIdSum->WPDRes.find(SlotSummary.ByteOffset);
933 assert(WPDRes != TIdSum->WPDRes.end());
934 if (ExternallyVisibleSymbolNamesPtr)
935 ExternallyVisibleSymbolNamesPtr->insert(WPDRes->second.SingleImplName);
936 WPDRes->second.SingleImplName = ModuleSummaryIndex::getGlobalNameForLocal(
937 WPDRes->second.SingleImplName,
938 Summary.getModuleHash(S->modulePath()));
939 }
940 }
941}
942
943static Error checkCombinedSummaryForTesting(const IPOOptions &Opts,
944 ModuleSummaryIndex *Summary) {
945 // Check that summary index contains regular LTO module when performing
946 // export to prevent occasional use of index from pure ThinLTO compilation
947 // (-fno-split-lto-module). This kind of summary index is passed to
948 // DevirtIndex::run, not to DevirtModule::run used by opt/runForTesting.
949 const auto &ModPaths = Summary->modulePaths();
950 if (Opts.wholeprogramdevirt_summary_action != PassSummaryAction::Import &&
952 return createStringError(
954 "combined summary should contain Regular LTO module");
955 return ErrorSuccess();
956}
957
958bool DevirtModule::runForTesting(Module &M, ModuleAnalysisManager &MAM,
959 bool DevirtSpeculatively) {
960 const IPOOptions &Opts = getIPOOptions(M);
961 StringRef ReadSummary = Opts.wholeprogramdevirt_read_summary;
962 StringRef WriteSummary = Opts.wholeprogramdevirt_write_summary;
963 PassSummaryAction SummaryAction = Opts.wholeprogramdevirt_summary_action;
964 std::unique_ptr<ModuleSummaryIndex> Summary =
965 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
966
967 // Handle the command-line summary arguments. This code is for testing
968 // purposes only, so we handle errors directly.
969 if (!ReadSummary.empty()) {
970 ExitOnError ExitOnErr(
971 ("-wholeprogramdevirt-read-summary: " + ReadSummary + ": ").str());
972 auto ReadSummaryFile =
973 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ReadSummary)));
974 if (Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr =
975 getModuleSummaryIndex(*ReadSummaryFile)) {
976 Summary = std::move(*SummaryOrErr);
977 ExitOnErr(checkCombinedSummaryForTesting(Opts, Summary.get()));
978 } else {
979 // Try YAML if we've failed with bitcode.
980 consumeError(SummaryOrErr.takeError());
981 yaml::Input In(ReadSummaryFile->getBuffer());
982 In >> *Summary;
983 ExitOnErr(errorCodeToError(In.error()));
984 }
985 }
986
987 bool Changed =
988 DevirtModule(
989 M, MAM,
990 SummaryAction == PassSummaryAction::Export ? Summary.get() : nullptr,
991 SummaryAction == PassSummaryAction::Import ? Summary.get() : nullptr,
992 DevirtSpeculatively)
993 .run();
994
995 if (!WriteSummary.empty()) {
996 ExitOnError ExitOnErr(
997 ("-wholeprogramdevirt-write-summary: " + WriteSummary + ": ").str());
998 std::error_code EC;
999 if (WriteSummary.ends_with(".bc")) {
1000 raw_fd_ostream OS(WriteSummary, EC, sys::fs::OF_None);
1001 ExitOnErr(errorCodeToError(EC));
1002 writeIndexToFile(*Summary, OS);
1003 } else {
1004 raw_fd_ostream OS(WriteSummary, EC, sys::fs::OF_TextWithCRLF);
1005 ExitOnErr(errorCodeToError(EC));
1006 yaml::Output Out(OS);
1007 Out << *Summary;
1008 }
1009 }
1010
1011 return Changed;
1012}
1013
1014void DevirtModule::buildTypeIdentifierMap(
1015 std::vector<VTableBits> &Bits,
1016 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
1017 DenseMap<GlobalVariable *, VTableBits *> GVToBits;
1018 Bits.reserve(M.global_size());
1020 for (GlobalVariable &GV : M.globals()) {
1021 Types.clear();
1022 GV.getMetadata(LLVMContext::MD_type, Types);
1023 if (GV.isDeclaration() || Types.empty())
1024 continue;
1025
1026 VTableBits *&BitsPtr = GVToBits[&GV];
1027 if (!BitsPtr) {
1028 Bits.emplace_back();
1029 Bits.back().GV = &GV;
1030 Bits.back().ObjectSize =
1031 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType());
1032 BitsPtr = &Bits.back();
1033 }
1034
1035 for (MDNode *Type : Types) {
1036 auto *TypeID = Type->getOperand(1).get();
1037
1040 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
1041 ->getZExtValue();
1042
1043 TypeIdMap[TypeID].insert({BitsPtr, Offset});
1044 }
1045 }
1046}
1047
1048bool DevirtModule::tryFindVirtualCallTargets(
1049 std::vector<VirtualCallTarget> &TargetsForSlot,
1050 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset,
1051 ModuleSummaryIndex *ExportSummary, bool &HasPublicTarget) {
1052 HasPublicTarget = false;
1053
1054 for (const TypeMemberInfo &TM : TypeMemberInfos) {
1055 if (!TM.Bits->GV->isConstant())
1056 return false;
1057
1058 if (TM.Bits->GV->getVCallVisibility() ==
1060 HasPublicTarget = true;
1061 if (!DevirtSpeculatively)
1062 return false;
1063 }
1064
1065 // A local vtable without live uses cannot be loaded from, so it does not
1066 // provide a call target.
1067 if (TM.Bits->GV->hasLocalLinkage() && TM.Bits->GV->hasZeroLiveUses())
1068 continue;
1069
1070 Function *Fn = nullptr;
1071 Constant *C = nullptr;
1072 std::tie(Fn, C) =
1073 getFunctionAtVTableOffset(TM.Bits->GV, TM.Offset + ByteOffset, M);
1074
1075 if (!Fn)
1076 return false;
1077
1078 if (FunctionsToSkip.match(Fn->getName()))
1079 return false;
1080
1081 // We can disregard __cxa_pure_virtual as a possible call target, as
1082 // calls to pure virtuals are UB.
1083 if (Fn->getName() == "__cxa_pure_virtual")
1084 continue;
1085
1086 // We can disregard unreachable functions as possible call targets, as
1087 // unreachable functions shouldn't be called.
1088 if (!Opts.wholeprogramdevirt_keep_unreachable_function &&
1089 mustBeUnreachableFunction(Fn, ExportSummary))
1090 continue;
1091
1092 // Save the symbol used in the vtable to use as the devirtualization
1093 // target.
1094 auto *GV = dyn_cast<GlobalValue>(C);
1095 assert(GV);
1096 if (auto *GA = dyn_cast<GlobalAlias>(GV))
1097 if (!GA->isInterposable() && !GA->getAliaseeObject()->isInterposable())
1098 GV = GA->getAliaseeObject();
1099 TargetsForSlot.push_back({GV, &TM});
1100 }
1101
1102 // In most cases empty functions will be overridden by the
1103 // implementation of the derived class, so we can skip them
1104 // for speculative devirtualization.
1105 if (HasPublicTarget) {
1106 erase_if(TargetsForSlot, [](const VirtualCallTarget &Target) {
1107 const auto *Fn = dyn_cast<Function>(Target.Fn);
1108 if (!Fn)
1109 Fn = cast<Function>(cast<GlobalAlias>(Target.Fn)->getAliasee());
1110 // TODO: This heuristic is currently not applied during hybrid LTO because
1111 // we skip all declarations. If there is a function summary, we should get
1112 // the instruction from there instead.
1113 return !Fn->isDeclaration() && Fn->getReturnType()->isVoidTy() &&
1114 Fn->getInstructionCount() <= 1;
1115 });
1116 }
1117
1118 // Give up if we couldn't find any targets.
1119 return !TargetsForSlot.empty();
1120}
1121
1122bool DevirtIndex::tryFindVirtualCallTargets(
1123 std::vector<ValueInfo> &TargetsForSlot,
1124 const TypeIdCompatibleVtableInfo TIdInfo, uint64_t ByteOffset,
1125 bool &HasPublicTarget) {
1126 HasPublicTarget = false;
1127
1128 for (const TypeIdOffsetVtableInfo &P : TIdInfo) {
1129 // Find a representative copy of the vtable initializer.
1130 // We can have multiple available_externally, linkonce_odr and weak_odr
1131 // vtable initializers. We can also have multiple external vtable
1132 // initializers in the case of comdats, which we cannot check here.
1133 // The linker should give an error in this case.
1134 //
1135 // Also, handle the case of same-named local Vtables with the same path
1136 // and therefore the same GUID. This can happen if there isn't enough
1137 // distinguishing path when compiling the source file. In that case we
1138 // conservatively return false early.
1139 if (P.VTableVI.hasLocal() && P.VTableVI.getSummaryList().size() > 1)
1140 return false;
1141 const GlobalVarSummary *VS = nullptr;
1142 for (const auto &S : P.VTableVI.getSummaryList()) {
1143 auto *CurVS = cast<GlobalVarSummary>(S->getBaseObject());
1144 if (!CurVS->vTableFuncs().empty() ||
1145 // Previously clang did not attach the necessary type metadata to
1146 // available_externally vtables, in which case there would not
1147 // be any vtable functions listed in the summary and we need
1148 // to treat this case conservatively (in case the bitcode is old).
1149 // However, we will also not have any vtable functions in the
1150 // case of a pure virtual base class. In that case we do want
1151 // to set VS to avoid treating it conservatively.
1153 VS = CurVS;
1154 // We cannot perform whole program devirtualization analysis on a vtable
1155 // with public LTO visibility.
1156 if (VS->getVCallVisibility() == GlobalObject::VCallVisibilityPublic) {
1157 HasPublicTarget = true;
1158 if (!DevirtSpeculatively)
1159 return false;
1160 }
1161 break;
1162 }
1163 }
1164 // There will be no VS if all copies are available_externally having no
1165 // type metadata. In that case we can't safely perform WPD.
1166 if (!VS)
1167 return false;
1168 if (!VS->isLive())
1169 continue;
1170 for (auto VTP : VS->vTableFuncs()) {
1171 if (VTP.VTableOffset != P.AddressPointOffset + ByteOffset)
1172 continue;
1173
1174 if (!Opts.wholeprogramdevirt_keep_unreachable_function &&
1175 mustBeUnreachableFunction(VTP.FuncVI))
1176 continue;
1177
1178 TargetsForSlot.push_back(VTP.FuncVI);
1179 }
1180 }
1181
1182 // Give up if we couldn't find any targets.
1183 return !TargetsForSlot.empty();
1184}
1185
1186void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo,
1187 Constant *TheFn, bool HasPublicTarget,
1188 bool &IsExported) {
1189 // Don't devirtualize function if we're told to skip it
1190 // in -wholeprogramdevirt-skip.
1191 if (FunctionsToSkip.match(TheFn->stripPointerCasts()->getName()))
1192 return;
1193 auto Apply = [&](CallSiteInfo &CSInfo) {
1194 for (auto &&VCallSite : CSInfo.CallSites) {
1195 if (!OptimizedCalls.insert(&VCallSite.CB).second)
1196 continue;
1197
1198 // Stop when the number of devirted calls reaches the cutoff.
1199 if (!DebugCounter::shouldExecute(CallsToDevirt))
1200 continue;
1201
1202 if (RemarksEnabled)
1203 VCallSite.emitRemark("single-impl",
1204 TheFn->stripPointerCasts()->getName(), OREGetter);
1205 NumSingleImpl++;
1206 auto &CB = VCallSite.CB;
1207 assert(!CB.getCalledFunction() && "devirtualizing direct call?");
1208 IRBuilder<> Builder(&CB);
1209 Value *Callee =
1210 Builder.CreateBitCast(TheFn, CB.getCalledOperand()->getType());
1211
1212 // If trap checking is enabled, add support to compare the virtual
1213 // function pointer to the devirtualized target. In case of a mismatch,
1214 // perform a debug trap.
1215 if (Opts.wholeprogramdevirt_check == WPDCheckMode::Trap) {
1216 auto *Cond = Builder.CreateICmpNE(CB.getCalledOperand(), Callee);
1218 Cond, &CB, /*Unreachable=*/false,
1219 MDBuilder(M.getContext()).createUnlikelyBranchWeights());
1220 Builder.SetInsertPoint(ThenTerm);
1221 Function *TrapFn =
1222 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::debugtrap);
1223 auto *CallTrap = Builder.CreateCall(TrapFn);
1224 CallTrap->setDebugLoc(CB.getDebugLoc());
1225 }
1226
1227 // If fallback checking or speculative devirtualization are enabled,
1228 // add support to compare the virtual function pointer to the
1229 // devirtualized target. In case of a mismatch, fall back to indirect
1230 // call. The guard's weights come from the indirect call's value
1231 // profile when one is available.
1232 if (Opts.wholeprogramdevirt_check == WPDCheckMode::Fallback ||
1233 HasPublicTarget) {
1234 MDBuilder MDB(M.getContext());
1235 uint64_t TotalCount = 0;
1237 CB, InstrProfValueKind::IPVK_IndirectCallTarget,
1238 std::numeric_limits<uint32_t>::max(), TotalCount);
1239 MDNode *Weights = nullptr;
1240 if (ValueData.empty() || TotalCount == 0) {
1241 Weights = MDB.createLikelyBranchWeights();
1242 } else {
1243 GlobalValue::GUID TargetGUID = cast<GlobalValue>(TheFn)->getGUID();
1244 auto It = llvm::find_if(ValueData, [&](const InstrProfValueData &VD) {
1245 return VD.Value == TargetGUID;
1246 });
1247 if (It == ValueData.end()) {
1248 Weights = MDB.createLikelyBranchWeights();
1249 } else {
1250 uint64_t FallbackCount =
1251 TotalCount - std::min(TotalCount, It->Count);
1252 assert((FallbackCount != 0 || It->Count != 0) &&
1253 "devirt branch weights are both zero.");
1254 Weights =
1255 MDB.createBranchWeights(fitWeights({It->Count, FallbackCount}));
1256 }
1257 }
1258 // Version the indirect call site. If the called value is equal to the
1259 // given callee, 'NewInst' will be executed, otherwise the original call
1260 // site will be executed.
1261 CallBase &NewInst = versionCallSite(CB, Callee, Weights);
1262 NewInst.setCalledOperand(Callee);
1263 // Since the new call site is direct, we must clear metadata that
1264 // is only appropriate for indirect calls. This includes !prof and
1265 // !callees metadata.
1266 NewInst.setMetadata(LLVMContext::MD_prof, nullptr);
1267 NewInst.setMetadata(LLVMContext::MD_callees, nullptr);
1268 // Additionally, we should remove them from the fallback indirect call,
1269 // so that we don't attempt to perform indirect call promotion later.
1270 CB.setMetadata(LLVMContext::MD_prof, nullptr);
1271 CB.setMetadata(LLVMContext::MD_callees, nullptr);
1272 }
1273
1274 // In either trapping or non-checking mode, devirtualize original call.
1275 else {
1276 // Devirtualize unconditionally.
1277 assert(!HasPublicTarget);
1278 CB.setCalledOperand(Callee);
1279 // Since the call site is now direct, we must clear metadata that
1280 // is only appropriate for indirect calls. This includes !prof and
1281 // !callees metadata.
1282 CB.setMetadata(LLVMContext::MD_prof, nullptr);
1283 CB.setMetadata(LLVMContext::MD_callees, nullptr);
1284 if (CB.getCalledOperand() &&
1286 auto *NewCS = CallBase::removeOperandBundle(
1288 CB.replaceAllUsesWith(NewCS);
1289 // Schedule for deletion at the end of pass run.
1290 CallsWithPtrAuthBundleRemoved.push_back(&CB);
1291 }
1292
1293 // This use is no longer unsafe.
1294 if (VCallSite.NumUnsafeUses)
1295 --*VCallSite.NumUnsafeUses;
1296 }
1297 }
1298 if (CSInfo.isExported())
1299 IsExported = true;
1300 if (!HasPublicTarget &&
1301 Opts.wholeprogramdevirt_check != WPDCheckMode::Fallback)
1302 CSInfo.markDevirt();
1303 };
1304 Apply(SlotInfo.CSInfo);
1305 for (auto &P : SlotInfo.ConstCSInfo)
1306 Apply(P.second);
1307}
1308
1309static bool addCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee) {
1310 // We can't add calls if we haven't seen a definition
1311 if (Callee.getSummaryList().empty())
1312 return false;
1313
1314 // Insert calls into the summary index so that the devirtualized targets
1315 // are eligible for import.
1316 // FIXME: Annotate type tests with hotness. For now, mark these as hot
1317 // to better ensure we have the opportunity to inline them.
1318 bool IsExported = false;
1319 auto &S = Callee.getSummaryList()[0];
1320 CalleeInfo CI(CalleeInfo::HotnessType::Hot, /* HasTailCall = */ false);
1321 auto AddCalls = [&](CallSiteInfo &CSInfo) {
1322 for (auto *FS : CSInfo.SummaryTypeCheckedLoadUsers) {
1323 FS->addCall({Callee, CI});
1324 IsExported |= S->modulePath() != FS->modulePath();
1325 }
1326 for (auto *FS : CSInfo.SummaryTypeTestAssumeUsers) {
1327 FS->addCall({Callee, CI});
1328 IsExported |= S->modulePath() != FS->modulePath();
1329 }
1330 };
1331 AddCalls(SlotInfo.CSInfo);
1332 for (auto &P : SlotInfo.ConstCSInfo)
1333 AddCalls(P.second);
1334 return IsExported;
1335}
1336
1337bool DevirtModule::trySingleImplDevirt(
1338 ModuleSummaryIndex *ExportSummary,
1339 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1340 WholeProgramDevirtResolution *Res, bool HasPublicTarget) {
1341 // See if the program contains a single implementation of this virtual
1342 // function.
1343 auto *TheFn = TargetsForSlot[0].Fn;
1344 for (auto &&Target : TargetsForSlot)
1345 if (TheFn != Target.Fn)
1346 return false;
1347
1348 // If so, update each call site to call that implementation directly.
1349 if (RemarksEnabled || AreStatisticsEnabled())
1350 TargetsForSlot[0].WasDevirt = true;
1351
1352 bool IsExported = false;
1353 applySingleImplDevirt(SlotInfo, TheFn, HasPublicTarget, IsExported);
1354 if (!IsExported)
1355 return false;
1356
1357 // If the only implementation has local linkage, we must promote to external
1358 // to make it visible to thin LTO objects. We can only get here during the
1359 // ThinLTO export phase.
1360 if (TheFn->hasLocalLinkage()) {
1361 std::string NewName = (TheFn->getName() + ".llvm.merged").str();
1362
1363 // Since we are renaming the function, any comdats with the same name must
1364 // also be renamed. This is required when targeting COFF, as the comdat name
1365 // must match one of the names of the symbols in the comdat.
1366 if (Comdat *C = TheFn->getComdat()) {
1367 if (C->getName() == TheFn->getName()) {
1368 Comdat *NewC = M.getOrInsertComdat(NewName);
1369 NewC->setSelectionKind(C->getSelectionKind());
1370 for (GlobalObject &GO : M.global_objects())
1371 if (GO.getComdat() == C)
1372 GO.setComdat(NewC);
1373 }
1374 }
1375
1376 TheFn->setLinkage(GlobalValue::ExternalLinkage);
1377 TheFn->setVisibility(GlobalValue::HiddenVisibility);
1378 TheFn->setName(NewName);
1379 }
1380 if (ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFn->getGUID()))
1381 // Any needed promotion of 'TheFn' has already been done during
1382 // LTO unit split, so we can ignore return value of AddCalls.
1383 addCalls(SlotInfo, TheFnVI);
1384
1385 if (HasPublicTarget)
1387 else
1389
1390 Res->SingleImplName = std::string(TheFn->getName());
1391
1392 return true;
1393}
1394
1395bool DevirtIndex::trySingleImplDevirt(MutableArrayRef<ValueInfo> TargetsForSlot,
1396 VTableSlotSummary &SlotSummary,
1397 VTableSlotInfo &SlotInfo,
1398 WholeProgramDevirtResolution *Res,
1399 std::set<ValueInfo> &DevirtTargets,
1400 bool HasPublicTarget) {
1401 // See if the program contains a single implementation of this virtual
1402 // function.
1403 auto TheFn = TargetsForSlot[0];
1404 for (auto &&Target : TargetsForSlot)
1405 if (TheFn != Target)
1406 return false;
1407
1408 // Don't devirtualize if we don't have target definition.
1409 auto Size = TheFn.getSummaryList().size();
1410 if (!Size)
1411 return false;
1412
1413 // Don't devirtualize function if we're told to skip it
1414 // in -wholeprogramdevirt-skip.
1415 if (FunctionsToSkip.match(TheFn.name()))
1416 return false;
1417
1418 // If the summary list contains multiple summaries where at least one is
1419 // a local, give up, as we won't know which (possibly promoted) name to use.
1420 if (TheFn.hasLocal() && Size > 1)
1421 return false;
1422
1423 // Collect functions devirtualized at least for one call site for stats.
1424 if (Opts.wholeprogramdevirt_print_index_based || AreStatisticsEnabled())
1425 DevirtTargets.insert(TheFn);
1426
1427 auto &S = TheFn.getSummaryList()[0];
1428 bool IsExported = addCalls(SlotInfo, TheFn);
1429 if (IsExported)
1430 ExportedGUIDs.insert(TheFn.getGUID());
1431
1432 // Record in summary for use in devirtualization during the ThinLTO import
1433 // step.
1434 if (HasPublicTarget)
1436 else
1438
1439 if (GlobalValue::isLocalLinkage(S->linkage())) {
1440 if (IsExported) {
1441 // If target is a local function and we are exporting it by
1442 // devirtualizing a call in another module, we need to record the
1443 // promoted name.
1444 if (ExternallyVisibleSymbolNamesPtr)
1445 ExternallyVisibleSymbolNamesPtr->insert(TheFn.name());
1447 TheFn.name(), ExportSummary.getModuleHash(S->modulePath()));
1448 } else {
1449 LocalWPDTargetsMap[TheFn].push_back(SlotSummary);
1450 Res->SingleImplName = std::string(TheFn.name());
1451 }
1452 } else
1453 Res->SingleImplName = std::string(TheFn.name());
1454
1455 // Name will be empty if this thin link driven off of serialized combined
1456 // index (e.g. llvm-lto). However, WPD is not supported/invoked for the
1457 // legacy LTO API anyway.
1458 assert(!Res->SingleImplName.empty());
1459
1460 return true;
1461}
1462
1463void DevirtModule::tryICallBranchFunnel(
1464 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1465 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1466 Triple T(M.getTargetTriple());
1467 if (T.getArch() != Triple::x86_64)
1468 return;
1469
1470 if (TargetsForSlot.size() > Opts.wholeprogramdevirt_branch_funnel_threshold)
1471 return;
1472
1473 bool HasNonDevirt = !SlotInfo.CSInfo.AllCallSitesDevirted;
1474 if (!HasNonDevirt)
1475 for (auto &P : SlotInfo.ConstCSInfo)
1476 if (!P.second.AllCallSitesDevirted) {
1477 HasNonDevirt = true;
1478 break;
1479 }
1480
1481 if (!HasNonDevirt)
1482 return;
1483
1484 // If any GV is AvailableExternally, not to generate branch.funnel.
1485 // NOTE: It is to avoid crash in LowerTypeTest.
1486 // If the branch.funnel is generated, because GV.isDeclarationForLinker(),
1487 // in LowerTypeTestsModule::lower(), its GlobalTypeMember would NOT
1488 // be saved in GlobalTypeMembers[&GV]. Then crash happens in
1489 // buildBitSetsFromDisjointSet due to GlobalTypeMembers[&GV] is NULL.
1490 // Even doing experiment to save it in GlobalTypeMembers[&GV] and
1491 // making GlobalTypeMembers[&GV] be not NULL, crash could avoid from
1492 // buildBitSetsFromDisjointSet. But still report_fatal_error in Verifier
1493 // or SelectionDAGBuilder later, because operands linkage type consistency
1494 // check of icall.branch.funnel can not pass.
1495 for (auto &T : TargetsForSlot) {
1496 if (T.TM->Bits->GV->hasAvailableExternallyLinkage())
1497 return;
1498 }
1499
1500 FunctionType *FT =
1501 FunctionType::get(Type::getVoidTy(M.getContext()), {Int8PtrTy}, true);
1502 Function *JT;
1503 if (isa<MDString>(Slot.TypeID)) {
1505 M.getDataLayout().getProgramAddressSpace(),
1506 getGlobalName(Slot, {}, "branch_funnel"), &M);
1508 } else {
1510 M.getDataLayout().getProgramAddressSpace(),
1511 "branch_funnel", &M);
1512 }
1513 JT->addParamAttr(0, Attribute::Nest);
1514
1515 std::vector<Value *> JTArgs;
1516 JTArgs.push_back(JT->arg_begin());
1517 for (auto &T : TargetsForSlot) {
1518 JTArgs.push_back(getMemberAddr(T.TM));
1519 JTArgs.push_back(T.Fn);
1520 }
1521
1522 BasicBlock *BB = BasicBlock::Create(M.getContext(), "", JT, nullptr);
1524 &M, llvm::Intrinsic::icall_branch_funnel, {});
1525
1526 auto *CI = CallInst::Create(Intr, JTArgs, "", BB);
1527 CI->setTailCallKind(CallInst::TCK_MustTail);
1528 ReturnInst::Create(M.getContext(), nullptr, BB);
1529
1530 bool IsExported = false;
1531 applyICallBranchFunnel(SlotInfo, *JT, IsExported);
1532 if (IsExported)
1534
1535 if (!JT->getEntryCount().has_value()) {
1536 // FIXME: we could pass through thinlto the necessary information.
1538 }
1539}
1540
1541void DevirtModule::applyICallBranchFunnel(VTableSlotInfo &SlotInfo,
1542 Function &JT, bool &IsExported) {
1543 DenseMap<Function *, double> FunctionEntryCounts;
1544 auto Apply = [&](CallSiteInfo &CSInfo) {
1545 if (CSInfo.isExported())
1546 IsExported = true;
1547 if (CSInfo.AllCallSitesDevirted)
1548 return;
1549
1550 std::map<CallBase *, CallBase *> CallBases;
1551 for (auto &&VCallSite : CSInfo.CallSites) {
1552 CallBase &CB = VCallSite.CB;
1553
1554 if (CallBases.find(&CB) != CallBases.end()) {
1555 // When finding devirtualizable calls, it's possible to find the same
1556 // vtable passed to multiple llvm.type.test or llvm.type.checked.load
1557 // calls, which can cause duplicate call sites to be recorded in
1558 // [Const]CallSites. If we've already found one of these
1559 // call instances, just ignore it. It will be replaced later.
1560 continue;
1561 }
1562
1563 // Jump tables are only profitable if the retpoline mitigation is enabled.
1564 Attribute FSAttr = CB.getCaller()->getFnAttribute("target-features");
1565 if (!FSAttr.isValid() ||
1566 !FSAttr.getValueAsString().contains("+retpoline"))
1567 continue;
1568
1569 NumBranchFunnel++;
1570 if (RemarksEnabled)
1571 VCallSite.emitRemark("branch-funnel", JT.getName(), OREGetter);
1572
1573 // Pass the address of the vtable in the nest register, which is r10 on
1574 // x86_64.
1575 std::vector<Type *> NewArgs;
1576 NewArgs.push_back(Int8PtrTy);
1577 append_range(NewArgs, CB.getFunctionType()->params());
1578 FunctionType *NewFT =
1580 CB.getFunctionType()->isVarArg());
1581 IRBuilder<> IRB(&CB);
1582 std::vector<Value *> Args;
1583 Args.push_back(VCallSite.VTable);
1584 llvm::append_range(Args, CB.args());
1585
1586 CallBase *NewCS = nullptr;
1588 // Accumulate the call frequencies of the original call site, and use
1589 // that as total entry count for the funnel function.
1590 auto &F = *CB.getCaller();
1591 auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
1592 auto EC = BFI.getBlockFreq(&F.getEntryBlock());
1593 auto CC = F.getEntryCount();
1594 double CallCount = 0.0;
1595 if (EC.getFrequency() != 0 && CC && *CC != 0) {
1596 double CallFreq =
1597 static_cast<double>(
1598 BFI.getBlockFreq(CB.getParent()).getFrequency()) /
1599 EC.getFrequency();
1600 CallCount = CallFreq * *CC;
1601 }
1602 FunctionEntryCounts[&JT] += CallCount;
1603 }
1604 if (isa<CallInst>(CB))
1605 NewCS = IRB.CreateCall(NewFT, &JT, Args);
1606 else
1607 NewCS =
1608 IRB.CreateInvoke(NewFT, &JT, cast<InvokeInst>(CB).getNormalDest(),
1609 cast<InvokeInst>(CB).getUnwindDest(), Args);
1610 NewCS->setCallingConv(CB.getCallingConv());
1611
1612 AttributeList Attrs = CB.getAttributes();
1613 std::vector<AttributeSet> NewArgAttrs;
1614 NewArgAttrs.push_back(AttributeSet::get(
1615 M.getContext(), ArrayRef<Attribute>{Attribute::get(
1616 M.getContext(), Attribute::Nest)}));
1617 for (unsigned I = 0; I + 2 < Attrs.getNumAttrSets(); ++I)
1618 NewArgAttrs.push_back(Attrs.getParamAttrs(I));
1619 NewCS->setAttributes(
1620 AttributeList::get(M.getContext(), Attrs.getFnAttrs(),
1621 Attrs.getRetAttrs(), NewArgAttrs));
1622
1623 CallBases[&CB] = NewCS;
1624
1625 // This use is no longer unsafe.
1626 if (VCallSite.NumUnsafeUses)
1627 --*VCallSite.NumUnsafeUses;
1628 }
1629 // Don't mark as devirtualized because there may be callers compiled without
1630 // retpoline mitigation, which would mean that they are lowered to
1631 // llvm.type.test and therefore require an llvm.type.test resolution for the
1632 // type identifier.
1633
1634 for (auto &[Old, New] : CallBases) {
1635 Old->replaceAllUsesWith(New);
1636 Old->eraseFromParent();
1637 }
1638 };
1639 Apply(SlotInfo.CSInfo);
1640 for (auto &P : SlotInfo.ConstCSInfo)
1641 Apply(P.second);
1642 for (auto &[F, C] : FunctionEntryCounts) {
1643 assert(!F->getEntryCount() &&
1644 "Unexpected entry count for funnel that was freshly synthesized");
1645 F->setEntryCount(static_cast<uint64_t>(std::round(C)));
1646 }
1647}
1648
1649bool DevirtModule::tryEvaluateFunctionsWithArgs(
1651 ArrayRef<uint64_t> Args) {
1652 // Evaluate each function and store the result in each target's RetVal
1653 // field.
1654 for (VirtualCallTarget &Target : TargetsForSlot) {
1655 // TODO: Skip for now if the vtable symbol was an alias to a function,
1656 // need to evaluate whether it would be correct to analyze the aliasee
1657 // function for this optimization.
1658 auto *Fn = dyn_cast<Function>(Target.Fn);
1659 if (!Fn)
1660 return false;
1661
1662 if (Fn->arg_size() != Args.size() + 1)
1663 return false;
1664
1665 Evaluator Eval(M.getDataLayout(), nullptr);
1667 EvalArgs.push_back(
1669 for (unsigned I = 0; I != Args.size(); ++I) {
1670 auto *ArgTy =
1672 if (!ArgTy)
1673 return false;
1674 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I]));
1675 }
1676
1677 Constant *RetVal;
1678 if (!Eval.EvaluateFunction(Fn, RetVal, EvalArgs) ||
1679 !isa<ConstantInt>(RetVal))
1680 return false;
1681 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue();
1682 }
1683 return true;
1684}
1685
1686void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1687 uint64_t TheRetVal) {
1688 for (auto Call : CSInfo.CallSites) {
1689 if (!OptimizedCalls.insert(&Call.CB).second)
1690 continue;
1691 NumUniformRetVal++;
1692 Call.replaceAndErase(
1693 "uniform-ret-val", FnName, RemarksEnabled, OREGetter,
1694 ConstantInt::get(cast<IntegerType>(Call.CB.getType()), TheRetVal));
1695 }
1696 CSInfo.markDevirt();
1697}
1698
1699bool DevirtModule::tryUniformRetValOpt(
1700 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo,
1701 WholeProgramDevirtResolution::ByArg *Res) {
1702 // Uniform return value optimization. If all functions return the same
1703 // constant, replace all calls with that constant.
1704 uint64_t TheRetVal = TargetsForSlot[0].RetVal;
1705 for (const VirtualCallTarget &Target : TargetsForSlot)
1706 if (Target.RetVal != TheRetVal)
1707 return false;
1708
1709 if (CSInfo.isExported()) {
1711 Res->Info = TheRetVal;
1712 }
1713
1714 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal);
1715 if (RemarksEnabled || AreStatisticsEnabled())
1716 for (auto &&Target : TargetsForSlot)
1717 Target.WasDevirt = true;
1718 return true;
1719}
1720
1721std::string DevirtModule::getGlobalName(VTableSlot Slot,
1722 ArrayRef<uint64_t> Args,
1723 StringRef Name) {
1724 std::string FullName = "__typeid_";
1725 raw_string_ostream OS(FullName);
1726 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset;
1727 for (uint64_t Arg : Args)
1728 OS << '_' << Arg;
1729 OS << '_' << Name;
1730 return FullName;
1731}
1732
1733bool DevirtModule::shouldExportConstantsAsAbsoluteSymbols() {
1734 Triple T(M.getTargetTriple());
1735 return T.isX86() && T.getObjectFormat() == Triple::ELF;
1736}
1737
1738void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1739 StringRef Name, Constant *C) {
1740 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
1741 getGlobalName(Slot, Args, Name), C, &M);
1743}
1744
1745void DevirtModule::exportConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1746 StringRef Name, uint32_t Const,
1747 uint32_t &Storage) {
1748 if (shouldExportConstantsAsAbsoluteSymbols()) {
1749 exportGlobal(
1750 Slot, Args, Name,
1751 ConstantExpr::getIntToPtr(ConstantInt::get(Int32Ty, Const), Int8PtrTy));
1752 return;
1753 }
1754
1755 Storage = Const;
1756}
1757
1758Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args,
1759 StringRef Name) {
1760 GlobalVariable *GV =
1761 M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Arr0Ty);
1763 return GV;
1764}
1765
1766Constant *DevirtModule::importConstant(VTableSlot Slot, ArrayRef<uint64_t> Args,
1767 StringRef Name, IntegerType *IntTy,
1768 uint32_t Storage) {
1769 if (!shouldExportConstantsAsAbsoluteSymbols())
1770 return ConstantInt::get(IntTy, Storage);
1771
1772 Constant *C = importGlobal(Slot, Args, Name);
1773 auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
1774 C = ConstantExpr::getPtrToInt(C, IntTy);
1775
1776 // We only need to set metadata if the global is newly created, in which
1777 // case it would not have hidden visibility.
1778 if (GV->hasMetadata(LLVMContext::MD_absolute_symbol))
1779 return C;
1780
1781 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
1782 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
1783 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
1784 GV->setMetadata(LLVMContext::MD_absolute_symbol,
1785 MDNode::get(M.getContext(), {MinC, MaxC}));
1786 };
1787 unsigned AbsWidth = IntTy->getBitWidth();
1788 if (AbsWidth == IntPtrTy->getBitWidth()) {
1789 uint64_t AllOnes = IntTy->getBitMask();
1790 SetAbsRange(AllOnes, AllOnes); // Full set.
1791 } else {
1792 SetAbsRange(0, 1ull << AbsWidth);
1793 }
1794 return C;
1795}
1796
1797void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName,
1798 bool IsOne,
1799 Constant *UniqueMemberAddr) {
1800 for (auto &&Call : CSInfo.CallSites) {
1801 if (!OptimizedCalls.insert(&Call.CB).second)
1802 continue;
1803 IRBuilder<> B(&Call.CB);
1804 Value *Cmp =
1805 B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, Call.VTable,
1806 B.CreateBitCast(UniqueMemberAddr, Call.VTable->getType()));
1807 Cmp = B.CreateZExt(Cmp, Call.CB.getType());
1808 NumUniqueRetVal++;
1809 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, OREGetter,
1810 Cmp);
1811 }
1812 CSInfo.markDevirt();
1813}
1814
1815Constant *DevirtModule::getMemberAddr(const TypeMemberInfo *M) {
1816 return ConstantExpr::getPtrAdd(M->Bits->GV,
1817 ConstantInt::get(Int64Ty, M->Offset));
1818}
1819
1820bool DevirtModule::tryUniqueRetValOpt(
1821 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot,
1822 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res,
1823 VTableSlot Slot, ArrayRef<uint64_t> Args) {
1824 // IsOne controls whether we look for a 0 or a 1.
1825 auto tryUniqueRetValOptFor = [&](bool IsOne) {
1826 const TypeMemberInfo *UniqueMember = nullptr;
1827 for (const VirtualCallTarget &Target : TargetsForSlot) {
1828 if (Target.RetVal == (IsOne ? 1 : 0)) {
1829 if (UniqueMember)
1830 return false;
1831 UniqueMember = Target.TM;
1832 }
1833 }
1834
1835 // We should have found a unique member or bailed out by now. We already
1836 // checked for a uniform return value in tryUniformRetValOpt.
1837 assert(UniqueMember);
1838
1839 Constant *UniqueMemberAddr = getMemberAddr(UniqueMember);
1840 if (CSInfo.isExported()) {
1842 Res->Info = IsOne;
1843
1844 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr);
1845 }
1846
1847 // Replace each call with the comparison.
1848 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne,
1849 UniqueMemberAddr);
1850
1851 // Update devirtualization statistics for targets.
1852 if (RemarksEnabled || AreStatisticsEnabled())
1853 for (auto &&Target : TargetsForSlot)
1854 Target.WasDevirt = true;
1855
1856 return true;
1857 };
1858
1859 if (BitWidth == 1) {
1860 if (tryUniqueRetValOptFor(true))
1861 return true;
1862 if (tryUniqueRetValOptFor(false))
1863 return true;
1864 }
1865 return false;
1866}
1867
1868void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName,
1869 Constant *Byte, Constant *Bit) {
1870 for (auto Call : CSInfo.CallSites) {
1871 if (!OptimizedCalls.insert(&Call.CB).second)
1872 continue;
1873 auto *RetType = cast<IntegerType>(Call.CB.getType());
1874 IRBuilder<> B(&Call.CB);
1875 Value *Addr = B.CreatePtrAddWithSExtOrTrunc(Call.VTable, Byte);
1876 if (RetType->getBitWidth() == 1) {
1877 Value *Bits = B.CreateLoad(Int8Ty, Addr);
1878 Value *BitsAndBit = B.CreateAnd(Bits, Bit);
1879 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0));
1880 NumVirtConstProp1Bit++;
1881 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled,
1882 OREGetter, IsBitSet);
1883 } else {
1884 Value *Val = B.CreateLoad(RetType, Addr);
1885 NumVirtConstProp++;
1886 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled,
1887 OREGetter, Val);
1888 }
1889 }
1890 CSInfo.markDevirt();
1891}
1892
1893bool DevirtModule::tryVirtualConstProp(
1894 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo,
1895 WholeProgramDevirtResolution *Res, VTableSlot Slot) {
1896 // TODO: Skip for now if the vtable symbol was an alias to a function,
1897 // need to evaluate whether it would be correct to analyze the aliasee
1898 // function for this optimization.
1899 auto *Fn = dyn_cast<Function>(TargetsForSlot[0].Fn);
1900 if (!Fn)
1901 return false;
1902 // This only works if the function returns an integer.
1903 auto *RetType = dyn_cast<IntegerType>(Fn->getReturnType());
1904 if (!RetType)
1905 return false;
1906 unsigned BitWidth = RetType->getBitWidth();
1907
1908 // TODO: Since we can evaluated these constants at compile-time, we can save
1909 // some space by calculating the smallest range of values that all these
1910 // constants can fit in, then only allocate enough space to fit those values.
1911 // At each callsite, we can get the original type by doing a sign/zero
1912 // extension. For example, if we would store an i64, but we can see that all
1913 // the values fit into an i16, then we can store an i16 before/after the
1914 // vtable and at each callsite do a s/zext.
1915 if (BitWidth > 64)
1916 return false;
1917
1918 Align TypeAlignment = M.getDataLayout().getABIIntegerTypeAlignment(BitWidth);
1919
1920 // Make sure that each function is defined, does not access memory, takes at
1921 // least one argument, does not use its first argument (which we assume is
1922 // 'this'), and has the same return type.
1923 //
1924 // Note that we test whether this copy of the function is readnone, rather
1925 // than testing function attributes, which must hold for any copy of the
1926 // function, even a less optimized version substituted at link time. This is
1927 // sound because the virtual constant propagation optimizations effectively
1928 // inline all implementations of the virtual function into each call site,
1929 // rather than using function attributes to perform local optimization.
1930 for (VirtualCallTarget &Target : TargetsForSlot) {
1931 // TODO: Skip for now if the vtable symbol was an alias to a function,
1932 // need to evaluate whether it would be correct to analyze the aliasee
1933 // function for this optimization.
1934 auto *Fn = dyn_cast<Function>(Target.Fn);
1935 if (!Fn)
1936 return false;
1937
1938 if (Fn->isDeclaration() || Fn->isInterposable() ||
1939 !computeFunctionBodyMemoryAccess(*Fn, FAM.getResult<AAManager>(*Fn))
1941 Fn->arg_empty() || !Fn->arg_begin()->use_empty() ||
1942 Fn->getReturnType() != RetType)
1943 return false;
1944
1945 // This only works if the integer size is at most the alignment of the
1946 // vtable. If the table is underaligned, then we can't guarantee that the
1947 // constant will always be aligned to the integer type alignment. For
1948 // example, if the table is `align 1`, we can never guarantee that an i32
1949 // stored before/after the vtable is 32-bit aligned without changing the
1950 // alignment of the new global.
1951 GlobalVariable *GV = Target.TM->Bits->GV;
1952 Align TableAlignment = M.getDataLayout().getValueOrABITypeAlignment(
1953 GV->getAlign(), GV->getValueType());
1954 if (TypeAlignment > TableAlignment)
1955 return false;
1956 }
1957
1958 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) {
1959 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first))
1960 continue;
1961
1962 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr;
1963 if (Res)
1964 ResByArg = &Res->ResByArg[CSByConstantArg.first];
1965
1966 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg))
1967 continue;
1968
1969 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second,
1970 ResByArg, Slot, CSByConstantArg.first))
1971 continue;
1972
1973 // Find an allocation offset in bits in all vtables associated with the
1974 // type.
1975 // TODO: If there would be "holes" in the vtable that were added by
1976 // padding, we could place i1s there to reduce any extra padding that
1977 // would be introduced by the i1s.
1978 uint64_t AllocBefore =
1979 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth);
1980 uint64_t AllocAfter =
1981 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth);
1982
1983 // Calculate the total amount of padding needed to store a value at both
1984 // ends of the object.
1985 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0;
1986 for (auto &&Target : TargetsForSlot) {
1987 TotalPaddingBefore += std::max<int64_t>(
1988 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0);
1989 TotalPaddingAfter += std::max<int64_t>(
1990 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0);
1991 }
1992
1993 // If the amount of padding is too large, give up.
1994 // FIXME: do something smarter here.
1995 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128)
1996 continue;
1997
1998 // Calculate the offset to the value as a (possibly negative) byte offset
1999 // and (if applicable) a bit offset, and store the values in the targets.
2000 int64_t OffsetByte;
2001 uint64_t OffsetBit;
2002 if (TotalPaddingBefore <= TotalPaddingAfter)
2003 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte,
2004 OffsetBit);
2005 else
2006 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte,
2007 OffsetBit);
2008
2009 // In an earlier check we forbade constant propagation from operating on
2010 // tables whose alignment is less than the alignment needed for loading
2011 // the constant. Thus, the address we take the offset from will always be
2012 // aligned to at least this integer alignment. Now, we need to ensure that
2013 // the offset is also aligned to this integer alignment to ensure we always
2014 // have an aligned load.
2015 assert(OffsetByte % TypeAlignment.value() == 0);
2016
2017 if (RemarksEnabled || AreStatisticsEnabled())
2018 for (auto &&Target : TargetsForSlot)
2019 Target.WasDevirt = true;
2020
2021
2022 if (CSByConstantArg.second.isExported()) {
2024 ResByArg->Byte = OffsetByte;
2025 exportConstant(Slot, CSByConstantArg.first, "bit", 1ULL << OffsetBit,
2026 ResByArg->Bit);
2027 }
2028
2029 // Rewrite each call to a load from OffsetByte/OffsetBit.
2030 Constant *ByteConst = ConstantInt::getSigned(Int32Ty, OffsetByte);
2031 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit);
2032 applyVirtualConstProp(CSByConstantArg.second,
2033 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst);
2034 }
2035 return true;
2036}
2037
2038void DevirtModule::rebuildGlobal(VTableBits &B) {
2039 if (B.Before.Bytes.empty() && B.After.Bytes.empty())
2040 return;
2041
2042 // Align the before byte array to the global's minimum alignment so that we
2043 // don't break any alignment requirements on the global.
2044 Align Alignment = M.getDataLayout().getValueOrABITypeAlignment(
2045 B.GV->getAlign(), B.GV->getValueType());
2046 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), Alignment));
2047
2048 // Before was stored in reverse order; flip it now.
2049 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I)
2050 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]);
2051
2052 // Build an anonymous global containing the before bytes, followed by the
2053 // original initializer, followed by the after bytes.
2054 auto *NewInit = ConstantStruct::getAnon(
2055 {ConstantDataArray::get(M.getContext(), B.Before.Bytes),
2056 B.GV->getInitializer(),
2057 ConstantDataArray::get(M.getContext(), B.After.Bytes)});
2058 auto *NewGV =
2059 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(),
2060 GlobalVariable::PrivateLinkage, NewInit, "", B.GV);
2061 NewGV->setSection(B.GV->getSection());
2062 NewGV->setComdat(B.GV->getComdat());
2063 NewGV->setAlignment(B.GV->getAlign());
2064
2065 // Copy the original vtable's metadata to the anonymous global, adjusting
2066 // offsets as required.
2067 NewGV->copyMetadata(B.GV, B.Before.Bytes.size());
2068
2069 // Build an alias named after the original global, pointing at the second
2070 // element (the original initializer).
2071 auto *Alias = GlobalAlias::create(
2072 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "",
2074 M.getDataLayout(), NewInit->getType(), NewGV,
2075 {ConstantInt::get(Int32Ty, 0), ConstantInt::get(Int32Ty, 1)},
2077 &M);
2078 Alias->setVisibility(B.GV->getVisibility());
2079 Alias->takeName(B.GV);
2080
2081 B.GV->replaceAllUsesWith(Alias);
2082 B.GV->eraseFromParent();
2083}
2084
2085bool DevirtModule::areRemarksEnabled() {
2086 const auto &FL = M.getFunctionList();
2087 for (const Function &Fn : FL) {
2088 if (Fn.empty())
2089 continue;
2090 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &Fn.front());
2091 return DI.isEnabled();
2092 }
2093 return false;
2094}
2095
2096/// Find assumes whose conditions depend on this type test through phi or select
2097/// nodes. SimplifyCFG can produce these patterns by merging type test + assume
2098/// sequences from different predecessors.
2099static void
2101 CallInst &TypeTest,
2102 SmallPtrSetImpl<Value *> &VisitedMerges) {
2103 SmallVector<Value *, 4> Worklist;
2104#ifndef NDEBUG
2105 SmallPtrSet<CallInst *, 4> DirectAssumes(Assumes.begin(), Assumes.end());
2106#endif
2107
2108 auto GetMergeUser = [](User *U, Value *V) -> Value * {
2109 if (isa<PHINode>(U))
2110 return U;
2111 if (auto *Select = dyn_cast<SelectInst>(U);
2112 Select && (Select->getTrueValue() == V || Select->getFalseValue() == V))
2113 return Select;
2114 return nullptr;
2115 };
2116
2117 // Direct assume users were already collected by
2118 // findDevirtualizableCallsForTypeTest. Start from merge users so this search
2119 // finds only assumptions that depend on the type test through merges.
2120 for (User *U : TypeTest.users())
2121 if (Value *Merge = GetMergeUser(U, &TypeTest))
2122 Worklist.push_back(Merge);
2123
2124 while (!Worklist.empty()) {
2125 Value *V = Worklist.pop_back_val();
2126 if (!VisitedMerges.insert(V).second)
2127 continue;
2128
2129 for (User *U : V->users()) {
2130 if (auto *Assume = dyn_cast<AssumeInst>(U)) {
2131 if (Assume->getArgOperand(0) == V) {
2132 assert(!DirectAssumes.contains(Assume) &&
2133 "assume must not be both direct and merged");
2134 Assumes.push_back(Assume);
2135 }
2136 continue;
2137 }
2138
2139 if (Value *Merge = GetMergeUser(U, V))
2140 Worklist.push_back(Merge);
2141 }
2142 }
2143}
2144
2145void DevirtModule::scanTypeTestUsers(
2146 Function *TypeTestFunc,
2147 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) {
2148 // Cleanup removes every assume reachable through a merge, so each merge only
2149 // needs to be processed once even if multiple unresolved type tests reach it.
2150 SmallPtrSet<Value *, 8> VisitedMerges;
2151
2152 // Find all virtual calls via a virtual table pointer %p under an assumption
2153 // of the form llvm.assume(llvm.type.test(%p, %md)) or
2154 // llvm.assume(llvm.public.type.test(%p, %md)).
2155 // This indicates that %p points to a member of the type identifier %md.
2156 // Group calls by (type ID, offset) pair (effectively the identity of the
2157 // virtual function) and store to CallSlots.
2158 for (Use &U : llvm::make_early_inc_range(TypeTestFunc->uses())) {
2159 auto *CI = dyn_cast<CallInst>(U.getUser());
2160 if (!CI)
2161 continue;
2162 // Search for virtual calls based on %p and add them to DevirtCalls.
2165 auto &DT = FAM.getResult<DominatorTreeAnalysis>(*CI->getFunction());
2166 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
2167
2168 Metadata *TypeId =
2169 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata();
2170 // If we found any, add them to CallSlots.
2171 if (!Assumes.empty()) {
2172 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts();
2173 for (DevirtCallSite Call : DevirtCalls)
2174 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB, nullptr);
2175 }
2176
2177 auto RemoveTypeTestAssumes = [&]() {
2178 // A merge of type test results does not imply that any individual type
2179 // test can be assumed, so don't use these assumes to identify
2180 // devirtualizable calls. They still need to be removed when type
2181 // information is missing for any value contributing to the merge.
2182 findAssumesThroughMergesForTypeTest(Assumes, *CI, VisitedMerges);
2183
2184 // We no longer need the assumes or the type test.
2185 for (auto *Assume : Assumes)
2186 Assume->eraseFromParent();
2187 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we
2188 // may use the vtable argument later.
2189 if (CI->use_empty())
2190 CI->eraseFromParent();
2191 };
2192
2193 // At this point we could remove all type test assume sequences, as they
2194 // were originally inserted for WPD. However, we can keep these in the
2195 // code stream for later analysis (e.g. to help drive more efficient ICP
2196 // sequences). They will eventually be removed by a second LowerTypeTests
2197 // invocation that cleans them up. In order to do this correctly, the first
2198 // LowerTypeTests invocation needs to know that they have "Unknown" type
2199 // test resolution, so that they aren't treated as Unsat and lowered to
2200 // False, which will break any uses on assumes. Below we remove any type
2201 // test assumes that will not be treated as Unknown by LTT.
2202
2203 // The type test assumes will be treated by LTT as Unsat if the type id is
2204 // not used on a global (in which case it has no entry in the TypeIdMap).
2205 if (!TypeIdMap.count(TypeId))
2206 RemoveTypeTestAssumes();
2207
2208 // For ThinLTO importing, we need to remove the type test assumes if this is
2209 // an MDString type id without a corresponding TypeIdSummary. Any
2210 // non-MDString type ids are ignored and treated as Unknown by LTT, so their
2211 // type test assumes can be kept. If the MDString type id is missing a
2212 // TypeIdSummary (e.g. because there was no use on a vcall, preventing the
2213 // exporting phase of WPD from analyzing it), then it would be treated as
2214 // Unsat by LTT and we need to remove its type test assumes here. If not
2215 // used on a vcall we don't need them for later optimization use in any
2216 // case.
2217 else if (ImportSummary && isa<MDString>(TypeId)) {
2218 const TypeIdSummary *TidSummary =
2219 ImportSummary->getTypeIdSummary(cast<MDString>(TypeId)->getString());
2220 if (!TidSummary)
2221 RemoveTypeTestAssumes();
2222 else
2223 // If one was created it should not be Unsat, because if we reached here
2224 // the type id was used on a global.
2226 }
2227 }
2228}
2229
2230void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) {
2231 Function *TypeTestFunc =
2232 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::type_test);
2233
2234 for (Use &U : llvm::make_early_inc_range(TypeCheckedLoadFunc->uses())) {
2235 auto *CI = dyn_cast<CallInst>(U.getUser());
2236 if (!CI)
2237 continue;
2238
2239 Value *Ptr = CI->getArgOperand(0);
2240 Value *Offset = CI->getArgOperand(1);
2241 Value *TypeIdValue = CI->getArgOperand(2);
2242 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata();
2243
2247 bool HasNonCallUses = false;
2248 auto &DT = FAM.getResult<DominatorTreeAnalysis>(*CI->getFunction());
2249 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
2250 HasNonCallUses, CI, DT);
2251
2252 // Start by generating "pessimistic" code that explicitly loads the function
2253 // pointer from the vtable and performs the type check. If possible, we will
2254 // eliminate the load and the type check later.
2255
2256 // If possible, only generate the load at the point where it is used.
2257 // This helps avoid unnecessary spills.
2258 IRBuilder<> LoadB(
2259 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI);
2260
2261 Value *LoadedValue = nullptr;
2262 if (TypeCheckedLoadFunc->getIntrinsicID() ==
2263 Intrinsic::type_checked_load_relative) {
2265 &M, Intrinsic::load_relative, {Int32Ty});
2266 LoadedValue = LoadB.CreateCall(LoadRelFunc, {Ptr, Offset});
2267 } else {
2268 Value *GEP = LoadB.CreatePtrAddWithSExtOrTrunc(Ptr, Offset);
2269 LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEP);
2270 }
2271
2272 for (Instruction *LoadedPtr : LoadedPtrs) {
2273 LoadedPtr->replaceAllUsesWith(LoadedValue);
2274 LoadedPtr->eraseFromParent();
2275 }
2276
2277 // Likewise for the type test.
2278 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI);
2279 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue});
2280
2281 for (Instruction *Pred : Preds) {
2282 Pred->replaceAllUsesWith(TypeTestCall);
2283 Pred->eraseFromParent();
2284 }
2285
2286 // We have already erased any extractvalue instructions that refer to the
2287 // intrinsic call, but the intrinsic may have other non-extractvalue uses
2288 // (although this is unlikely). In that case, explicitly build a pair and
2289 // RAUW it.
2290 if (!CI->use_empty()) {
2291 Value *Pair = PoisonValue::get(CI->getType());
2292 IRBuilder<> B(CI);
2293 Pair = B.CreateInsertValue(Pair, LoadedValue, {0});
2294 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1});
2295 CI->replaceAllUsesWith(Pair);
2296 }
2297
2298 // The number of unsafe uses is initially the number of uses.
2299 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall];
2300 NumUnsafeUses = DevirtCalls.size();
2301
2302 // If the function pointer has a non-call user, we cannot eliminate the type
2303 // check, as one of those users may eventually call the pointer. Increment
2304 // the unsafe use count to make sure it cannot reach zero.
2305 if (HasNonCallUses)
2306 ++NumUnsafeUses;
2307 for (DevirtCallSite Call : DevirtCalls) {
2308 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CB,
2309 &NumUnsafeUses);
2310 }
2311
2312 CI->eraseFromParent();
2313 }
2314}
2315
2316void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) {
2317 auto *TypeId = dyn_cast<MDString>(Slot.TypeID);
2318 if (!TypeId)
2319 return;
2320 const TypeIdSummary *TidSummary =
2321 ImportSummary->getTypeIdSummary(TypeId->getString());
2322 if (!TidSummary)
2323 return;
2324 auto ResI = TidSummary->WPDRes.find(Slot.ByteOffset);
2325 if (ResI == TidSummary->WPDRes.end())
2326 return;
2327 const WholeProgramDevirtResolution &Res = ResI->second;
2328
2331 assert(!Res.SingleImplName.empty());
2332 // The type of the function in the declaration is irrelevant because every
2333 // call site will cast it to the correct type.
2334 Value *SingleImplVal =
2335 M.getOrInsertFunction(Res.SingleImplName,
2336 Type::getVoidTy(M.getContext()))
2337 .getCallee();
2338 if (auto *A = dyn_cast<GlobalAlias>(SingleImplVal->stripPointerCasts()))
2339 if (!A->isInterposable() && !A->getAliaseeObject()->isInterposable())
2340 SingleImplVal = A->getAliaseeObject();
2341 Constant *SingleImpl = cast<Constant>(SingleImplVal);
2342
2343 // This is the import phase so we should not be exporting anything.
2344 bool IsExported = false;
2345 bool IsSpeculative =
2347 applySingleImplDevirt(SlotInfo, SingleImpl, IsSpeculative, IsExported);
2348 assert(!IsExported);
2349 }
2350
2351 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) {
2352 auto I = Res.ResByArg.find(CSByConstantArg.first);
2353 if (I == Res.ResByArg.end())
2354 continue;
2355 auto &ResByArg = I->second;
2356 // FIXME: We should figure out what to do about the "function name" argument
2357 // to the apply* functions, as the function names are unavailable during the
2358 // importing phase. For now we just pass the empty string. This does not
2359 // impact correctness because the function names are just used for remarks.
2360 switch (ResByArg.TheKind) {
2362 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info);
2363 break;
2365 Constant *UniqueMemberAddr =
2366 importGlobal(Slot, CSByConstantArg.first, "unique_member");
2367 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info,
2368 UniqueMemberAddr);
2369 break;
2370 }
2372 Constant *Byte = ConstantInt::get(Int32Ty, ResByArg.Byte);
2373 Constant *Bit = importConstant(Slot, CSByConstantArg.first, "bit", Int8Ty,
2374 ResByArg.Bit);
2375 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit);
2376 break;
2377 }
2378 default:
2379 break;
2380 }
2381 }
2382
2384 // The type of the function is irrelevant, because it's bitcast at calls
2385 // anyhow.
2386 auto *JT = cast<Function>(
2387 M.getOrInsertFunction(getGlobalName(Slot, {}, "branch_funnel"),
2388 Type::getVoidTy(M.getContext()))
2389 .getCallee());
2390 bool IsExported = false;
2391 applyICallBranchFunnel(SlotInfo, *JT, IsExported);
2392 assert(!IsExported);
2393 }
2394}
2395
2396void DevirtModule::removeRedundantTypeTests() {
2397 auto *True = ConstantInt::getTrue(M.getContext());
2398 for (auto &&U : NumUnsafeUsesForTypeTest) {
2399 if (U.second == 0) {
2400 U.first->replaceAllUsesWith(True);
2401 U.first->eraseFromParent();
2402 }
2403 }
2404}
2405
2406ValueInfo
2407DevirtModule::lookUpFunctionValueInfo(Function *TheFn,
2408 ModuleSummaryIndex *ExportSummary) {
2409 assert((ExportSummary != nullptr) &&
2410 "Caller guarantees ExportSummary is not nullptr");
2411
2412 const auto TheFnGUID = TheFn->getGUID();
2413 const auto TheFnGUIDWithExportedName =
2415 // Look up ValueInfo with the GUID in the current linkage.
2416 ValueInfo TheFnVI = ExportSummary->getValueInfo(TheFnGUID);
2417 // If no entry is found and GUID is different from GUID computed using
2418 // exported name, look up ValueInfo with the exported name unconditionally.
2419 // This is a fallback.
2420 //
2421 // The reason to have a fallback:
2422 // 1. LTO could enable global value internalization via
2423 // `enable-lto-internalization`.
2424 // 2. The GUID in ExportedSummary is computed using exported name.
2425 if ((!TheFnVI) && (TheFnGUID != TheFnGUIDWithExportedName)) {
2426 TheFnVI = ExportSummary->getValueInfo(TheFnGUIDWithExportedName);
2427 }
2428 return TheFnVI;
2429}
2430
2431bool DevirtModule::mustBeUnreachableFunction(
2432 Function *const F, ModuleSummaryIndex *ExportSummary) {
2433 // First, learn unreachability by analyzing function IR.
2434 if (!F->isDeclaration()) {
2435 // A function must be unreachable if its entry block ends with an
2436 // 'unreachable'.
2437 return isa<UnreachableInst>(F->getEntryBlock().getTerminator());
2438 }
2439 // Learn unreachability from ExportSummary if ExportSummary is present.
2440 return ExportSummary &&
2442 DevirtModule::lookUpFunctionValueInfo(F, ExportSummary));
2443}
2444
2445bool DevirtModule::run() {
2446 // If only some of the modules were split, we cannot correctly perform
2447 // this transformation. We already checked for the presense of type tests
2448 // with partially split modules during the thin link, and would have emitted
2449 // an error if any were found, so here we can simply return.
2450 if ((ExportSummary && ExportSummary->partiallySplitLTOUnits()) ||
2451 (ImportSummary && ImportSummary->partiallySplitLTOUnits()))
2452 return false;
2453
2454 Function *PublicTypeTestFunc = nullptr;
2455 // If we are in speculative devirtualization mode, we can work on the public
2456 // type test intrinsics.
2457 if (DevirtSpeculatively)
2458 PublicTypeTestFunc =
2459 Intrinsic::getDeclarationIfExists(&M, Intrinsic::public_type_test);
2460 Function *TypeTestFunc =
2461 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_test);
2462 Function *TypeCheckedLoadFunc =
2463 Intrinsic::getDeclarationIfExists(&M, Intrinsic::type_checked_load);
2464 Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
2465 &M, Intrinsic::type_checked_load_relative);
2466 Function *AssumeFunc =
2467 Intrinsic::getDeclarationIfExists(&M, Intrinsic::assume);
2468
2469 // Normally if there are no users of the devirtualization intrinsics in the
2470 // module, this pass has nothing to do. But if we are exporting, we also need
2471 // to handle any users that appear only in the function summaries.
2472 if (!ExportSummary &&
2473 (((!PublicTypeTestFunc || PublicTypeTestFunc->use_empty()) &&
2474 (!TypeTestFunc || TypeTestFunc->use_empty())) ||
2475 !AssumeFunc || AssumeFunc->use_empty()) &&
2476 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()) &&
2477 (!TypeCheckedLoadRelativeFunc ||
2478 TypeCheckedLoadRelativeFunc->use_empty()))
2479 return false;
2480
2481 // Rebuild type metadata into a map for easy lookup.
2482 std::vector<VTableBits> Bits;
2483 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap;
2484 buildTypeIdentifierMap(Bits, TypeIdMap);
2485
2486 if (PublicTypeTestFunc && AssumeFunc)
2487 scanTypeTestUsers(PublicTypeTestFunc, TypeIdMap);
2488
2489 if (TypeTestFunc && AssumeFunc)
2490 scanTypeTestUsers(TypeTestFunc, TypeIdMap);
2491
2492 if (TypeCheckedLoadFunc)
2493 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc);
2494
2495 if (TypeCheckedLoadRelativeFunc)
2496 scanTypeCheckedLoadUsers(TypeCheckedLoadRelativeFunc);
2497
2498 if (ImportSummary) {
2499 for (auto &S : CallSlots)
2500 importResolution(S.first, S.second);
2501
2502 removeRedundantTypeTests();
2503
2504 // We have lowered or deleted the type intrinsics, so we will no longer have
2505 // enough information to reason about the liveness of virtual function
2506 // pointers in GlobalDCE.
2507 for (GlobalVariable &GV : M.globals())
2508 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2509
2510 // The rest of the code is only necessary when exporting or during regular
2511 // LTO, so we are done.
2512 return true;
2513 }
2514
2515 if (TypeIdMap.empty())
2516 return true;
2517
2518 // Collect information from summary about which calls to try to devirtualize.
2519 if (ExportSummary) {
2520 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID;
2521 for (auto &P : TypeIdMap) {
2522 if (auto *TypeId = dyn_cast<MDString>(P.first))
2524 TypeId->getString())]
2525 .push_back(TypeId);
2526 }
2527
2528 for (auto &P : *ExportSummary) {
2529 for (auto &S : P.second.getSummaryList()) {
2530 auto *FS = dyn_cast<FunctionSummary>(S.get());
2531 if (!FS)
2532 continue;
2533 // FIXME: Only add live functions.
2534 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2535 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
2536 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2537 }
2538 }
2539 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2540 for (Metadata *MD : MetadataByGUID[VF.GUID]) {
2541 CallSlots[{MD, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2542 }
2543 }
2544 for (const FunctionSummary::ConstVCall &VC :
2545 FS->type_test_assume_const_vcalls()) {
2546 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2547 CallSlots[{MD, VC.VFunc.Offset}]
2548 .ConstCSInfo[VC.Args]
2549 .addSummaryTypeTestAssumeUser(FS);
2550 }
2551 }
2552 for (const FunctionSummary::ConstVCall &VC :
2553 FS->type_checked_load_const_vcalls()) {
2554 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) {
2555 CallSlots[{MD, VC.VFunc.Offset}]
2556 .ConstCSInfo[VC.Args]
2557 .addSummaryTypeCheckedLoadUser(FS);
2558 }
2559 }
2560 }
2561 }
2562 }
2563
2564 // For each (type, offset) pair:
2565 bool DidVirtualConstProp = false;
2566 std::map<std::string, GlobalValue *> DevirtTargets;
2567 for (auto &S : CallSlots) {
2568 // Search each of the members of the type identifier for the virtual
2569 // function implementation at offset S.first.ByteOffset, and add to
2570 // TargetsForSlot.
2571 std::vector<VirtualCallTarget> TargetsForSlot;
2572 WholeProgramDevirtResolution *Res = nullptr;
2573 const std::set<TypeMemberInfo> &TypeMemberInfos = TypeIdMap[S.first.TypeID];
2574 if (ExportSummary && isa<MDString>(S.first.TypeID) &&
2575 TypeMemberInfos.size())
2576 // For any type id used on a global's type metadata, create the type id
2577 // summary resolution regardless of whether we can devirtualize, so that
2578 // lower type tests knows the type id is not Unsat. If it was not used on
2579 // a global's type metadata, the TypeIdMap entry set will be empty, and
2580 // we don't want to create an entry (with the default Unknown type
2581 // resolution), which can prevent detection of the Unsat.
2582 Res = &ExportSummary
2583 ->getOrInsertTypeIdSummary(
2584 cast<MDString>(S.first.TypeID)->getString())
2585 .WPDRes[S.first.ByteOffset];
2586
2587 bool HasPublicTarget = true;
2588 if (tryFindVirtualCallTargets(TargetsForSlot, TypeMemberInfos,
2589 S.first.ByteOffset, ExportSummary,
2590 HasPublicTarget)) {
2591 bool SingleImplDevirt = trySingleImplDevirt(
2592 ExportSummary, TargetsForSlot, S.second, Res, HasPublicTarget);
2593 if (!SingleImplDevirt && !HasPublicTarget) {
2594 DidVirtualConstProp |=
2595 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first);
2596
2597 tryICallBranchFunnel(TargetsForSlot, S.second, Res, S.first);
2598 }
2599
2600 // Collect functions devirtualized at least for one call site for stats.
2601 if (RemarksEnabled || AreStatisticsEnabled())
2602 for (const auto &T : TargetsForSlot)
2603 if (T.WasDevirt)
2604 DevirtTargets[std::string(T.Fn->getName())] = T.Fn;
2605 }
2606
2607 // CFI-specific: if we are exporting and any llvm.type.checked.load
2608 // intrinsics were *not* devirtualized, we need to add the resulting
2609 // llvm.type.test intrinsics to the function summaries so that the
2610 // LowerTypeTests pass will export them.
2611 if (ExportSummary && isa<MDString>(S.first.TypeID)) {
2613 cast<MDString>(S.first.TypeID)->getString());
2614 auto AddTypeTestsForTypeCheckedLoads = [&](CallSiteInfo &CSI) {
2615 if (!CSI.AllCallSitesDevirted)
2616 for (auto *FS : CSI.SummaryTypeCheckedLoadUsers)
2617 FS->addTypeTest(GUID);
2618 };
2619 AddTypeTestsForTypeCheckedLoads(S.second.CSInfo);
2620 for (auto &CCS : S.second.ConstCSInfo)
2621 AddTypeTestsForTypeCheckedLoads(CCS.second);
2622 }
2623 }
2624
2625 if (RemarksEnabled) {
2626 // Generate remarks for each devirtualized function.
2627 for (const auto &DT : DevirtTargets) {
2628 GlobalValue *GV = DT.second;
2629 auto *F = dyn_cast<Function>(GV);
2630 if (!F) {
2631 auto *A = dyn_cast<GlobalAlias>(GV);
2632 assert(A && isa<Function>(A->getAliasee()));
2633 F = dyn_cast<Function>(A->getAliasee());
2634 assert(F);
2635 }
2636
2637 using namespace ore;
2638 OREGetter(*F).emit(OptimizationRemark(DEBUG_TYPE, "Devirtualized", F)
2639 << "devirtualized " << NV("FunctionName", DT.first));
2640 }
2641 }
2642
2643 NumDevirtTargets += DevirtTargets.size();
2644
2645 removeRedundantTypeTests();
2646
2647 // Rebuild each global we touched as part of virtual constant propagation to
2648 // include the before and after bytes.
2649 if (DidVirtualConstProp)
2650 for (VTableBits &B : Bits)
2651 rebuildGlobal(B);
2652
2653 // We have lowered or deleted the type intrinsics, so we will no longer have
2654 // enough information to reason about the liveness of virtual function
2655 // pointers in GlobalDCE.
2656 for (GlobalVariable &GV : M.globals())
2657 GV.eraseMetadata(LLVMContext::MD_vcall_visibility);
2658
2659 for (auto *CI : CallsWithPtrAuthBundleRemoved)
2660 CI->eraseFromParent();
2661
2662 return true;
2663}
2664
2665void DevirtIndex::run() {
2666 if (ExportSummary.typeIdCompatibleVtableMap().empty())
2667 return;
2668
2669 // Assert that we haven't made any changes that would affect the hasLocal()
2670 // flag on the GUID summary info.
2671 assert(!ExportSummary.withInternalizeAndPromote() &&
2672 "Expect index-based WPD to run before internalization and promotion");
2673
2674 DenseMap<GlobalValue::GUID, std::vector<StringRef>> NameByGUID;
2675 for (const auto &P : ExportSummary.typeIdCompatibleVtableMap()) {
2676 NameByGUID[GlobalValue::getGUIDAssumingExternalLinkage(P.first)].push_back(
2677 P.first);
2678 // Create the type id summary resolution regardlness of whether we can
2679 // devirtualize, so that lower type tests knows the type id is used on
2680 // a global and not Unsat. We do this here rather than in the loop over the
2681 // CallSlots, since that handling will only see type tests that directly
2682 // feed assumes, and we would miss any that aren't currently handled by WPD
2683 // (such as type tests that feed assumes via phis).
2684 ExportSummary.getOrInsertTypeIdSummary(P.first);
2685 }
2686
2687 // Collect information from summary about which calls to try to devirtualize.
2688 for (auto &P : ExportSummary) {
2689 for (auto &S : P.second.getSummaryList()) {
2690 auto *FS = dyn_cast<FunctionSummary>(S.get());
2691 if (!FS)
2692 continue;
2693 // FIXME: Only add live functions.
2694 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) {
2695 for (StringRef Name : NameByGUID[VF.GUID]) {
2696 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeTestAssumeUser(FS);
2697 }
2698 }
2699 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) {
2700 for (StringRef Name : NameByGUID[VF.GUID]) {
2701 CallSlots[{Name, VF.Offset}].CSInfo.addSummaryTypeCheckedLoadUser(FS);
2702 }
2703 }
2704 for (const FunctionSummary::ConstVCall &VC :
2705 FS->type_test_assume_const_vcalls()) {
2706 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2707 CallSlots[{Name, VC.VFunc.Offset}]
2708 .ConstCSInfo[VC.Args]
2709 .addSummaryTypeTestAssumeUser(FS);
2710 }
2711 }
2712 for (const FunctionSummary::ConstVCall &VC :
2713 FS->type_checked_load_const_vcalls()) {
2714 for (StringRef Name : NameByGUID[VC.VFunc.GUID]) {
2715 CallSlots[{Name, VC.VFunc.Offset}]
2716 .ConstCSInfo[VC.Args]
2717 .addSummaryTypeCheckedLoadUser(FS);
2718 }
2719 }
2720 }
2721 }
2722
2723 std::set<ValueInfo> DevirtTargets;
2724 // For each (type, offset) pair:
2725 for (auto &S : CallSlots) {
2726 // Search each of the members of the type identifier for the virtual
2727 // function implementation at offset S.first.ByteOffset, and add to
2728 // TargetsForSlot.
2729 std::vector<ValueInfo> TargetsForSlot;
2730 auto TidSummary = ExportSummary.getTypeIdCompatibleVtableSummary(S.first.TypeID);
2731 assert(TidSummary);
2732 // The type id summary would have been created while building the NameByGUID
2733 // map earlier.
2734 WholeProgramDevirtResolution *Res =
2735 &ExportSummary.getTypeIdSummary(S.first.TypeID)
2736 ->WPDRes[S.first.ByteOffset];
2737
2738 bool HasPublicTarget = true;
2739 if (tryFindVirtualCallTargets(TargetsForSlot, *TidSummary,
2740 S.first.ByteOffset, HasPublicTarget)) {
2741
2742 if (!trySingleImplDevirt(TargetsForSlot, S.first, S.second, Res,
2743 DevirtTargets, HasPublicTarget))
2744 continue;
2745 }
2746 }
2747
2748 // Optionally have the thin link print message for each devirtualized
2749 // function.
2750 if (Opts.wholeprogramdevirt_print_index_based)
2751 for (const auto &DT : DevirtTargets)
2752 errs() << "Devirtualized call to " << DT << "\n";
2753
2754 NumDevirtTargets += DevirtTargets.size();
2755}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
@ CallSiteInfo
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Provides passes for computing function attributes based on interprocedural analyses.
#define DEBUG_TYPE
static void emitRemark(const Function &F, OptimizationRemarkEmitter &ORE, bool Skip)
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
#define T
static bool mustBeUnreachableFunction(const Function &F)
This is the interface to build a ModuleSummaryIndex for a module.
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains the declarations for profiling metadata utility functions.
R600 Clause Merge
RISCVCC::CondCode CC
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
static void findAssumesThroughMergesForTypeTest(SmallVectorImpl< CallInst * > &Assumes, CallInst &TypeTest, SmallPtrSetImpl< Value * > &VisitedMerges)
Find assumes whose conditions depend on this type test through phi or select nodes.
static bool typeIDVisibleToRegularObj(StringRef TypeID, function_ref< bool(StringRef)> IsVisibleToRegularObj)
static bool addCalls(VTableSlotInfo &SlotInfo, const ValueInfo &Callee)
static bool skipUpdateDueToValidation(GlobalVariable &GV, function_ref< bool(StringRef)> IsVisibleToRegularObj)
static Error checkCombinedSummaryForTesting(const IPOOptions &Opts, ModuleSummaryIndex *Summary)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:260
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
void setCallingConv(CallingConv::ID CC)
bool arg_empty() const
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
void setCalledOperand(Value *V)
static LLVM_ABI CallBase * removeOperandBundle(CallBase *CB, uint32_t ID, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle ID removed.
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
@ ICMP_NE
not equal
Definition InstrTypes.h:762
void setSelectionKind(SelectionKind Val)
Definition Comdat.h:48
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1518
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1477
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:643
const Constant * stripPointerCasts() const
Definition Constant.h:243
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static bool shouldExecute(CounterInfo &Counter)
bool empty() const
Definition DenseMap.h:716
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Subclass of Error for the sole purpose of identifying the success path in the type system.
Definition Error.h:334
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Tagged union holding either a T or a Error.
Definition Error.h:485
Type * getParamType(unsigned i) const
Parameter type accessors.
ArrayRef< Type * > params() const
bool isVarArg() const
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
bool empty() const
Definition Function.h:853
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
bool arg_empty() const
Definition Function.h:896
const BasicBlock & front() const
Definition Function.h:854
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
arg_iterator arg_begin()
Definition Function.h:862
std::optional< uint64_t > getEntryCount() const
Get the entry count for this function.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition Function.cpp:669
size_t arg_size() const
Definition Function.h:895
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
unsigned getInstructionCount() const
Returns the number of non-debug IR instructions in this function.
Definition Function.cpp:360
static GEPNoWrapFlags inBounds()
static LLVM_ABI Expected< GlobPattern > create(StringRef Pat, std::optional< size_t > MaxSubPatterns={}, bool SlashAgnostic=false)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:695
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
LLVM_ABI VCallVisibility getVCallVisibility() const
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
LLVM_ABI void setVCallVisibilityMetadata(VCallVisibility Visibility)
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
Definition Globals.cpp:103
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
void setVisibility(VisibilityTypes V)
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Type * getValueType() const
LLVM_ABI bool isInterposable(bool CheckNoIPA=true) const
Return true if this global's definition can be substituted with an arbitrary definition at link time ...
Definition Globals.cpp:178
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
MaybeAlign getAlign() const
Returns the alignment of the given variable.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
uint64_t getBitMask() const
Return a bitmask with ones set for all of the bits that can be set by an unsigned version of this typ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
Root of the metadata hierarchy.
Definition Metadata.h:65
Class to hold module path string table and global value map, and encapsulate methods for operating on...
const TypeIdSummary * getTypeIdSummary(StringRef TypeId) const
This returns either a pointer to the type id summary (if present in the summary map) or null (if not ...
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
static constexpr const char * getRegularLTOModuleName()
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Analysis providing profile information.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:438
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
Target - Wrapper for Target specific information.
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
LLVM_ABI bool eraseMetadata(unsigned KindID)
Erase all metadata attachments with the given kind.
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:802
LLVM_ABI uint64_t findLowestOffset(ArrayRef< VirtualCallTarget > Targets, bool IsAfter, uint64_t Size)
LLVM_ABI void setAfterReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocAfter, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
LLVM_ABI void setBeforeReturnValues(MutableArrayRef< VirtualCallTarget > Targets, uint64_t AllocBefore, unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
LLVM_ABI MemoryEffects computeFunctionBodyMemoryAccess(Function &F, AAResults &AAR)
Returns the memory access properties of this copy of the function.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO, bool DevirtSpeculativelyInIndex=false)
Convert llvm.public.type.test calls to llvm.type.test when whole program visibility is available,...
PassSummaryAction
What to do with the summary when running passes that operate on it.
Definition IPO.h:35
@ Export
Export information to summary.
Definition IPO.h:38
@ Import
Import information from summary.
Definition IPO.h:37
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
@ invalid_argument
Definition Errc.h:56
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:44
LLVM_ABI void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
LLVM_ABI void getVisibleToRegularObjVtableGUIDs(ModuleSummaryIndex &Index, DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols, function_ref< bool(StringRef)> IsVisibleToRegularObj)
Based on typeID string, get all associated vtable GUIDS that are visible to regular objects.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI void findDevirtualizableCallsForTypeCheckedLoad(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< Instruction * > &LoadedPtrs, SmallVectorImpl< Instruction * > &Preds, bool &HasNonCallUses, const CallInst *CI, DominatorTree &DT)
Given a call to the intrinsic @llvm.type.checked.load, find all devirtualizable call sites based on t...
LLVM_ABI CallBase & versionCallSite(CallBase &CB, Value *Callee, MDNode *BranchWeights)
Predicate and clone the given call site.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void setExplicitlyUnknownFunctionEntryCount(Function &F, StringRef PassName)
Analogous to setExplicitlyUnknownBranchWeights, but for functions and their entry counts.
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
IntPtrTy
Definition InstrProf.h:82
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition Error.h:1261
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
LLVM_ABI bool hasWholeProgramVisibility(const cl::LibraryOptionsContext &LibraryOptions, bool WholeProgramVisibilityEnabledInLTO)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void runWholeProgramDevirtOnIndex(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr)
Perform index-based whole program devirtualization on the Summary index.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
LLVM_ABI void findDevirtualizableCallsForTypeTest(SmallVectorImpl< DevirtCallSite > &DevirtCalls, SmallVectorImpl< CallInst * > &Assumes, const CallInst *CI, DominatorTree &DT)
Given a call to the intrinsic @llvm.type.test, find all devirtualizable call sites based on the call ...
LLVM_ABI void updateVCallVisibilityInModule(Module &M, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, bool ValidateAllVtablesHaveTypeInfos, function_ref< bool(StringRef)> IsVisibleToRegularObj)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void updateVCallVisibilityInIndex(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
LLVM_ABI std::pair< Function *, Constant * > getFunctionAtVTableOffset(GlobalVariable *GV, uint64_t Offset, Module &M)
Given a vtable and a specified offset, returns the function and the trivial pointer at the specified ...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Class to accumulate and hold information about a callee.
static unsigned getHashValue(const VTableSlotSummary &I)
static bool isEqual(const VTableSlotSummary &LHS, const VTableSlotSummary &RHS)
static bool isEqual(const VTableSlot &LHS, const VTableSlot &RHS)
static unsigned getHashValue(const VTableSlot &I)
An information struct used to provide DenseMap with the various necessary components for a given valu...
The following data structures summarize type metadata information.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
enum llvm::TypeTestResolution::Kind TheKind
Struct that holds a reference to a particular GUID in a global value summary.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
const ModuleSummaryIndex * ImportSummary
ModuleSummaryIndex * ExportSummary
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.
LLVM_ABI VirtualCallTarget(GlobalValue *Fn, const TypeMemberInfo *TM)