1 //===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass implements whole program optimization of virtual calls in cases 11 // where we know (via !type metadata) that the list of callees is fixed. This 12 // includes the following: 13 // - Single implementation devirtualization: if a virtual call has a single 14 // possible callee, replace all calls with a direct call to that callee. 15 // - Virtual constant propagation: if the virtual function's return type is an 16 // integer <=64 bits and all possible callees are readnone, for each class and 17 // each list of constant arguments: evaluate the function, store the return 18 // value alongside the virtual table, and rewrite each virtual call as a load 19 // from the virtual table. 20 // - Uniform return value optimization: if the conditions for virtual constant 21 // propagation hold and each function returns the same constant value, replace 22 // each virtual call with that constant. 23 // - Unique return value optimization for i1 return values: if the conditions 24 // for virtual constant propagation hold and a single vtable's function 25 // returns 0, or a single vtable's function returns 1, replace each virtual 26 // call with a comparison of the vptr against that vtable's address. 27 // 28 // This pass is intended to be used during the regular and thin LTO pipelines. 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). During 33 // ThinLTO, the pass operates in two phases: 34 // - Export phase: this is run during the thin link over a single merged module 35 // that contains all vtables with !type metadata that participate in the link. 36 // The pass computes a resolution for each virtual call and stores it in the 37 // type identifier summary. 38 // - Import phase: this is run during the thin backends over the individual 39 // modules. The pass applies the resolutions previously computed during the 40 // import phase to each eligible virtual call. 41 // 42 //===----------------------------------------------------------------------===// 43 44 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 45 #include "llvm/ADT/ArrayRef.h" 46 #include "llvm/ADT/DenseMap.h" 47 #include "llvm/ADT/DenseMapInfo.h" 48 #include "llvm/ADT/DenseSet.h" 49 #include "llvm/ADT/iterator_range.h" 50 #include "llvm/ADT/MapVector.h" 51 #include "llvm/ADT/SmallVector.h" 52 #include "llvm/Analysis/AliasAnalysis.h" 53 #include "llvm/Analysis/BasicAliasAnalysis.h" 54 #include "llvm/Analysis/TypeMetadataUtils.h" 55 #include "llvm/IR/CallSite.h" 56 #include "llvm/IR/Constants.h" 57 #include "llvm/IR/DataLayout.h" 58 #include "llvm/IR/DebugInfoMetadata.h" 59 #include "llvm/IR/DebugLoc.h" 60 #include "llvm/IR/DerivedTypes.h" 61 #include "llvm/IR/DiagnosticInfo.h" 62 #include "llvm/IR/Function.h" 63 #include "llvm/IR/GlobalAlias.h" 64 #include "llvm/IR/GlobalVariable.h" 65 #include "llvm/IR/IRBuilder.h" 66 #include "llvm/IR/InstrTypes.h" 67 #include "llvm/IR/Instruction.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/Intrinsics.h" 70 #include "llvm/IR/LLVMContext.h" 71 #include "llvm/IR/Metadata.h" 72 #include "llvm/IR/Module.h" 73 #include "llvm/IR/ModuleSummaryIndexYAML.h" 74 #include "llvm/Pass.h" 75 #include "llvm/PassRegistry.h" 76 #include "llvm/PassSupport.h" 77 #include "llvm/Support/Casting.h" 78 #include "llvm/Support/Error.h" 79 #include "llvm/Support/FileSystem.h" 80 #include "llvm/Support/MathExtras.h" 81 #include "llvm/Transforms/IPO.h" 82 #include "llvm/Transforms/IPO/FunctionAttrs.h" 83 #include "llvm/Transforms/Utils/Evaluator.h" 84 #include <algorithm> 85 #include <cstddef> 86 #include <map> 87 #include <set> 88 #include <string> 89 90 using namespace llvm; 91 using namespace wholeprogramdevirt; 92 93 #define DEBUG_TYPE "wholeprogramdevirt" 94 95 static cl::opt<PassSummaryAction> ClSummaryAction( 96 "wholeprogramdevirt-summary-action", 97 cl::desc("What to do with the summary when running this pass"), 98 cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"), 99 clEnumValN(PassSummaryAction::Import, "import", 100 "Import typeid resolutions from summary and globals"), 101 clEnumValN(PassSummaryAction::Export, "export", 102 "Export typeid resolutions to summary and globals")), 103 cl::Hidden); 104 105 static cl::opt<std::string> ClReadSummary( 106 "wholeprogramdevirt-read-summary", 107 cl::desc("Read summary from given YAML file before running pass"), 108 cl::Hidden); 109 110 static cl::opt<std::string> ClWriteSummary( 111 "wholeprogramdevirt-write-summary", 112 cl::desc("Write summary to given YAML file after running pass"), 113 cl::Hidden); 114 115 // Find the minimum offset that we may store a value of size Size bits at. If 116 // IsAfter is set, look for an offset before the object, otherwise look for an 117 // offset after the object. 118 uint64_t 119 wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, 120 bool IsAfter, uint64_t Size) { 121 // Find a minimum offset taking into account only vtable sizes. 122 uint64_t MinByte = 0; 123 for (const VirtualCallTarget &Target : Targets) { 124 if (IsAfter) 125 MinByte = std::max(MinByte, Target.minAfterBytes()); 126 else 127 MinByte = std::max(MinByte, Target.minBeforeBytes()); 128 } 129 130 // Build a vector of arrays of bytes covering, for each target, a slice of the 131 // used region (see AccumBitVector::BytesUsed in 132 // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, 133 // this aligns the used regions to start at MinByte. 134 // 135 // In this example, A, B and C are vtables, # is a byte already allocated for 136 // a virtual function pointer, AAAA... (etc.) are the used regions for the 137 // vtables and Offset(X) is the value computed for the Offset variable below 138 // for X. 139 // 140 // Offset(A) 141 // | | 142 // |MinByte 143 // A: ################AAAAAAAA|AAAAAAAA 144 // B: ########BBBBBBBBBBBBBBBB|BBBB 145 // C: ########################|CCCCCCCCCCCCCCCC 146 // | Offset(B) | 147 // 148 // This code produces the slices of A, B and C that appear after the divider 149 // at MinByte. 150 std::vector<ArrayRef<uint8_t>> Used; 151 for (const VirtualCallTarget &Target : Targets) { 152 ArrayRef<uint8_t> VTUsed = IsAfter ? Target.TM->Bits->After.BytesUsed 153 : Target.TM->Bits->Before.BytesUsed; 154 uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() 155 : MinByte - Target.minBeforeBytes(); 156 157 // Disregard used regions that are smaller than Offset. These are 158 // effectively all-free regions that do not need to be checked. 159 if (VTUsed.size() > Offset) 160 Used.push_back(VTUsed.slice(Offset)); 161 } 162 163 if (Size == 1) { 164 // Find a free bit in each member of Used. 165 for (unsigned I = 0;; ++I) { 166 uint8_t BitsUsed = 0; 167 for (auto &&B : Used) 168 if (I < B.size()) 169 BitsUsed |= B[I]; 170 if (BitsUsed != 0xff) 171 return (MinByte + I) * 8 + 172 countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); 173 } 174 } else { 175 // Find a free (Size/8) byte region in each member of Used. 176 // FIXME: see if alignment helps. 177 for (unsigned I = 0;; ++I) { 178 for (auto &&B : Used) { 179 unsigned Byte = 0; 180 while ((I + Byte) < B.size() && Byte < (Size / 8)) { 181 if (B[I + Byte]) 182 goto NextI; 183 ++Byte; 184 } 185 } 186 return (MinByte + I) * 8; 187 NextI:; 188 } 189 } 190 } 191 192 void wholeprogramdevirt::setBeforeReturnValues( 193 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, 194 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { 195 if (BitWidth == 1) 196 OffsetByte = -(AllocBefore / 8 + 1); 197 else 198 OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); 199 OffsetBit = AllocBefore % 8; 200 201 for (VirtualCallTarget &Target : Targets) { 202 if (BitWidth == 1) 203 Target.setBeforeBit(AllocBefore); 204 else 205 Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); 206 } 207 } 208 209 void wholeprogramdevirt::setAfterReturnValues( 210 MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, 211 unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { 212 if (BitWidth == 1) 213 OffsetByte = AllocAfter / 8; 214 else 215 OffsetByte = (AllocAfter + 7) / 8; 216 OffsetBit = AllocAfter % 8; 217 218 for (VirtualCallTarget &Target : Targets) { 219 if (BitWidth == 1) 220 Target.setAfterBit(AllocAfter); 221 else 222 Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); 223 } 224 } 225 226 VirtualCallTarget::VirtualCallTarget(Function *Fn, const TypeMemberInfo *TM) 227 : Fn(Fn), TM(TM), 228 IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()), WasDevirt(false) {} 229 230 namespace { 231 232 // A slot in a set of virtual tables. The TypeID identifies the set of virtual 233 // tables, and the ByteOffset is the offset in bytes from the address point to 234 // the virtual function pointer. 235 struct VTableSlot { 236 Metadata *TypeID; 237 uint64_t ByteOffset; 238 }; 239 240 } // end anonymous namespace 241 242 namespace llvm { 243 244 template <> struct DenseMapInfo<VTableSlot> { 245 static VTableSlot getEmptyKey() { 246 return {DenseMapInfo<Metadata *>::getEmptyKey(), 247 DenseMapInfo<uint64_t>::getEmptyKey()}; 248 } 249 static VTableSlot getTombstoneKey() { 250 return {DenseMapInfo<Metadata *>::getTombstoneKey(), 251 DenseMapInfo<uint64_t>::getTombstoneKey()}; 252 } 253 static unsigned getHashValue(const VTableSlot &I) { 254 return DenseMapInfo<Metadata *>::getHashValue(I.TypeID) ^ 255 DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); 256 } 257 static bool isEqual(const VTableSlot &LHS, 258 const VTableSlot &RHS) { 259 return LHS.TypeID == RHS.TypeID && LHS.ByteOffset == RHS.ByteOffset; 260 } 261 }; 262 263 } // end namespace llvm 264 265 namespace { 266 267 // A virtual call site. VTable is the loaded virtual table pointer, and CS is 268 // the indirect virtual call. 269 struct VirtualCallSite { 270 Value *VTable; 271 CallSite CS; 272 273 // If non-null, this field points to the associated unsafe use count stored in 274 // the DevirtModule::NumUnsafeUsesForTypeTest map below. See the description 275 // of that field for details. 276 unsigned *NumUnsafeUses; 277 278 void emitRemark(const Twine &OptName, const Twine &TargetName) { 279 Function *F = CS.getCaller(); 280 emitOptimizationRemark( 281 F->getContext(), DEBUG_TYPE, *F, 282 CS.getInstruction()->getDebugLoc(), 283 OptName + ": devirtualized a call to " + TargetName); 284 } 285 286 void replaceAndErase(const Twine &OptName, const Twine &TargetName, 287 bool RemarksEnabled, Value *New) { 288 if (RemarksEnabled) 289 emitRemark(OptName, TargetName); 290 CS->replaceAllUsesWith(New); 291 if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) { 292 BranchInst::Create(II->getNormalDest(), CS.getInstruction()); 293 II->getUnwindDest()->removePredecessor(II->getParent()); 294 } 295 CS->eraseFromParent(); 296 // This use is no longer unsafe. 297 if (NumUnsafeUses) 298 --*NumUnsafeUses; 299 } 300 }; 301 302 // Call site information collected for a specific VTableSlot and possibly a list 303 // of constant integer arguments. The grouping by arguments is handled by the 304 // VTableSlotInfo class. 305 struct CallSiteInfo { 306 /// The set of call sites for this slot. Used during regular LTO and the 307 /// import phase of ThinLTO (as well as the export phase of ThinLTO for any 308 /// call sites that appear in the merged module itself); in each of these 309 /// cases we are directly operating on the call sites at the IR level. 310 std::vector<VirtualCallSite> CallSites; 311 312 // These fields are used during the export phase of ThinLTO and reflect 313 // information collected from function summaries. 314 315 /// Whether any function summary contains an llvm.assume(llvm.type.test) for 316 /// this slot. 317 bool SummaryHasTypeTestAssumeUsers; 318 319 /// CFI-specific: a vector containing the list of function summaries that use 320 /// the llvm.type.checked.load intrinsic and therefore will require 321 /// resolutions for llvm.type.test in order to implement CFI checks if 322 /// devirtualization was unsuccessful. If devirtualization was successful, the 323 /// pass will clear this vector by calling markDevirt(). If at the end of the 324 /// pass the vector is non-empty, we will need to add a use of llvm.type.test 325 /// to each of the function summaries in the vector. 326 std::vector<FunctionSummary *> SummaryTypeCheckedLoadUsers; 327 328 bool isExported() const { 329 return SummaryHasTypeTestAssumeUsers || 330 !SummaryTypeCheckedLoadUsers.empty(); 331 } 332 333 /// As explained in the comment for SummaryTypeCheckedLoadUsers. 334 void markDevirt() { SummaryTypeCheckedLoadUsers.clear(); } 335 }; 336 337 // Call site information collected for a specific VTableSlot. 338 struct VTableSlotInfo { 339 // The set of call sites which do not have all constant integer arguments 340 // (excluding "this"). 341 CallSiteInfo CSInfo; 342 343 // The set of call sites with all constant integer arguments (excluding 344 // "this"), grouped by argument list. 345 std::map<std::vector<uint64_t>, CallSiteInfo> ConstCSInfo; 346 347 void addCallSite(Value *VTable, CallSite CS, unsigned *NumUnsafeUses); 348 349 private: 350 CallSiteInfo &findCallSiteInfo(CallSite CS); 351 }; 352 353 CallSiteInfo &VTableSlotInfo::findCallSiteInfo(CallSite CS) { 354 std::vector<uint64_t> Args; 355 auto *CI = dyn_cast<IntegerType>(CS.getType()); 356 if (!CI || CI->getBitWidth() > 64 || CS.arg_empty()) 357 return CSInfo; 358 for (auto &&Arg : make_range(CS.arg_begin() + 1, CS.arg_end())) { 359 auto *CI = dyn_cast<ConstantInt>(Arg); 360 if (!CI || CI->getBitWidth() > 64) 361 return CSInfo; 362 Args.push_back(CI->getZExtValue()); 363 } 364 return ConstCSInfo[Args]; 365 } 366 367 void VTableSlotInfo::addCallSite(Value *VTable, CallSite CS, 368 unsigned *NumUnsafeUses) { 369 findCallSiteInfo(CS).CallSites.push_back({VTable, CS, NumUnsafeUses}); 370 } 371 372 struct DevirtModule { 373 Module &M; 374 function_ref<AAResults &(Function &)> AARGetter; 375 376 PassSummaryAction Action; 377 ModuleSummaryIndex *Summary; 378 379 IntegerType *Int8Ty; 380 PointerType *Int8PtrTy; 381 IntegerType *Int32Ty; 382 IntegerType *Int64Ty; 383 IntegerType *IntPtrTy; 384 385 bool RemarksEnabled; 386 387 MapVector<VTableSlot, VTableSlotInfo> CallSlots; 388 389 // This map keeps track of the number of "unsafe" uses of a loaded function 390 // pointer. The key is the associated llvm.type.test intrinsic call generated 391 // by this pass. An unsafe use is one that calls the loaded function pointer 392 // directly. Every time we eliminate an unsafe use (for example, by 393 // devirtualizing it or by applying virtual constant propagation), we 394 // decrement the value stored in this map. If a value reaches zero, we can 395 // eliminate the type check by RAUWing the associated llvm.type.test call with 396 // true. 397 std::map<CallInst *, unsigned> NumUnsafeUsesForTypeTest; 398 399 DevirtModule(Module &M, function_ref<AAResults &(Function &)> AARGetter, 400 PassSummaryAction Action, ModuleSummaryIndex *Summary) 401 : M(M), AARGetter(AARGetter), Action(Action), Summary(Summary), 402 Int8Ty(Type::getInt8Ty(M.getContext())), 403 Int8PtrTy(Type::getInt8PtrTy(M.getContext())), 404 Int32Ty(Type::getInt32Ty(M.getContext())), 405 Int64Ty(Type::getInt64Ty(M.getContext())), 406 IntPtrTy(M.getDataLayout().getIntPtrType(M.getContext(), 0)), 407 RemarksEnabled(areRemarksEnabled()) {} 408 409 bool areRemarksEnabled(); 410 411 void scanTypeTestUsers(Function *TypeTestFunc, Function *AssumeFunc); 412 void scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc); 413 414 void buildTypeIdentifierMap( 415 std::vector<VTableBits> &Bits, 416 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap); 417 Constant *getPointerAtOffset(Constant *I, uint64_t Offset); 418 bool 419 tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, 420 const std::set<TypeMemberInfo> &TypeMemberInfos, 421 uint64_t ByteOffset); 422 423 void applySingleImplDevirt(VTableSlotInfo &SlotInfo, Constant *TheFn, 424 bool &IsExported); 425 bool trySingleImplDevirt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 426 VTableSlotInfo &SlotInfo, 427 WholeProgramDevirtResolution *Res); 428 429 bool tryEvaluateFunctionsWithArgs( 430 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 431 ArrayRef<uint64_t> Args); 432 433 void applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 434 uint64_t TheRetVal); 435 bool tryUniformRetValOpt(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 436 CallSiteInfo &CSInfo, 437 WholeProgramDevirtResolution::ByArg *Res); 438 439 // Returns the global symbol name that is used to export information about the 440 // given vtable slot and list of arguments. 441 std::string getGlobalName(VTableSlot Slot, ArrayRef<uint64_t> Args, 442 StringRef Name); 443 444 // This function is called during the export phase to create a symbol 445 // definition containing information about the given vtable slot and list of 446 // arguments. 447 void exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, StringRef Name, 448 Constant *C); 449 450 // This function is called during the import phase to create a reference to 451 // the symbol definition created during the export phase. 452 Constant *importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 453 StringRef Name, unsigned AbsWidth = 0); 454 455 void applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, bool IsOne, 456 Constant *UniqueMemberAddr); 457 bool tryUniqueRetValOpt(unsigned BitWidth, 458 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 459 CallSiteInfo &CSInfo, 460 WholeProgramDevirtResolution::ByArg *Res, 461 VTableSlot Slot, ArrayRef<uint64_t> Args); 462 463 void applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, 464 Constant *Byte, Constant *Bit); 465 bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, 466 VTableSlotInfo &SlotInfo, 467 WholeProgramDevirtResolution *Res, VTableSlot Slot); 468 469 void rebuildGlobal(VTableBits &B); 470 471 // Apply the summary resolution for Slot to all virtual calls in SlotInfo. 472 void importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo); 473 474 // If we were able to eliminate all unsafe uses for a type checked load, 475 // eliminate the associated type tests by replacing them with true. 476 void removeRedundantTypeTests(); 477 478 bool run(); 479 480 // Lower the module using the action and summary passed as command line 481 // arguments. For testing purposes only. 482 static bool runForTesting(Module &M, 483 function_ref<AAResults &(Function &)> AARGetter); 484 }; 485 486 struct WholeProgramDevirt : public ModulePass { 487 static char ID; 488 489 bool UseCommandLine = false; 490 491 PassSummaryAction Action; 492 ModuleSummaryIndex *Summary; 493 494 WholeProgramDevirt() : ModulePass(ID), UseCommandLine(true) { 495 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); 496 } 497 498 WholeProgramDevirt(PassSummaryAction Action, ModuleSummaryIndex *Summary) 499 : ModulePass(ID), Action(Action), Summary(Summary) { 500 initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); 501 } 502 503 bool runOnModule(Module &M) override { 504 if (skipModule(M)) 505 return false; 506 if (UseCommandLine) 507 return DevirtModule::runForTesting(M, LegacyAARGetter(*this)); 508 return DevirtModule(M, LegacyAARGetter(*this), Action, Summary).run(); 509 } 510 511 void getAnalysisUsage(AnalysisUsage &AU) const override { 512 AU.addRequired<AssumptionCacheTracker>(); 513 AU.addRequired<TargetLibraryInfoWrapperPass>(); 514 } 515 }; 516 517 } // end anonymous namespace 518 519 INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", 520 "Whole program devirtualization", false, false) 521 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 522 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 523 INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt", 524 "Whole program devirtualization", false, false) 525 char WholeProgramDevirt::ID = 0; 526 527 ModulePass *llvm::createWholeProgramDevirtPass(PassSummaryAction Action, 528 ModuleSummaryIndex *Summary) { 529 return new WholeProgramDevirt(Action, Summary); 530 } 531 532 PreservedAnalyses WholeProgramDevirtPass::run(Module &M, 533 ModuleAnalysisManager &AM) { 534 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 535 auto AARGetter = [&](Function &F) -> AAResults & { 536 return FAM.getResult<AAManager>(F); 537 }; 538 if (!DevirtModule(M, AARGetter, PassSummaryAction::None, nullptr).run()) 539 return PreservedAnalyses::all(); 540 return PreservedAnalyses::none(); 541 } 542 543 bool DevirtModule::runForTesting( 544 Module &M, function_ref<AAResults &(Function &)> AARGetter) { 545 ModuleSummaryIndex Summary; 546 547 // Handle the command-line summary arguments. This code is for testing 548 // purposes only, so we handle errors directly. 549 if (!ClReadSummary.empty()) { 550 ExitOnError ExitOnErr("-wholeprogramdevirt-read-summary: " + ClReadSummary + 551 ": "); 552 auto ReadSummaryFile = 553 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(ClReadSummary))); 554 555 yaml::Input In(ReadSummaryFile->getBuffer()); 556 In >> Summary; 557 ExitOnErr(errorCodeToError(In.error())); 558 } 559 560 bool Changed = DevirtModule(M, AARGetter, ClSummaryAction, &Summary).run(); 561 562 if (!ClWriteSummary.empty()) { 563 ExitOnError ExitOnErr( 564 "-wholeprogramdevirt-write-summary: " + ClWriteSummary + ": "); 565 std::error_code EC; 566 raw_fd_ostream OS(ClWriteSummary, EC, sys::fs::F_Text); 567 ExitOnErr(errorCodeToError(EC)); 568 569 yaml::Output Out(OS); 570 Out << Summary; 571 } 572 573 return Changed; 574 } 575 576 void DevirtModule::buildTypeIdentifierMap( 577 std::vector<VTableBits> &Bits, 578 DenseMap<Metadata *, std::set<TypeMemberInfo>> &TypeIdMap) { 579 DenseMap<GlobalVariable *, VTableBits *> GVToBits; 580 Bits.reserve(M.getGlobalList().size()); 581 SmallVector<MDNode *, 2> Types; 582 for (GlobalVariable &GV : M.globals()) { 583 Types.clear(); 584 GV.getMetadata(LLVMContext::MD_type, Types); 585 if (Types.empty()) 586 continue; 587 588 VTableBits *&BitsPtr = GVToBits[&GV]; 589 if (!BitsPtr) { 590 Bits.emplace_back(); 591 Bits.back().GV = &GV; 592 Bits.back().ObjectSize = 593 M.getDataLayout().getTypeAllocSize(GV.getInitializer()->getType()); 594 BitsPtr = &Bits.back(); 595 } 596 597 for (MDNode *Type : Types) { 598 auto TypeID = Type->getOperand(1).get(); 599 600 uint64_t Offset = 601 cast<ConstantInt>( 602 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue()) 603 ->getZExtValue(); 604 605 TypeIdMap[TypeID].insert({BitsPtr, Offset}); 606 } 607 } 608 } 609 610 Constant *DevirtModule::getPointerAtOffset(Constant *I, uint64_t Offset) { 611 if (I->getType()->isPointerTy()) { 612 if (Offset == 0) 613 return I; 614 return nullptr; 615 } 616 617 const DataLayout &DL = M.getDataLayout(); 618 619 if (auto *C = dyn_cast<ConstantStruct>(I)) { 620 const StructLayout *SL = DL.getStructLayout(C->getType()); 621 if (Offset >= SL->getSizeInBytes()) 622 return nullptr; 623 624 unsigned Op = SL->getElementContainingOffset(Offset); 625 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), 626 Offset - SL->getElementOffset(Op)); 627 } 628 if (auto *C = dyn_cast<ConstantArray>(I)) { 629 ArrayType *VTableTy = C->getType(); 630 uint64_t ElemSize = DL.getTypeAllocSize(VTableTy->getElementType()); 631 632 unsigned Op = Offset / ElemSize; 633 if (Op >= C->getNumOperands()) 634 return nullptr; 635 636 return getPointerAtOffset(cast<Constant>(I->getOperand(Op)), 637 Offset % ElemSize); 638 } 639 return nullptr; 640 } 641 642 bool DevirtModule::tryFindVirtualCallTargets( 643 std::vector<VirtualCallTarget> &TargetsForSlot, 644 const std::set<TypeMemberInfo> &TypeMemberInfos, uint64_t ByteOffset) { 645 for (const TypeMemberInfo &TM : TypeMemberInfos) { 646 if (!TM.Bits->GV->isConstant()) 647 return false; 648 649 Constant *Ptr = getPointerAtOffset(TM.Bits->GV->getInitializer(), 650 TM.Offset + ByteOffset); 651 if (!Ptr) 652 return false; 653 654 auto Fn = dyn_cast<Function>(Ptr->stripPointerCasts()); 655 if (!Fn) 656 return false; 657 658 // We can disregard __cxa_pure_virtual as a possible call target, as 659 // calls to pure virtuals are UB. 660 if (Fn->getName() == "__cxa_pure_virtual") 661 continue; 662 663 TargetsForSlot.push_back({Fn, &TM}); 664 } 665 666 // Give up if we couldn't find any targets. 667 return !TargetsForSlot.empty(); 668 } 669 670 void DevirtModule::applySingleImplDevirt(VTableSlotInfo &SlotInfo, 671 Constant *TheFn, bool &IsExported) { 672 auto Apply = [&](CallSiteInfo &CSInfo) { 673 for (auto &&VCallSite : CSInfo.CallSites) { 674 if (RemarksEnabled) 675 VCallSite.emitRemark("single-impl", TheFn->getName()); 676 VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( 677 TheFn, VCallSite.CS.getCalledValue()->getType())); 678 // This use is no longer unsafe. 679 if (VCallSite.NumUnsafeUses) 680 --*VCallSite.NumUnsafeUses; 681 } 682 if (CSInfo.isExported()) { 683 IsExported = true; 684 CSInfo.markDevirt(); 685 } 686 }; 687 Apply(SlotInfo.CSInfo); 688 for (auto &P : SlotInfo.ConstCSInfo) 689 Apply(P.second); 690 } 691 692 bool DevirtModule::trySingleImplDevirt( 693 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 694 VTableSlotInfo &SlotInfo, WholeProgramDevirtResolution *Res) { 695 // See if the program contains a single implementation of this virtual 696 // function. 697 Function *TheFn = TargetsForSlot[0].Fn; 698 for (auto &&Target : TargetsForSlot) 699 if (TheFn != Target.Fn) 700 return false; 701 702 // If so, update each call site to call that implementation directly. 703 if (RemarksEnabled) 704 TargetsForSlot[0].WasDevirt = true; 705 706 bool IsExported = false; 707 applySingleImplDevirt(SlotInfo, TheFn, IsExported); 708 if (!IsExported) 709 return false; 710 711 // If the only implementation has local linkage, we must promote to external 712 // to make it visible to thin LTO objects. We can only get here during the 713 // ThinLTO export phase. 714 if (TheFn->hasLocalLinkage()) { 715 TheFn->setLinkage(GlobalValue::ExternalLinkage); 716 TheFn->setVisibility(GlobalValue::HiddenVisibility); 717 TheFn->setName(TheFn->getName() + "$merged"); 718 } 719 720 Res->TheKind = WholeProgramDevirtResolution::SingleImpl; 721 Res->SingleImplName = TheFn->getName(); 722 723 return true; 724 } 725 726 bool DevirtModule::tryEvaluateFunctionsWithArgs( 727 MutableArrayRef<VirtualCallTarget> TargetsForSlot, 728 ArrayRef<uint64_t> Args) { 729 // Evaluate each function and store the result in each target's RetVal 730 // field. 731 for (VirtualCallTarget &Target : TargetsForSlot) { 732 if (Target.Fn->arg_size() != Args.size() + 1) 733 return false; 734 735 Evaluator Eval(M.getDataLayout(), nullptr); 736 SmallVector<Constant *, 2> EvalArgs; 737 EvalArgs.push_back( 738 Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); 739 for (unsigned I = 0; I != Args.size(); ++I) { 740 auto *ArgTy = dyn_cast<IntegerType>( 741 Target.Fn->getFunctionType()->getParamType(I + 1)); 742 if (!ArgTy) 743 return false; 744 EvalArgs.push_back(ConstantInt::get(ArgTy, Args[I])); 745 } 746 747 Constant *RetVal; 748 if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || 749 !isa<ConstantInt>(RetVal)) 750 return false; 751 Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); 752 } 753 return true; 754 } 755 756 void DevirtModule::applyUniformRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 757 uint64_t TheRetVal) { 758 for (auto Call : CSInfo.CallSites) 759 Call.replaceAndErase( 760 "uniform-ret-val", FnName, RemarksEnabled, 761 ConstantInt::get(cast<IntegerType>(Call.CS.getType()), TheRetVal)); 762 CSInfo.markDevirt(); 763 } 764 765 bool DevirtModule::tryUniformRetValOpt( 766 MutableArrayRef<VirtualCallTarget> TargetsForSlot, CallSiteInfo &CSInfo, 767 WholeProgramDevirtResolution::ByArg *Res) { 768 // Uniform return value optimization. If all functions return the same 769 // constant, replace all calls with that constant. 770 uint64_t TheRetVal = TargetsForSlot[0].RetVal; 771 for (const VirtualCallTarget &Target : TargetsForSlot) 772 if (Target.RetVal != TheRetVal) 773 return false; 774 775 if (CSInfo.isExported()) { 776 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal; 777 Res->Info = TheRetVal; 778 } 779 780 applyUniformRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), TheRetVal); 781 if (RemarksEnabled) 782 for (auto &&Target : TargetsForSlot) 783 Target.WasDevirt = true; 784 return true; 785 } 786 787 std::string DevirtModule::getGlobalName(VTableSlot Slot, 788 ArrayRef<uint64_t> Args, 789 StringRef Name) { 790 std::string FullName = "__typeid_"; 791 raw_string_ostream OS(FullName); 792 OS << cast<MDString>(Slot.TypeID)->getString() << '_' << Slot.ByteOffset; 793 for (uint64_t Arg : Args) 794 OS << '_' << Arg; 795 OS << '_' << Name; 796 return OS.str(); 797 } 798 799 void DevirtModule::exportGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 800 StringRef Name, Constant *C) { 801 GlobalAlias *GA = GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage, 802 getGlobalName(Slot, Args, Name), C, &M); 803 GA->setVisibility(GlobalValue::HiddenVisibility); 804 } 805 806 Constant *DevirtModule::importGlobal(VTableSlot Slot, ArrayRef<uint64_t> Args, 807 StringRef Name, unsigned AbsWidth) { 808 Constant *C = M.getOrInsertGlobal(getGlobalName(Slot, Args, Name), Int8Ty); 809 auto *GV = dyn_cast<GlobalVariable>(C); 810 // We only need to set metadata if the global is newly created, in which 811 // case it would not have hidden visibility. 812 if (!GV || GV->getVisibility() == GlobalValue::HiddenVisibility) 813 return C; 814 815 GV->setVisibility(GlobalValue::HiddenVisibility); 816 auto SetAbsRange = [&](uint64_t Min, uint64_t Max) { 817 auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min)); 818 auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max)); 819 GV->setMetadata(LLVMContext::MD_absolute_symbol, 820 MDNode::get(M.getContext(), {MinC, MaxC})); 821 }; 822 if (AbsWidth == IntPtrTy->getBitWidth()) 823 SetAbsRange(~0ull, ~0ull); // Full set. 824 else if (AbsWidth) 825 SetAbsRange(0, 1ull << AbsWidth); 826 return GV; 827 } 828 829 void DevirtModule::applyUniqueRetValOpt(CallSiteInfo &CSInfo, StringRef FnName, 830 bool IsOne, 831 Constant *UniqueMemberAddr) { 832 for (auto &&Call : CSInfo.CallSites) { 833 IRBuilder<> B(Call.CS.getInstruction()); 834 Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, 835 Call.VTable, UniqueMemberAddr); 836 Cmp = B.CreateZExt(Cmp, Call.CS->getType()); 837 Call.replaceAndErase("unique-ret-val", FnName, RemarksEnabled, Cmp); 838 } 839 CSInfo.markDevirt(); 840 } 841 842 bool DevirtModule::tryUniqueRetValOpt( 843 unsigned BitWidth, MutableArrayRef<VirtualCallTarget> TargetsForSlot, 844 CallSiteInfo &CSInfo, WholeProgramDevirtResolution::ByArg *Res, 845 VTableSlot Slot, ArrayRef<uint64_t> Args) { 846 // IsOne controls whether we look for a 0 or a 1. 847 auto tryUniqueRetValOptFor = [&](bool IsOne) { 848 const TypeMemberInfo *UniqueMember = nullptr; 849 for (const VirtualCallTarget &Target : TargetsForSlot) { 850 if (Target.RetVal == (IsOne ? 1 : 0)) { 851 if (UniqueMember) 852 return false; 853 UniqueMember = Target.TM; 854 } 855 } 856 857 // We should have found a unique member or bailed out by now. We already 858 // checked for a uniform return value in tryUniformRetValOpt. 859 assert(UniqueMember); 860 861 Constant *UniqueMemberAddr = 862 ConstantExpr::getBitCast(UniqueMember->Bits->GV, Int8PtrTy); 863 UniqueMemberAddr = ConstantExpr::getGetElementPtr( 864 Int8Ty, UniqueMemberAddr, 865 ConstantInt::get(Int64Ty, UniqueMember->Offset)); 866 867 if (CSInfo.isExported()) { 868 Res->TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal; 869 Res->Info = IsOne; 870 871 exportGlobal(Slot, Args, "unique_member", UniqueMemberAddr); 872 } 873 874 // Replace each call with the comparison. 875 applyUniqueRetValOpt(CSInfo, TargetsForSlot[0].Fn->getName(), IsOne, 876 UniqueMemberAddr); 877 878 // Update devirtualization statistics for targets. 879 if (RemarksEnabled) 880 for (auto &&Target : TargetsForSlot) 881 Target.WasDevirt = true; 882 883 return true; 884 }; 885 886 if (BitWidth == 1) { 887 if (tryUniqueRetValOptFor(true)) 888 return true; 889 if (tryUniqueRetValOptFor(false)) 890 return true; 891 } 892 return false; 893 } 894 895 void DevirtModule::applyVirtualConstProp(CallSiteInfo &CSInfo, StringRef FnName, 896 Constant *Byte, Constant *Bit) { 897 for (auto Call : CSInfo.CallSites) { 898 auto *RetType = cast<IntegerType>(Call.CS.getType()); 899 IRBuilder<> B(Call.CS.getInstruction()); 900 Value *Addr = B.CreateGEP(Int8Ty, Call.VTable, Byte); 901 if (RetType->getBitWidth() == 1) { 902 Value *Bits = B.CreateLoad(Addr); 903 Value *BitsAndBit = B.CreateAnd(Bits, Bit); 904 auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); 905 Call.replaceAndErase("virtual-const-prop-1-bit", FnName, RemarksEnabled, 906 IsBitSet); 907 } else { 908 Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); 909 Value *Val = B.CreateLoad(RetType, ValAddr); 910 Call.replaceAndErase("virtual-const-prop", FnName, RemarksEnabled, Val); 911 } 912 } 913 CSInfo.markDevirt(); 914 } 915 916 bool DevirtModule::tryVirtualConstProp( 917 MutableArrayRef<VirtualCallTarget> TargetsForSlot, VTableSlotInfo &SlotInfo, 918 WholeProgramDevirtResolution *Res, VTableSlot Slot) { 919 // This only works if the function returns an integer. 920 auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); 921 if (!RetType) 922 return false; 923 unsigned BitWidth = RetType->getBitWidth(); 924 if (BitWidth > 64) 925 return false; 926 927 // Make sure that each function is defined, does not access memory, takes at 928 // least one argument, does not use its first argument (which we assume is 929 // 'this'), and has the same return type. 930 // 931 // Note that we test whether this copy of the function is readnone, rather 932 // than testing function attributes, which must hold for any copy of the 933 // function, even a less optimized version substituted at link time. This is 934 // sound because the virtual constant propagation optimizations effectively 935 // inline all implementations of the virtual function into each call site, 936 // rather than using function attributes to perform local optimization. 937 for (VirtualCallTarget &Target : TargetsForSlot) { 938 if (Target.Fn->isDeclaration() || 939 computeFunctionBodyMemoryAccess(*Target.Fn, AARGetter(*Target.Fn)) != 940 MAK_ReadNone || 941 Target.Fn->arg_empty() || !Target.Fn->arg_begin()->use_empty() || 942 Target.Fn->getReturnType() != RetType) 943 return false; 944 } 945 946 for (auto &&CSByConstantArg : SlotInfo.ConstCSInfo) { 947 if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) 948 continue; 949 950 WholeProgramDevirtResolution::ByArg *ResByArg = nullptr; 951 if (Res) 952 ResByArg = &Res->ResByArg[CSByConstantArg.first]; 953 954 if (tryUniformRetValOpt(TargetsForSlot, CSByConstantArg.second, ResByArg)) 955 continue; 956 957 if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second, 958 ResByArg, Slot, CSByConstantArg.first)) 959 continue; 960 961 // Find an allocation offset in bits in all vtables associated with the 962 // type. 963 uint64_t AllocBefore = 964 findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); 965 uint64_t AllocAfter = 966 findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); 967 968 // Calculate the total amount of padding needed to store a value at both 969 // ends of the object. 970 uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; 971 for (auto &&Target : TargetsForSlot) { 972 TotalPaddingBefore += std::max<int64_t>( 973 (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); 974 TotalPaddingAfter += std::max<int64_t>( 975 (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); 976 } 977 978 // If the amount of padding is too large, give up. 979 // FIXME: do something smarter here. 980 if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) 981 continue; 982 983 // Calculate the offset to the value as a (possibly negative) byte offset 984 // and (if applicable) a bit offset, and store the values in the targets. 985 int64_t OffsetByte; 986 uint64_t OffsetBit; 987 if (TotalPaddingBefore <= TotalPaddingAfter) 988 setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, 989 OffsetBit); 990 else 991 setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, 992 OffsetBit); 993 994 if (RemarksEnabled) 995 for (auto &&Target : TargetsForSlot) 996 Target.WasDevirt = true; 997 998 Constant *ByteConst = ConstantInt::get(Int32Ty, OffsetByte); 999 Constant *BitConst = ConstantInt::get(Int8Ty, 1ULL << OffsetBit); 1000 1001 if (CSByConstantArg.second.isExported()) { 1002 ResByArg->TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp; 1003 exportGlobal(Slot, CSByConstantArg.first, "byte", 1004 ConstantExpr::getIntToPtr(ByteConst, Int8PtrTy)); 1005 exportGlobal(Slot, CSByConstantArg.first, "bit", 1006 ConstantExpr::getIntToPtr(BitConst, Int8PtrTy)); 1007 } 1008 1009 // Rewrite each call to a load from OffsetByte/OffsetBit. 1010 applyVirtualConstProp(CSByConstantArg.second, 1011 TargetsForSlot[0].Fn->getName(), ByteConst, BitConst); 1012 } 1013 return true; 1014 } 1015 1016 void DevirtModule::rebuildGlobal(VTableBits &B) { 1017 if (B.Before.Bytes.empty() && B.After.Bytes.empty()) 1018 return; 1019 1020 // Align each byte array to pointer width. 1021 unsigned PointerSize = M.getDataLayout().getPointerSize(); 1022 B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize)); 1023 B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize)); 1024 1025 // Before was stored in reverse order; flip it now. 1026 for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) 1027 std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); 1028 1029 // Build an anonymous global containing the before bytes, followed by the 1030 // original initializer, followed by the after bytes. 1031 auto NewInit = ConstantStruct::getAnon( 1032 {ConstantDataArray::get(M.getContext(), B.Before.Bytes), 1033 B.GV->getInitializer(), 1034 ConstantDataArray::get(M.getContext(), B.After.Bytes)}); 1035 auto NewGV = 1036 new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), 1037 GlobalVariable::PrivateLinkage, NewInit, "", B.GV); 1038 NewGV->setSection(B.GV->getSection()); 1039 NewGV->setComdat(B.GV->getComdat()); 1040 1041 // Copy the original vtable's metadata to the anonymous global, adjusting 1042 // offsets as required. 1043 NewGV->copyMetadata(B.GV, B.Before.Bytes.size()); 1044 1045 // Build an alias named after the original global, pointing at the second 1046 // element (the original initializer). 1047 auto Alias = GlobalAlias::create( 1048 B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", 1049 ConstantExpr::getGetElementPtr( 1050 NewInit->getType(), NewGV, 1051 ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), 1052 ConstantInt::get(Int32Ty, 1)}), 1053 &M); 1054 Alias->setVisibility(B.GV->getVisibility()); 1055 Alias->takeName(B.GV); 1056 1057 B.GV->replaceAllUsesWith(Alias); 1058 B.GV->eraseFromParent(); 1059 } 1060 1061 bool DevirtModule::areRemarksEnabled() { 1062 const auto &FL = M.getFunctionList(); 1063 if (FL.empty()) 1064 return false; 1065 const Function &Fn = FL.front(); 1066 1067 const auto &BBL = Fn.getBasicBlockList(); 1068 if (BBL.empty()) 1069 return false; 1070 auto DI = OptimizationRemark(DEBUG_TYPE, "", DebugLoc(), &BBL.front()); 1071 return DI.isEnabled(); 1072 } 1073 1074 void DevirtModule::scanTypeTestUsers(Function *TypeTestFunc, 1075 Function *AssumeFunc) { 1076 // Find all virtual calls via a virtual table pointer %p under an assumption 1077 // of the form llvm.assume(llvm.type.test(%p, %md)). This indicates that %p 1078 // points to a member of the type identifier %md. Group calls by (type ID, 1079 // offset) pair (effectively the identity of the virtual function) and store 1080 // to CallSlots. 1081 DenseSet<Value *> SeenPtrs; 1082 for (auto I = TypeTestFunc->use_begin(), E = TypeTestFunc->use_end(); 1083 I != E;) { 1084 auto CI = dyn_cast<CallInst>(I->getUser()); 1085 ++I; 1086 if (!CI) 1087 continue; 1088 1089 // Search for virtual calls based on %p and add them to DevirtCalls. 1090 SmallVector<DevirtCallSite, 1> DevirtCalls; 1091 SmallVector<CallInst *, 1> Assumes; 1092 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI); 1093 1094 // If we found any, add them to CallSlots. Only do this if we haven't seen 1095 // the vtable pointer before, as it may have been CSE'd with pointers from 1096 // other call sites, and we don't want to process call sites multiple times. 1097 if (!Assumes.empty()) { 1098 Metadata *TypeId = 1099 cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); 1100 Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); 1101 if (SeenPtrs.insert(Ptr).second) { 1102 for (DevirtCallSite Call : DevirtCalls) { 1103 CallSlots[{TypeId, Call.Offset}].addCallSite(CI->getArgOperand(0), 1104 Call.CS, nullptr); 1105 } 1106 } 1107 } 1108 1109 // We no longer need the assumes or the type test. 1110 for (auto Assume : Assumes) 1111 Assume->eraseFromParent(); 1112 // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we 1113 // may use the vtable argument later. 1114 if (CI->use_empty()) 1115 CI->eraseFromParent(); 1116 } 1117 } 1118 1119 void DevirtModule::scanTypeCheckedLoadUsers(Function *TypeCheckedLoadFunc) { 1120 Function *TypeTestFunc = Intrinsic::getDeclaration(&M, Intrinsic::type_test); 1121 1122 for (auto I = TypeCheckedLoadFunc->use_begin(), 1123 E = TypeCheckedLoadFunc->use_end(); 1124 I != E;) { 1125 auto CI = dyn_cast<CallInst>(I->getUser()); 1126 ++I; 1127 if (!CI) 1128 continue; 1129 1130 Value *Ptr = CI->getArgOperand(0); 1131 Value *Offset = CI->getArgOperand(1); 1132 Value *TypeIdValue = CI->getArgOperand(2); 1133 Metadata *TypeId = cast<MetadataAsValue>(TypeIdValue)->getMetadata(); 1134 1135 SmallVector<DevirtCallSite, 1> DevirtCalls; 1136 SmallVector<Instruction *, 1> LoadedPtrs; 1137 SmallVector<Instruction *, 1> Preds; 1138 bool HasNonCallUses = false; 1139 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds, 1140 HasNonCallUses, CI); 1141 1142 // Start by generating "pessimistic" code that explicitly loads the function 1143 // pointer from the vtable and performs the type check. If possible, we will 1144 // eliminate the load and the type check later. 1145 1146 // If possible, only generate the load at the point where it is used. 1147 // This helps avoid unnecessary spills. 1148 IRBuilder<> LoadB( 1149 (LoadedPtrs.size() == 1 && !HasNonCallUses) ? LoadedPtrs[0] : CI); 1150 Value *GEP = LoadB.CreateGEP(Int8Ty, Ptr, Offset); 1151 Value *GEPPtr = LoadB.CreateBitCast(GEP, PointerType::getUnqual(Int8PtrTy)); 1152 Value *LoadedValue = LoadB.CreateLoad(Int8PtrTy, GEPPtr); 1153 1154 for (Instruction *LoadedPtr : LoadedPtrs) { 1155 LoadedPtr->replaceAllUsesWith(LoadedValue); 1156 LoadedPtr->eraseFromParent(); 1157 } 1158 1159 // Likewise for the type test. 1160 IRBuilder<> CallB((Preds.size() == 1 && !HasNonCallUses) ? Preds[0] : CI); 1161 CallInst *TypeTestCall = CallB.CreateCall(TypeTestFunc, {Ptr, TypeIdValue}); 1162 1163 for (Instruction *Pred : Preds) { 1164 Pred->replaceAllUsesWith(TypeTestCall); 1165 Pred->eraseFromParent(); 1166 } 1167 1168 // We have already erased any extractvalue instructions that refer to the 1169 // intrinsic call, but the intrinsic may have other non-extractvalue uses 1170 // (although this is unlikely). In that case, explicitly build a pair and 1171 // RAUW it. 1172 if (!CI->use_empty()) { 1173 Value *Pair = UndefValue::get(CI->getType()); 1174 IRBuilder<> B(CI); 1175 Pair = B.CreateInsertValue(Pair, LoadedValue, {0}); 1176 Pair = B.CreateInsertValue(Pair, TypeTestCall, {1}); 1177 CI->replaceAllUsesWith(Pair); 1178 } 1179 1180 // The number of unsafe uses is initially the number of uses. 1181 auto &NumUnsafeUses = NumUnsafeUsesForTypeTest[TypeTestCall]; 1182 NumUnsafeUses = DevirtCalls.size(); 1183 1184 // If the function pointer has a non-call user, we cannot eliminate the type 1185 // check, as one of those users may eventually call the pointer. Increment 1186 // the unsafe use count to make sure it cannot reach zero. 1187 if (HasNonCallUses) 1188 ++NumUnsafeUses; 1189 for (DevirtCallSite Call : DevirtCalls) { 1190 CallSlots[{TypeId, Call.Offset}].addCallSite(Ptr, Call.CS, 1191 &NumUnsafeUses); 1192 } 1193 1194 CI->eraseFromParent(); 1195 } 1196 } 1197 1198 void DevirtModule::importResolution(VTableSlot Slot, VTableSlotInfo &SlotInfo) { 1199 const WholeProgramDevirtResolution &Res = 1200 Summary->getTypeIdSummary(cast<MDString>(Slot.TypeID)->getString()) 1201 .WPDRes[Slot.ByteOffset]; 1202 1203 if (Res.TheKind == WholeProgramDevirtResolution::SingleImpl) { 1204 // The type of the function in the declaration is irrelevant because every 1205 // call site will cast it to the correct type. 1206 auto *SingleImpl = M.getOrInsertFunction( 1207 Res.SingleImplName, Type::getVoidTy(M.getContext()), nullptr); 1208 1209 // This is the import phase so we should not be exporting anything. 1210 bool IsExported = false; 1211 applySingleImplDevirt(SlotInfo, SingleImpl, IsExported); 1212 assert(!IsExported); 1213 } 1214 1215 for (auto &CSByConstantArg : SlotInfo.ConstCSInfo) { 1216 auto I = Res.ResByArg.find(CSByConstantArg.first); 1217 if (I == Res.ResByArg.end()) 1218 continue; 1219 auto &ResByArg = I->second; 1220 // FIXME: We should figure out what to do about the "function name" argument 1221 // to the apply* functions, as the function names are unavailable during the 1222 // importing phase. For now we just pass the empty string. This does not 1223 // impact correctness because the function names are just used for remarks. 1224 switch (ResByArg.TheKind) { 1225 case WholeProgramDevirtResolution::ByArg::UniformRetVal: 1226 applyUniformRetValOpt(CSByConstantArg.second, "", ResByArg.Info); 1227 break; 1228 case WholeProgramDevirtResolution::ByArg::UniqueRetVal: { 1229 Constant *UniqueMemberAddr = 1230 importGlobal(Slot, CSByConstantArg.first, "unique_member"); 1231 applyUniqueRetValOpt(CSByConstantArg.second, "", ResByArg.Info, 1232 UniqueMemberAddr); 1233 break; 1234 } 1235 case WholeProgramDevirtResolution::ByArg::VirtualConstProp: { 1236 Constant *Byte = importGlobal(Slot, CSByConstantArg.first, "byte", 32); 1237 Byte = ConstantExpr::getPtrToInt(Byte, Int32Ty); 1238 Constant *Bit = importGlobal(Slot, CSByConstantArg.first, "bit", 8); 1239 Bit = ConstantExpr::getPtrToInt(Bit, Int8Ty); 1240 applyVirtualConstProp(CSByConstantArg.second, "", Byte, Bit); 1241 } 1242 default: 1243 break; 1244 } 1245 } 1246 } 1247 1248 void DevirtModule::removeRedundantTypeTests() { 1249 auto True = ConstantInt::getTrue(M.getContext()); 1250 for (auto &&U : NumUnsafeUsesForTypeTest) { 1251 if (U.second == 0) { 1252 U.first->replaceAllUsesWith(True); 1253 U.first->eraseFromParent(); 1254 } 1255 } 1256 } 1257 1258 bool DevirtModule::run() { 1259 Function *TypeTestFunc = 1260 M.getFunction(Intrinsic::getName(Intrinsic::type_test)); 1261 Function *TypeCheckedLoadFunc = 1262 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load)); 1263 Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); 1264 1265 // Normally if there are no users of the devirtualization intrinsics in the 1266 // module, this pass has nothing to do. But if we are exporting, we also need 1267 // to handle any users that appear only in the function summaries. 1268 if (Action != PassSummaryAction::Export && 1269 (!TypeTestFunc || TypeTestFunc->use_empty() || !AssumeFunc || 1270 AssumeFunc->use_empty()) && 1271 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty())) 1272 return false; 1273 1274 if (TypeTestFunc && AssumeFunc) 1275 scanTypeTestUsers(TypeTestFunc, AssumeFunc); 1276 1277 if (TypeCheckedLoadFunc) 1278 scanTypeCheckedLoadUsers(TypeCheckedLoadFunc); 1279 1280 if (Action == PassSummaryAction::Import) { 1281 for (auto &S : CallSlots) 1282 importResolution(S.first, S.second); 1283 1284 removeRedundantTypeTests(); 1285 1286 // The rest of the code is only necessary when exporting or during regular 1287 // LTO, so we are done. 1288 return true; 1289 } 1290 1291 // Rebuild type metadata into a map for easy lookup. 1292 std::vector<VTableBits> Bits; 1293 DenseMap<Metadata *, std::set<TypeMemberInfo>> TypeIdMap; 1294 buildTypeIdentifierMap(Bits, TypeIdMap); 1295 if (TypeIdMap.empty()) 1296 return true; 1297 1298 // Collect information from summary about which calls to try to devirtualize. 1299 if (Action == PassSummaryAction::Export) { 1300 DenseMap<GlobalValue::GUID, TinyPtrVector<Metadata *>> MetadataByGUID; 1301 for (auto &P : TypeIdMap) { 1302 if (auto *TypeId = dyn_cast<MDString>(P.first)) 1303 MetadataByGUID[GlobalValue::getGUID(TypeId->getString())].push_back( 1304 TypeId); 1305 } 1306 1307 for (auto &P : *Summary) { 1308 for (auto &S : P.second) { 1309 auto *FS = dyn_cast<FunctionSummary>(S.get()); 1310 if (!FS) 1311 continue; 1312 // FIXME: Only add live functions. 1313 for (FunctionSummary::VFuncId VF : FS->type_test_assume_vcalls()) { 1314 for (Metadata *MD : MetadataByGUID[VF.GUID]) { 1315 CallSlots[{MD, VF.Offset}].CSInfo.SummaryHasTypeTestAssumeUsers = 1316 true; 1317 } 1318 } 1319 for (FunctionSummary::VFuncId VF : FS->type_checked_load_vcalls()) { 1320 for (Metadata *MD : MetadataByGUID[VF.GUID]) { 1321 CallSlots[{MD, VF.Offset}] 1322 .CSInfo.SummaryTypeCheckedLoadUsers.push_back(FS); 1323 } 1324 } 1325 for (const FunctionSummary::ConstVCall &VC : 1326 FS->type_test_assume_const_vcalls()) { 1327 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { 1328 CallSlots[{MD, VC.VFunc.Offset}] 1329 .ConstCSInfo[VC.Args] 1330 .SummaryHasTypeTestAssumeUsers = true; 1331 } 1332 } 1333 for (const FunctionSummary::ConstVCall &VC : 1334 FS->type_checked_load_const_vcalls()) { 1335 for (Metadata *MD : MetadataByGUID[VC.VFunc.GUID]) { 1336 CallSlots[{MD, VC.VFunc.Offset}] 1337 .ConstCSInfo[VC.Args] 1338 .SummaryTypeCheckedLoadUsers.push_back(FS); 1339 } 1340 } 1341 } 1342 } 1343 } 1344 1345 // For each (type, offset) pair: 1346 bool DidVirtualConstProp = false; 1347 std::map<std::string, Function*> DevirtTargets; 1348 for (auto &S : CallSlots) { 1349 // Search each of the members of the type identifier for the virtual 1350 // function implementation at offset S.first.ByteOffset, and add to 1351 // TargetsForSlot. 1352 std::vector<VirtualCallTarget> TargetsForSlot; 1353 if (tryFindVirtualCallTargets(TargetsForSlot, TypeIdMap[S.first.TypeID], 1354 S.first.ByteOffset)) { 1355 WholeProgramDevirtResolution *Res = nullptr; 1356 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) 1357 Res = 1358 &Summary 1359 ->getTypeIdSummary(cast<MDString>(S.first.TypeID)->getString()) 1360 .WPDRes[S.first.ByteOffset]; 1361 1362 if (!trySingleImplDevirt(TargetsForSlot, S.second, Res) && 1363 tryVirtualConstProp(TargetsForSlot, S.second, Res, S.first)) 1364 DidVirtualConstProp = true; 1365 1366 // Collect functions devirtualized at least for one call site for stats. 1367 if (RemarksEnabled) 1368 for (const auto &T : TargetsForSlot) 1369 if (T.WasDevirt) 1370 DevirtTargets[T.Fn->getName()] = T.Fn; 1371 } 1372 1373 // CFI-specific: if we are exporting and any llvm.type.checked.load 1374 // intrinsics were *not* devirtualized, we need to add the resulting 1375 // llvm.type.test intrinsics to the function summaries so that the 1376 // LowerTypeTests pass will export them. 1377 if (Action == PassSummaryAction::Export && isa<MDString>(S.first.TypeID)) { 1378 auto GUID = 1379 GlobalValue::getGUID(cast<MDString>(S.first.TypeID)->getString()); 1380 for (auto FS : S.second.CSInfo.SummaryTypeCheckedLoadUsers) 1381 FS->addTypeTest(GUID); 1382 for (auto &CCS : S.second.ConstCSInfo) 1383 for (auto FS : CCS.second.SummaryTypeCheckedLoadUsers) 1384 FS->addTypeTest(GUID); 1385 } 1386 } 1387 1388 if (RemarksEnabled) { 1389 // Generate remarks for each devirtualized function. 1390 for (const auto &DT : DevirtTargets) { 1391 Function *F = DT.second; 1392 DISubprogram *SP = F->getSubprogram(); 1393 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, SP, 1394 Twine("devirtualized ") + F->getName()); 1395 } 1396 } 1397 1398 removeRedundantTypeTests(); 1399 1400 // Rebuild each global we touched as part of virtual constant propagation to 1401 // include the before and after bytes. 1402 if (DidVirtualConstProp) 1403 for (VTableBits &B : Bits) 1404 rebuildGlobal(B); 1405 1406 return true; 1407 } 1408