Peter Collingbourne | df49d1b | 2016-02-09 22:50:34 +0000 | [diff] [blame^] | 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 bitset information) that the list of callee 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 | //===----------------------------------------------------------------------===// |
| 29 | |
| 30 | #include "llvm/Transforms/IPO/WholeProgramDevirt.h" |
| 31 | #include "llvm/Transforms/IPO.h" |
| 32 | #include "llvm/ADT/DenseSet.h" |
| 33 | #include "llvm/ADT/MapVector.h" |
| 34 | #include "llvm/IR/CallSite.h" |
| 35 | #include "llvm/IR/Constants.h" |
| 36 | #include "llvm/IR/DataLayout.h" |
| 37 | #include "llvm/IR/IRBuilder.h" |
| 38 | #include "llvm/IR/Instructions.h" |
| 39 | #include "llvm/IR/Intrinsics.h" |
| 40 | #include "llvm/IR/Module.h" |
| 41 | #include "llvm/Pass.h" |
| 42 | #include "llvm/Support/raw_ostream.h" |
| 43 | #include "llvm/Transforms/Utils/Evaluator.h" |
| 44 | #include "llvm/Transforms/Utils/Local.h" |
| 45 | |
| 46 | #include <set> |
| 47 | |
| 48 | using namespace llvm; |
| 49 | using namespace wholeprogramdevirt; |
| 50 | |
| 51 | #define DEBUG_TYPE "wholeprogramdevirt" |
| 52 | |
| 53 | // Find the minimum offset that we may store a value of size Size bits at. If |
| 54 | // IsAfter is set, look for an offset before the object, otherwise look for an |
| 55 | // offset after the object. |
| 56 | uint64_t |
| 57 | wholeprogramdevirt::findLowestOffset(ArrayRef<VirtualCallTarget> Targets, |
| 58 | bool IsAfter, uint64_t Size) { |
| 59 | // Find a minimum offset taking into account only vtable sizes. |
| 60 | uint64_t MinByte = 0; |
| 61 | for (const VirtualCallTarget &Target : Targets) { |
| 62 | if (IsAfter) |
| 63 | MinByte = std::max(MinByte, Target.minAfterBytes()); |
| 64 | else |
| 65 | MinByte = std::max(MinByte, Target.minBeforeBytes()); |
| 66 | } |
| 67 | |
| 68 | // Build a vector of arrays of bytes covering, for each target, a slice of the |
| 69 | // used region (see AccumBitVector::BytesUsed in |
| 70 | // llvm/Transforms/IPO/WholeProgramDevirt.h) starting at MinByte. Effectively, |
| 71 | // this aligns the used regions to start at MinByte. |
| 72 | // |
| 73 | // In this example, A, B and C are vtables, # is a byte already allocated for |
| 74 | // a virtual function pointer, AAAA... (etc.) are the used regions for the |
| 75 | // vtables and Offset(X) is the value computed for the Offset variable below |
| 76 | // for X. |
| 77 | // |
| 78 | // Offset(A) |
| 79 | // | | |
| 80 | // |MinByte |
| 81 | // A: ################AAAAAAAA|AAAAAAAA |
| 82 | // B: ########BBBBBBBBBBBBBBBB|BBBB |
| 83 | // C: ########################|CCCCCCCCCCCCCCCC |
| 84 | // | Offset(B) | |
| 85 | // |
| 86 | // This code produces the slices of A, B and C that appear after the divider |
| 87 | // at MinByte. |
| 88 | std::vector<ArrayRef<uint8_t>> Used; |
| 89 | for (const VirtualCallTarget &Target : Targets) { |
| 90 | ArrayRef<uint8_t> VTUsed = IsAfter ? Target.BS->Bits->After.BytesUsed |
| 91 | : Target.BS->Bits->Before.BytesUsed; |
| 92 | uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() |
| 93 | : MinByte - Target.minBeforeBytes(); |
| 94 | |
| 95 | // Disregard used regions that are smaller than Offset. These are |
| 96 | // effectively all-free regions that do not need to be checked. |
| 97 | if (VTUsed.size() > Offset) |
| 98 | Used.push_back(VTUsed.slice(Offset)); |
| 99 | } |
| 100 | |
| 101 | if (Size == 1) { |
| 102 | // Find a free bit in each member of Used. |
| 103 | for (unsigned I = 0;; ++I) { |
| 104 | uint8_t BitsUsed = 0; |
| 105 | for (auto &&B : Used) |
| 106 | if (I < B.size()) |
| 107 | BitsUsed |= B[I]; |
| 108 | if (BitsUsed != 0xff) |
| 109 | return (MinByte + I) * 8 + |
| 110 | countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); |
| 111 | } |
| 112 | } else { |
| 113 | // Find a free (Size/8) byte region in each member of Used. |
| 114 | // FIXME: see if alignment helps. |
| 115 | for (unsigned I = 0;; ++I) { |
| 116 | for (auto &&B : Used) { |
| 117 | unsigned Byte = 0; |
| 118 | while ((I + Byte) < B.size() && Byte < (Size / 8)) { |
| 119 | if (B[I + Byte]) |
| 120 | goto NextI; |
| 121 | ++Byte; |
| 122 | } |
| 123 | } |
| 124 | return (MinByte + I) * 8; |
| 125 | NextI:; |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | void wholeprogramdevirt::setBeforeReturnValues( |
| 131 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocBefore, |
| 132 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 133 | if (BitWidth == 1) |
| 134 | OffsetByte = -(AllocBefore / 8 + 1); |
| 135 | else |
| 136 | OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); |
| 137 | OffsetBit = AllocBefore % 8; |
| 138 | |
| 139 | for (VirtualCallTarget &Target : Targets) { |
| 140 | if (BitWidth == 1) |
| 141 | Target.setBeforeBit(AllocBefore); |
| 142 | else |
| 143 | Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | void wholeprogramdevirt::setAfterReturnValues( |
| 148 | MutableArrayRef<VirtualCallTarget> Targets, uint64_t AllocAfter, |
| 149 | unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { |
| 150 | if (BitWidth == 1) |
| 151 | OffsetByte = AllocAfter / 8; |
| 152 | else |
| 153 | OffsetByte = (AllocAfter + 7) / 8; |
| 154 | OffsetBit = AllocAfter % 8; |
| 155 | |
| 156 | for (VirtualCallTarget &Target : Targets) { |
| 157 | if (BitWidth == 1) |
| 158 | Target.setAfterBit(AllocAfter); |
| 159 | else |
| 160 | Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | VirtualCallTarget::VirtualCallTarget(Function *Fn, const BitSetInfo *BS) |
| 165 | : Fn(Fn), BS(BS), |
| 166 | IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()) {} |
| 167 | |
| 168 | namespace { |
| 169 | |
| 170 | // A slot in a set of virtual tables. The BitSetID identifies the set of virtual |
| 171 | // tables, and the ByteOffset is the offset in bytes from the address point to |
| 172 | // the virtual function pointer. |
| 173 | struct VTableSlot { |
| 174 | Metadata *BitSetID; |
| 175 | uint64_t ByteOffset; |
| 176 | }; |
| 177 | |
| 178 | } |
| 179 | |
| 180 | template <> struct DenseMapInfo<VTableSlot> { |
| 181 | static VTableSlot getEmptyKey() { |
| 182 | return {DenseMapInfo<Metadata *>::getEmptyKey(), |
| 183 | DenseMapInfo<uint64_t>::getEmptyKey()}; |
| 184 | } |
| 185 | static VTableSlot getTombstoneKey() { |
| 186 | return {DenseMapInfo<Metadata *>::getTombstoneKey(), |
| 187 | DenseMapInfo<uint64_t>::getTombstoneKey()}; |
| 188 | } |
| 189 | static unsigned getHashValue(const VTableSlot &I) { |
| 190 | return DenseMapInfo<Metadata *>::getHashValue(I.BitSetID) ^ |
| 191 | DenseMapInfo<uint64_t>::getHashValue(I.ByteOffset); |
| 192 | } |
| 193 | static bool isEqual(const VTableSlot &LHS, |
| 194 | const VTableSlot &RHS) { |
| 195 | return LHS.BitSetID == RHS.BitSetID && LHS.ByteOffset == RHS.ByteOffset; |
| 196 | } |
| 197 | }; |
| 198 | |
| 199 | namespace { |
| 200 | |
| 201 | // A virtual call site. VTable is the loaded virtual table pointer, and CS is |
| 202 | // the indirect virtual call. |
| 203 | struct VirtualCallSite { |
| 204 | Value *VTable; |
| 205 | CallSite CS; |
| 206 | |
| 207 | void replaceAndErase(Value *New) { |
| 208 | CS->replaceAllUsesWith(New); |
| 209 | if (auto II = dyn_cast<InvokeInst>(CS.getInstruction())) { |
| 210 | BranchInst::Create(II->getNormalDest(), CS.getInstruction()); |
| 211 | II->getUnwindDest()->removePredecessor(II->getParent()); |
| 212 | } |
| 213 | CS->eraseFromParent(); |
| 214 | } |
| 215 | }; |
| 216 | |
| 217 | struct DevirtModule { |
| 218 | Module &M; |
| 219 | IntegerType *Int8Ty; |
| 220 | PointerType *Int8PtrTy; |
| 221 | IntegerType *Int32Ty; |
| 222 | |
| 223 | MapVector<VTableSlot, std::vector<VirtualCallSite>> CallSlots; |
| 224 | |
| 225 | DevirtModule(Module &M) |
| 226 | : M(M), Int8Ty(Type::getInt8Ty(M.getContext())), |
| 227 | Int8PtrTy(Type::getInt8PtrTy(M.getContext())), |
| 228 | Int32Ty(Type::getInt32Ty(M.getContext())) {} |
| 229 | void findLoadCallsAtConstantOffset(Metadata *BitSet, Value *Ptr, |
| 230 | uint64_t Offset, Value *VTable); |
| 231 | void findCallsAtConstantOffset(Metadata *BitSet, Value *Ptr, uint64_t Offset, |
| 232 | Value *VTable); |
| 233 | |
| 234 | void buildBitSets(std::vector<VTableBits> &Bits, |
| 235 | DenseMap<Metadata *, std::set<BitSetInfo>> &BitSets); |
| 236 | bool tryFindVirtualCallTargets(std::vector<VirtualCallTarget> &TargetsForSlot, |
| 237 | const std::set<BitSetInfo> &BitSetInfos, |
| 238 | uint64_t ByteOffset); |
| 239 | bool trySingleImplDevirt(ArrayRef<VirtualCallTarget> TargetsForSlot, |
| 240 | MutableArrayRef<VirtualCallSite> CallSites); |
| 241 | bool tryEvaluateFunctionsWithArgs( |
| 242 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
| 243 | ArrayRef<ConstantInt *> Args); |
| 244 | bool tryUniformRetValOpt(IntegerType *RetType, |
| 245 | ArrayRef<VirtualCallTarget> TargetsForSlot, |
| 246 | MutableArrayRef<VirtualCallSite> CallSites); |
| 247 | bool tryUniqueRetValOpt(unsigned BitWidth, |
| 248 | ArrayRef<VirtualCallTarget> TargetsForSlot, |
| 249 | MutableArrayRef<VirtualCallSite> CallSites); |
| 250 | bool tryVirtualConstProp(MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
| 251 | ArrayRef<VirtualCallSite> CallSites); |
| 252 | |
| 253 | void rebuildGlobal(VTableBits &B); |
| 254 | |
| 255 | bool run(); |
| 256 | }; |
| 257 | |
| 258 | struct WholeProgramDevirt : public ModulePass { |
| 259 | static char ID; |
| 260 | WholeProgramDevirt() : ModulePass(ID) { |
| 261 | initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); |
| 262 | } |
| 263 | bool runOnModule(Module &M) { return DevirtModule(M).run(); } |
| 264 | }; |
| 265 | |
| 266 | } // anonymous namespace |
| 267 | |
| 268 | INITIALIZE_PASS(WholeProgramDevirt, "wholeprogramdevirt", |
| 269 | "Whole program devirtualization", false, false) |
| 270 | char WholeProgramDevirt::ID = 0; |
| 271 | |
| 272 | ModulePass *llvm::createWholeProgramDevirtPass() { |
| 273 | return new WholeProgramDevirt; |
| 274 | } |
| 275 | |
| 276 | // Search for virtual calls that call FPtr and add them to CallSlots. |
| 277 | void DevirtModule::findCallsAtConstantOffset(Metadata *BitSet, Value *FPtr, |
| 278 | uint64_t Offset, Value *VTable) { |
| 279 | for (const Use &U : FPtr->uses()) { |
| 280 | Value *User = U.getUser(); |
| 281 | if (isa<BitCastInst>(User)) { |
| 282 | findCallsAtConstantOffset(BitSet, User, Offset, VTable); |
| 283 | } else if (auto CI = dyn_cast<CallInst>(User)) { |
| 284 | CallSlots[{BitSet, Offset}].push_back({VTable, CI}); |
| 285 | } else if (auto II = dyn_cast<InvokeInst>(User)) { |
| 286 | CallSlots[{BitSet, Offset}].push_back({VTable, II}); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // Search for virtual calls that load from VPtr and add them to CallSlots. |
| 292 | void DevirtModule::findLoadCallsAtConstantOffset(Metadata *BitSet, Value *VPtr, |
| 293 | uint64_t Offset, |
| 294 | Value *VTable) { |
| 295 | for (const Use &U : VPtr->uses()) { |
| 296 | Value *User = U.getUser(); |
| 297 | if (isa<BitCastInst>(User)) { |
| 298 | findLoadCallsAtConstantOffset(BitSet, User, Offset, VTable); |
| 299 | } else if (isa<LoadInst>(User)) { |
| 300 | findCallsAtConstantOffset(BitSet, User, Offset, VTable); |
| 301 | } else if (auto GEP = dyn_cast<GetElementPtrInst>(User)) { |
| 302 | // Take into account the GEP offset. |
| 303 | if (VPtr == GEP->getPointerOperand() && GEP->hasAllConstantIndices()) { |
| 304 | SmallVector<Value *, 8> Indices(GEP->op_begin() + 1, GEP->op_end()); |
| 305 | uint64_t GEPOffset = M.getDataLayout().getIndexedOffsetInType( |
| 306 | GEP->getSourceElementType(), Indices); |
| 307 | findLoadCallsAtConstantOffset(BitSet, User, Offset + GEPOffset, VTable); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | void DevirtModule::buildBitSets( |
| 314 | std::vector<VTableBits> &Bits, |
| 315 | DenseMap<Metadata *, std::set<BitSetInfo>> &BitSets) { |
| 316 | NamedMDNode *BitSetNM = M.getNamedMetadata("llvm.bitsets"); |
| 317 | if (!BitSetNM) |
| 318 | return; |
| 319 | |
| 320 | DenseMap<GlobalVariable *, VTableBits *> GVToBits; |
| 321 | Bits.reserve(BitSetNM->getNumOperands()); |
| 322 | for (auto Op : BitSetNM->operands()) { |
| 323 | auto OpConstMD = dyn_cast_or_null<ConstantAsMetadata>(Op->getOperand(1)); |
| 324 | if (!OpConstMD) |
| 325 | continue; |
| 326 | auto BitSetID = Op->getOperand(0).get(); |
| 327 | |
| 328 | Constant *OpConst = OpConstMD->getValue(); |
| 329 | if (auto GA = dyn_cast<GlobalAlias>(OpConst)) |
| 330 | OpConst = GA->getAliasee(); |
| 331 | auto OpGlobal = dyn_cast<GlobalVariable>(OpConst); |
| 332 | if (!OpGlobal) |
| 333 | continue; |
| 334 | |
| 335 | uint64_t Offset = |
| 336 | cast<ConstantInt>( |
| 337 | cast<ConstantAsMetadata>(Op->getOperand(2))->getValue()) |
| 338 | ->getZExtValue(); |
| 339 | |
| 340 | VTableBits *&BitsPtr = GVToBits[OpGlobal]; |
| 341 | if (!BitsPtr) { |
| 342 | Bits.emplace_back(); |
| 343 | Bits.back().GV = OpGlobal; |
| 344 | Bits.back().ObjectSize = M.getDataLayout().getTypeAllocSize( |
| 345 | OpGlobal->getInitializer()->getType()); |
| 346 | BitsPtr = &Bits.back(); |
| 347 | } |
| 348 | BitSets[BitSetID].insert({BitsPtr, Offset}); |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | bool DevirtModule::tryFindVirtualCallTargets( |
| 353 | std::vector<VirtualCallTarget> &TargetsForSlot, |
| 354 | const std::set<BitSetInfo> &BitSetInfos, uint64_t ByteOffset) { |
| 355 | for (const BitSetInfo &BS : BitSetInfos) { |
| 356 | if (!BS.Bits->GV->isConstant()) |
| 357 | return false; |
| 358 | |
| 359 | auto Init = dyn_cast<ConstantArray>(BS.Bits->GV->getInitializer()); |
| 360 | if (!Init) |
| 361 | return false; |
| 362 | ArrayType *VTableTy = Init->getType(); |
| 363 | |
| 364 | uint64_t ElemSize = |
| 365 | M.getDataLayout().getTypeAllocSize(VTableTy->getElementType()); |
| 366 | uint64_t GlobalSlotOffset = BS.Offset + ByteOffset; |
| 367 | if (GlobalSlotOffset % ElemSize != 0) |
| 368 | return false; |
| 369 | |
| 370 | unsigned Op = GlobalSlotOffset / ElemSize; |
| 371 | if (Op >= Init->getNumOperands()) |
| 372 | return false; |
| 373 | |
| 374 | auto Fn = dyn_cast<Function>(Init->getOperand(Op)->stripPointerCasts()); |
| 375 | if (!Fn) |
| 376 | return false; |
| 377 | |
| 378 | // We can disregard __cxa_pure_virtual as a possible call target, as |
| 379 | // calls to pure virtuals are UB. |
| 380 | if (Fn->getName() == "__cxa_pure_virtual") |
| 381 | continue; |
| 382 | |
| 383 | TargetsForSlot.push_back({Fn, &BS}); |
| 384 | } |
| 385 | |
| 386 | // Give up if we couldn't find any targets. |
| 387 | return !TargetsForSlot.empty(); |
| 388 | } |
| 389 | |
| 390 | bool DevirtModule::trySingleImplDevirt( |
| 391 | ArrayRef<VirtualCallTarget> TargetsForSlot, |
| 392 | MutableArrayRef<VirtualCallSite> CallSites) { |
| 393 | // See if the program contains a single implementation of this virtual |
| 394 | // function. |
| 395 | Function *TheFn = TargetsForSlot[0].Fn; |
| 396 | for (auto &&Target : TargetsForSlot) |
| 397 | if (TheFn != Target.Fn) |
| 398 | return false; |
| 399 | |
| 400 | // If so, update each call site to call that implementation directly. |
| 401 | for (auto &&VCallSite : CallSites) { |
| 402 | VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( |
| 403 | TheFn, VCallSite.CS.getCalledValue()->getType())); |
| 404 | } |
| 405 | return true; |
| 406 | } |
| 407 | |
| 408 | bool DevirtModule::tryEvaluateFunctionsWithArgs( |
| 409 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
| 410 | ArrayRef<ConstantInt *> Args) { |
| 411 | // Evaluate each function and store the result in each target's RetVal |
| 412 | // field. |
| 413 | for (VirtualCallTarget &Target : TargetsForSlot) { |
| 414 | if (Target.Fn->arg_size() != Args.size() + 1) |
| 415 | return false; |
| 416 | for (unsigned I = 0; I != Args.size(); ++I) |
| 417 | if (Target.Fn->getFunctionType()->getParamType(I + 1) != |
| 418 | Args[I]->getType()) |
| 419 | return false; |
| 420 | |
| 421 | Evaluator Eval(M.getDataLayout(), nullptr); |
| 422 | SmallVector<Constant *, 2> EvalArgs; |
| 423 | EvalArgs.push_back( |
| 424 | Constant::getNullValue(Target.Fn->getFunctionType()->getParamType(0))); |
| 425 | EvalArgs.insert(EvalArgs.end(), Args.begin(), Args.end()); |
| 426 | Constant *RetVal; |
| 427 | if (!Eval.EvaluateFunction(Target.Fn, RetVal, EvalArgs) || |
| 428 | !isa<ConstantInt>(RetVal)) |
| 429 | return false; |
| 430 | Target.RetVal = cast<ConstantInt>(RetVal)->getZExtValue(); |
| 431 | } |
| 432 | return true; |
| 433 | } |
| 434 | |
| 435 | bool DevirtModule::tryUniformRetValOpt( |
| 436 | IntegerType *RetType, ArrayRef<VirtualCallTarget> TargetsForSlot, |
| 437 | MutableArrayRef<VirtualCallSite> CallSites) { |
| 438 | // Uniform return value optimization. If all functions return the same |
| 439 | // constant, replace all calls with that constant. |
| 440 | uint64_t TheRetVal = TargetsForSlot[0].RetVal; |
| 441 | for (const VirtualCallTarget &Target : TargetsForSlot) |
| 442 | if (Target.RetVal != TheRetVal) |
| 443 | return false; |
| 444 | |
| 445 | auto TheRetValConst = ConstantInt::get(RetType, TheRetVal); |
| 446 | for (auto Call : CallSites) |
| 447 | Call.replaceAndErase(TheRetValConst); |
| 448 | return true; |
| 449 | } |
| 450 | |
| 451 | bool DevirtModule::tryUniqueRetValOpt( |
| 452 | unsigned BitWidth, ArrayRef<VirtualCallTarget> TargetsForSlot, |
| 453 | MutableArrayRef<VirtualCallSite> CallSites) { |
| 454 | // IsOne controls whether we look for a 0 or a 1. |
| 455 | auto tryUniqueRetValOptFor = [&](bool IsOne) { |
| 456 | const BitSetInfo *UniqueBitSet = 0; |
| 457 | for (const VirtualCallTarget &Target : TargetsForSlot) { |
| 458 | if (Target.RetVal == IsOne ? 1 : 0) { |
| 459 | if (UniqueBitSet) |
| 460 | return false; |
| 461 | UniqueBitSet = Target.BS; |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | // We should have found a unique bit set or bailed out by now. We already |
| 466 | // checked for a uniform return value in tryUniformRetValOpt. |
| 467 | assert(UniqueBitSet); |
| 468 | |
| 469 | // Replace each call with the comparison. |
| 470 | for (auto &&Call : CallSites) { |
| 471 | IRBuilder<> B(Call.CS.getInstruction()); |
| 472 | Value *OneAddr = B.CreateBitCast(UniqueBitSet->Bits->GV, Int8PtrTy); |
| 473 | OneAddr = B.CreateConstGEP1_64(OneAddr, UniqueBitSet->Offset); |
| 474 | Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, |
| 475 | Call.VTable, OneAddr); |
| 476 | Call.replaceAndErase(Cmp); |
| 477 | } |
| 478 | return true; |
| 479 | }; |
| 480 | |
| 481 | if (BitWidth == 1) { |
| 482 | if (tryUniqueRetValOptFor(true)) |
| 483 | return true; |
| 484 | if (tryUniqueRetValOptFor(false)) |
| 485 | return true; |
| 486 | } |
| 487 | return false; |
| 488 | } |
| 489 | |
| 490 | bool DevirtModule::tryVirtualConstProp( |
| 491 | MutableArrayRef<VirtualCallTarget> TargetsForSlot, |
| 492 | ArrayRef<VirtualCallSite> CallSites) { |
| 493 | // This only works if the function returns an integer. |
| 494 | auto RetType = dyn_cast<IntegerType>(TargetsForSlot[0].Fn->getReturnType()); |
| 495 | if (!RetType) |
| 496 | return false; |
| 497 | unsigned BitWidth = RetType->getBitWidth(); |
| 498 | if (BitWidth > 64) |
| 499 | return false; |
| 500 | |
| 501 | // Make sure that each function does not access memory, takes at least one |
| 502 | // argument, does not use its first argument (which we assume is 'this'), |
| 503 | // and has the same return type. |
| 504 | for (VirtualCallTarget &Target : TargetsForSlot) { |
| 505 | if (!Target.Fn->doesNotAccessMemory() || Target.Fn->arg_empty() || |
| 506 | !Target.Fn->arg_begin()->use_empty() || |
| 507 | Target.Fn->getReturnType() != RetType) |
| 508 | return false; |
| 509 | } |
| 510 | |
| 511 | // Group call sites by the list of constant arguments they pass. |
| 512 | // The comparator ensures deterministic ordering. |
| 513 | struct ByAPIntValue { |
| 514 | bool operator()(const std::vector<ConstantInt *> &A, |
| 515 | const std::vector<ConstantInt *> &B) const { |
| 516 | return std::lexicographical_compare( |
| 517 | A.begin(), A.end(), B.begin(), B.end(), |
| 518 | [](ConstantInt *AI, ConstantInt *BI) { |
| 519 | return AI->getValue().ult(BI->getValue()); |
| 520 | }); |
| 521 | } |
| 522 | }; |
| 523 | std::map<std::vector<ConstantInt *>, std::vector<VirtualCallSite>, |
| 524 | ByAPIntValue> |
| 525 | VCallSitesByConstantArg; |
| 526 | for (auto &&VCallSite : CallSites) { |
| 527 | std::vector<ConstantInt *> Args; |
| 528 | if (VCallSite.CS.getType() != RetType) |
| 529 | continue; |
| 530 | for (auto &&Arg : |
| 531 | make_range(VCallSite.CS.arg_begin() + 1, VCallSite.CS.arg_end())) { |
| 532 | if (!isa<ConstantInt>(Arg)) |
| 533 | break; |
| 534 | Args.push_back(cast<ConstantInt>(&Arg)); |
| 535 | } |
| 536 | if (Args.size() + 1 != VCallSite.CS.arg_size()) |
| 537 | continue; |
| 538 | |
| 539 | VCallSitesByConstantArg[Args].push_back(VCallSite); |
| 540 | } |
| 541 | |
| 542 | for (auto &&CSByConstantArg : VCallSitesByConstantArg) { |
| 543 | if (!tryEvaluateFunctionsWithArgs(TargetsForSlot, CSByConstantArg.first)) |
| 544 | continue; |
| 545 | |
| 546 | if (tryUniformRetValOpt(RetType, TargetsForSlot, CSByConstantArg.second)) |
| 547 | continue; |
| 548 | |
| 549 | if (tryUniqueRetValOpt(BitWidth, TargetsForSlot, CSByConstantArg.second)) |
| 550 | continue; |
| 551 | |
| 552 | // Find an allocation offset in bits in all vtables in the bitset. |
| 553 | uint64_t AllocBefore = |
| 554 | findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); |
| 555 | uint64_t AllocAfter = |
| 556 | findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); |
| 557 | |
| 558 | // Calculate the total amount of padding needed to store a value at both |
| 559 | // ends of the object. |
| 560 | uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; |
| 561 | for (auto &&Target : TargetsForSlot) { |
| 562 | TotalPaddingBefore += std::max<int64_t>( |
| 563 | (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); |
| 564 | TotalPaddingAfter += std::max<int64_t>( |
| 565 | (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); |
| 566 | } |
| 567 | |
| 568 | // If the amount of padding is too large, give up. |
| 569 | // FIXME: do something smarter here. |
| 570 | if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) |
| 571 | continue; |
| 572 | |
| 573 | // Calculate the offset to the value as a (possibly negative) byte offset |
| 574 | // and (if applicable) a bit offset, and store the values in the targets. |
| 575 | int64_t OffsetByte; |
| 576 | uint64_t OffsetBit; |
| 577 | if (TotalPaddingBefore <= TotalPaddingAfter) |
| 578 | setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, |
| 579 | OffsetBit); |
| 580 | else |
| 581 | setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, |
| 582 | OffsetBit); |
| 583 | |
| 584 | // Rewrite each call to a load from OffsetByte/OffsetBit. |
| 585 | for (auto Call : CSByConstantArg.second) { |
| 586 | IRBuilder<> B(Call.CS.getInstruction()); |
| 587 | Value *Addr = B.CreateConstGEP1_64(Call.VTable, OffsetByte); |
| 588 | if (BitWidth == 1) { |
| 589 | Value *Bits = B.CreateLoad(Addr); |
| 590 | Value *Bit = ConstantInt::get(Int8Ty, 1 << OffsetBit); |
| 591 | Value *BitsAndBit = B.CreateAnd(Bits, Bit); |
| 592 | auto IsBitSet = B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); |
| 593 | Call.replaceAndErase(IsBitSet); |
| 594 | } else { |
| 595 | Value *ValAddr = B.CreateBitCast(Addr, RetType->getPointerTo()); |
| 596 | Value *Val = B.CreateLoad(RetType, ValAddr); |
| 597 | Call.replaceAndErase(Val); |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | return true; |
| 602 | } |
| 603 | |
| 604 | void DevirtModule::rebuildGlobal(VTableBits &B) { |
| 605 | if (B.Before.Bytes.empty() && B.After.Bytes.empty()) |
| 606 | return; |
| 607 | |
| 608 | // Align each byte array to pointer width. |
| 609 | unsigned PointerSize = M.getDataLayout().getPointerSize(); |
| 610 | B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize)); |
| 611 | B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize)); |
| 612 | |
| 613 | // Before was stored in reverse order; flip it now. |
| 614 | for (size_t I = 0, Size = B.Before.Bytes.size(); I != Size / 2; ++I) |
| 615 | std::swap(B.Before.Bytes[I], B.Before.Bytes[Size - 1 - I]); |
| 616 | |
| 617 | // Build an anonymous global containing the before bytes, followed by the |
| 618 | // original initializer, followed by the after bytes. |
| 619 | auto NewInit = ConstantStruct::getAnon( |
| 620 | {ConstantDataArray::get(M.getContext(), B.Before.Bytes), |
| 621 | B.GV->getInitializer(), |
| 622 | ConstantDataArray::get(M.getContext(), B.After.Bytes)}); |
| 623 | auto NewGV = |
| 624 | new GlobalVariable(M, NewInit->getType(), B.GV->isConstant(), |
| 625 | GlobalVariable::PrivateLinkage, NewInit, "", B.GV); |
| 626 | NewGV->setSection(B.GV->getSection()); |
| 627 | NewGV->setComdat(B.GV->getComdat()); |
| 628 | |
| 629 | // Build an alias named after the original global, pointing at the second |
| 630 | // element (the original initializer). |
| 631 | auto Alias = GlobalAlias::create( |
| 632 | B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", |
| 633 | ConstantExpr::getGetElementPtr( |
| 634 | NewInit->getType(), NewGV, |
| 635 | ArrayRef<Constant *>{ConstantInt::get(Int32Ty, 0), |
| 636 | ConstantInt::get(Int32Ty, 1)}), |
| 637 | &M); |
| 638 | Alias->setVisibility(B.GV->getVisibility()); |
| 639 | Alias->takeName(B.GV); |
| 640 | |
| 641 | B.GV->replaceAllUsesWith(Alias); |
| 642 | B.GV->eraseFromParent(); |
| 643 | } |
| 644 | |
| 645 | bool DevirtModule::run() { |
| 646 | Function *BitSetTestFunc = |
| 647 | M.getFunction(Intrinsic::getName(Intrinsic::bitset_test)); |
| 648 | if (!BitSetTestFunc || BitSetTestFunc->use_empty()) |
| 649 | return false; |
| 650 | |
| 651 | Function *AssumeFunc = M.getFunction(Intrinsic::getName(Intrinsic::assume)); |
| 652 | if (!AssumeFunc || AssumeFunc->use_empty()) |
| 653 | return false; |
| 654 | |
| 655 | // Find all virtual calls via a virtual table pointer %p under an assumption |
| 656 | // of the form llvm.assume(llvm.bitset.test(%p, %md)). This indicates that %p |
| 657 | // points to a vtable in the bitset %md. Group calls by (bitset, offset) pair |
| 658 | // (effectively the identity of the virtual function) and store to CallSlots. |
| 659 | DenseSet<Value *> SeenPtrs; |
| 660 | for (auto I = BitSetTestFunc->use_begin(), E = BitSetTestFunc->use_end(); |
| 661 | I != E;) { |
| 662 | auto CI = dyn_cast<CallInst>(I->getUser()); |
| 663 | ++I; |
| 664 | if (!CI) |
| 665 | continue; |
| 666 | |
| 667 | // Find llvm.assume intrinsics for this llvm.bitset.test call. |
| 668 | SmallVector<CallInst *, 1> Assumes; |
| 669 | for (const Use &CIU : CI->uses()) { |
| 670 | auto AssumeCI = dyn_cast<CallInst>(CIU.getUser()); |
| 671 | if (AssumeCI && AssumeCI->getCalledValue() == AssumeFunc) |
| 672 | Assumes.push_back(AssumeCI); |
| 673 | } |
| 674 | |
| 675 | // If we found any, search for virtual calls based on %p and add them to |
| 676 | // CallSlots. |
| 677 | if (!Assumes.empty()) { |
| 678 | Metadata *BitSet = |
| 679 | cast<MetadataAsValue>(CI->getArgOperand(1))->getMetadata(); |
| 680 | Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); |
| 681 | if (SeenPtrs.insert(Ptr).second) |
| 682 | findLoadCallsAtConstantOffset(BitSet, Ptr, 0, CI->getArgOperand(0)); |
| 683 | } |
| 684 | |
| 685 | // We no longer need the assumes or the bitset test. |
| 686 | for (auto Assume : Assumes) |
| 687 | Assume->eraseFromParent(); |
| 688 | // We can't use RecursivelyDeleteTriviallyDeadInstructions here because we |
| 689 | // may use the vtable argument later. |
| 690 | if (CI->use_empty()) |
| 691 | CI->eraseFromParent(); |
| 692 | } |
| 693 | |
| 694 | // Rebuild llvm.bitsets metadata into a map for easy lookup. |
| 695 | std::vector<VTableBits> Bits; |
| 696 | DenseMap<Metadata *, std::set<BitSetInfo>> BitSets; |
| 697 | buildBitSets(Bits, BitSets); |
| 698 | if (BitSets.empty()) |
| 699 | return true; |
| 700 | |
| 701 | // For each (bitset, offset) pair: |
| 702 | bool DidVirtualConstProp = false; |
| 703 | for (auto &S : CallSlots) { |
| 704 | // Search each of the vtables in the bitset for the virtual function |
| 705 | // implementation at offset S.first.ByteOffset, and add to TargetsForSlot. |
| 706 | std::vector<VirtualCallTarget> TargetsForSlot; |
| 707 | if (!tryFindVirtualCallTargets(TargetsForSlot, BitSets[S.first.BitSetID], |
| 708 | S.first.ByteOffset)) |
| 709 | continue; |
| 710 | |
| 711 | if (trySingleImplDevirt(TargetsForSlot, S.second)) |
| 712 | continue; |
| 713 | |
| 714 | DidVirtualConstProp |= tryVirtualConstProp(TargetsForSlot, S.second); |
| 715 | } |
| 716 | |
| 717 | // Rebuild each global we touched as part of virtual constant propagation to |
| 718 | // include the before and after bytes. |
| 719 | if (DidVirtualConstProp) |
| 720 | for (VTableBits &B : Bits) |
| 721 | rebuildGlobal(B); |
| 722 | |
| 723 | return true; |
| 724 | } |