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