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