Index: include/llvm/InitializePasses.h =================================================================== --- include/llvm/InitializePasses.h +++ include/llvm/InitializePasses.h @@ -312,6 +312,7 @@ void initializeFuncletLayoutPass(PassRegistry &); void initializeLoopLoadEliminationPass(PassRegistry&); void initializeFunctionImportPassPass(PassRegistry &); +void initializeWholeProgramDevirtPass(PassRegistry &); } #endif Index: include/llvm/Transforms/IPO.h =================================================================== --- include/llvm/Transforms/IPO.h +++ include/llvm/Transforms/IPO.h @@ -226,6 +226,10 @@ /// \brief This pass export CFI checks for use by external modules. ModulePass *createCrossDSOCFIPass(); +/// \brief This pass implements whole-program devirtualization using bitset +/// metadata. +ModulePass *createWholeProgramDevirtPass(); + //===----------------------------------------------------------------------===// // SampleProfilePass - Loads sample profile data from disk and generates // IR metadata to reflect the profile. Index: include/llvm/Transforms/IPO/PassManagerBuilder.h =================================================================== --- include/llvm/Transforms/IPO/PassManagerBuilder.h +++ include/llvm/Transforms/IPO/PassManagerBuilder.h @@ -157,6 +157,7 @@ legacy::PassManagerBase &PM) const; void addInitialAliasAnalysisPasses(legacy::PassManagerBase &PM) const; void addLTOOptimizationPasses(legacy::PassManagerBase &PM); + void addEarlyLTOOptimizationPasses(legacy::PassManagerBase &PM); void addLateLTOOptimizationPasses(legacy::PassManagerBase &PM); void addPGOInstrPasses(legacy::PassManagerBase &MPM); Index: include/llvm/Transforms/IPO/WholeProgramDevirt.h =================================================================== --- /dev/null +++ include/llvm/Transforms/IPO/WholeProgramDevirt.h @@ -0,0 +1,214 @@ +//===- WholeProgramDevirt.h - Whole-program devirt pass ---------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file defines parts of the whole-program devirtualization pass +// implementation that may be usefully unit tested. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TRANSFORMS_IPO_WHOLEPROGRAMDEVIRT_H +#define LLVM_TRANSFORMS_IPO_WHOLEPROGRAMDEVIRT_H + +#include "llvm/ADT/ArrayRef.h" +#include +#include +#include +#include + +namespace llvm { + +class Function; +class GlobalVariable; + +namespace wholeprogramdevirt { + +// A bit vector that keeps track of which bits are used. We use this to +// pack constant values compactly before and after each virtual table. +struct AccumBitVector { + std::vector Bytes; + + // Bits in BytesUsed[I] are 1 if matching bit in Bytes[I] is used, 0 if not. + std::vector BytesUsed; + + std::pair getPtrToData(uint64_t Pos, uint8_t Size) { + if (Bytes.size() < Pos + Size) { + Bytes.resize(Pos + Size); + BytesUsed.resize(Pos + Size); + } + return std::make_pair(Bytes.data() + Pos, BytesUsed.data() + Pos); + } + + // Set little-endian value Val with size Size at bit position Pos, + // and mark bytes as used. + void setLE(uint64_t Pos, uint64_t Val, uint8_t Size) { + assert(Pos % 8 == 0); + auto DataUsed = getPtrToData(Pos / 8, Size); + for (unsigned I = 0; I != Size; ++I) { + DataUsed.first[I] = Val >> (I * 8); + assert(!DataUsed.second[I]); + DataUsed.second[I] = 0xff; + } + } + + // Set big-endian value Val with size Size at bit position Pos, + // and mark bytes as used. + void setBE(uint64_t Pos, uint64_t Val, uint8_t Size) { + assert(Pos % 8 == 0); + auto DataUsed = getPtrToData(Pos / 8, Size); + for (unsigned I = 0; I != Size; ++I) { + DataUsed.first[Size - I - 1] = Val >> (I * 8); + assert(!DataUsed.second[Size - I - 1]); + DataUsed.second[Size - I - 1] = 0xff; + } + } + + // Set bit at bit position Pos to b and mark bit as used. + void setBit(uint64_t Pos, bool b) { + auto DataUsed = getPtrToData(Pos / 8, 1); + if (b) + *DataUsed.first |= 1 << (Pos % 8); + assert(!(*DataUsed.second & (1 << Pos % 8))); + *DataUsed.second |= 1 << (Pos % 8); + } +}; + +// The bits that will be stored before and after a particular vtable. +struct VTableBits { + // The vtable global. + GlobalVariable *GV; + + // Cache of the vtable's size in bytes. + uint64_t ObjectSize = 0; + + // The bit vector that will be laid out before the vtable. Note that these + // bytes are stored in reverse order until the globals are rebuilt. This means + // that any values in the array must be stored using the opposite endianness + // from the target. + AccumBitVector Before; + + // The bit vector that will be laid out after the vtable. + AccumBitVector After; +}; + +// Information about an entry in a particular bitset. +struct BitSetInfo { + // The VTableBits for the vtable. + VTableBits *Bits; + + // The offset in bytes from the start of the vtable (i.e. the address point). + uint64_t Offset; + + bool operator<(const BitSetInfo &other) const { + return Bits < other.Bits || (Bits == other.Bits && Offset < other.Offset); + } +}; + +// A virtual call target, i.e. an entry in a particular vtable. +struct VirtualCallTarget { + VirtualCallTarget(Function *Fn, const BitSetInfo *BS); + + // For testing only. + VirtualCallTarget(const BitSetInfo *BS, bool IsBigEndian) + : Fn(nullptr), BS(BS), IsBigEndian(IsBigEndian) {} + + // The function stored in the vtable. + Function *Fn; + + // A pointer to the bitset through which the pointer to Fn is accessed. + const BitSetInfo *BS; + + // When doing virtual constant propagation, this stores the return value for + // the function when passed the currently considered argument list. + uint64_t RetVal; + + // Whether the target is big endian. + bool IsBigEndian; + + // The minimum byte offset before the address point. This covers the bytes in + // the vtable object before the address point (e.g. RTTI, access-to-top, + // vtables for other base classes) and is equal to the offset from the start + // of the vtable object to the address point. + uint64_t minBeforeBytes() const { return BS->Offset; } + + // The minimum byte offset after the address point. This covers the bytes in + // the vtable object after the address point (e.g. the vtable for the current + // class and any later base classes) and is equal to the size of the vtable + // object minus the offset from the start of the vtable object to the address + // point. + uint64_t minAfterBytes() const { return BS->Bits->ObjectSize - BS->Offset; } + + // The number of bytes allocated (for the vtable plus the byte array) before + // the address point. + uint64_t allocatedBeforeBytes() const { + return minBeforeBytes() + BS->Bits->Before.Bytes.size(); + } + + // The number of bytes allocated (for the vtable plus the byte array) after + // the address point. + uint64_t allocatedAfterBytes() const { + return minAfterBytes() + BS->Bits->After.Bytes.size(); + } + + // Set the bit at position Pos before the address point to RetVal. + void setBeforeBit(uint64_t Pos) { + assert(Pos >= 8 * minBeforeBytes()); + BS->Bits->Before.setBit(Pos - 8 * minBeforeBytes(), RetVal); + } + + // Set the bit at position Pos after the address point to RetVal. + void setAfterBit(uint64_t Pos) { + assert(Pos >= 8 * minAfterBytes()); + BS->Bits->After.setBit(Pos - 8 * minAfterBytes(), RetVal); + } + + // Set the bytes at position Pos before the address point to RetVal. + // Because the bytes in Before are stored in reverse order, we use the + // opposite endianness to the target. + void setBeforeBytes(uint64_t Pos, uint8_t Size) { + assert(Pos >= 8 * minBeforeBytes()); + if (IsBigEndian) + BS->Bits->Before.setLE(Pos - 8 * minBeforeBytes(), RetVal, Size); + else + BS->Bits->Before.setBE(Pos - 8 * minBeforeBytes(), RetVal, Size); + } + + // Set the bytes at position Pos after the address point to RetVal. + void setAfterBytes(uint64_t Pos, uint8_t Size) { + assert(Pos >= 8 * minAfterBytes()); + if (IsBigEndian) + BS->Bits->After.setBE(Pos - 8 * minAfterBytes(), RetVal, Size); + else + BS->Bits->After.setLE(Pos - 8 * minAfterBytes(), RetVal, Size); + } +}; + +// Find the minimum offset that we may store a value of size Size bits at. If +// IsAfter is set, look for an offset before the object, otherwise look for an +// offset after the object. +uint64_t findLowestOffset(ArrayRef Targets, bool IsAfter, + uint64_t Size); + +// Set the stored value in each of Targets to VirtualCallTarget::RetVal at the +// given allocation offset before the vtable address. Stores the computed +// byte/bit offset to OffsetByte/OffsetBit. +void setBeforeReturnValues(MutableArrayRef Targets, + uint64_t AllocBefore, unsigned BitWidth, + int64_t &OffsetByte, uint64_t &OffsetBit); + +// Set the stored value in each of Targets to VirtualCallTarget::RetVal at the +// given allocation offset after the vtable address. Stores the computed +// byte/bit offset to OffsetByte/OffsetBit. +void setAfterReturnValues(MutableArrayRef Targets, + uint64_t AllocAfter, unsigned BitWidth, + int64_t &OffsetByte, uint64_t &OffsetBit); + +} +} + +#endif Index: include/llvm/Transforms/Utils/Evaluator.h =================================================================== --- /dev/null +++ include/llvm/Transforms/Utils/Evaluator.h @@ -0,0 +1,119 @@ +//===-- Evaluator.h - LLVM IR evaluator -------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Function evaluator for LLVM IR. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TRANSFORMS_UTILS_EVALUATOR_H +#define LLVM_TRANSFORMS_UTILS_EVALUATOR_H + +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/Constant.h" +#include "llvm/IR/GlobalVariable.h" + +#include +#include + +namespace llvm { + +class DataLayout; +class Function; +class TargetLibraryInfo; + +/// This class evaluates LLVM IR, producing the Constant representing each SSA +/// instruction. Changes to global variables are stored in a mapping that can +/// be iterated over after the evaluation is complete. Once an evaluation call +/// fails, the evaluation object should not be reused. +class Evaluator { +public: + Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI) + : DL(DL), TLI(TLI) { + ValueStack.emplace_back(); + } + + ~Evaluator() { + for (auto &Tmp : AllocaTmps) + // If there are still users of the alloca, the program is doing something + // silly, e.g. storing the address of the alloca somewhere and using it + // later. Since this is undefined, we'll just make it be null. + if (!Tmp->use_empty()) + Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType())); + } + + /// Evaluate a call to function F, returning true if successful, false if we + /// can't evaluate it. ActualArgs contains the formal arguments for the + /// function. + bool EvaluateFunction(Function *F, Constant *&RetVal, + const SmallVectorImpl &ActualArgs); + + /// Evaluate all instructions in block BB, returning true if successful, false + /// if we can't evaluate it. NewBB returns the next BB that control flows + /// into, or null upon return. + bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB); + + Constant *getVal(Value *V) { + if (Constant *CV = dyn_cast(V)) return CV; + Constant *R = ValueStack.back().lookup(V); + assert(R && "Reference to an uncomputed value!"); + return R; + } + + void setVal(Value *V, Constant *C) { + ValueStack.back()[V] = C; + } + + const DenseMap &getMutatedMemory() const { + return MutatedMemory; + } + + const SmallPtrSetImpl &getInvariants() const { + return Invariants; + } + +private: + Constant *ComputeLoadResult(Constant *P); + + /// As we compute SSA register values, we store their contents here. The back + /// of the deque contains the current function and the stack contains the + /// values in the calling frames. + std::deque> ValueStack; + + /// This is used to detect recursion. In pathological situations we could hit + /// exponential behavior, but at least there is nothing unbounded. + SmallVector CallStack; + + /// For each store we execute, we update this map. Loads check this to get + /// the most up-to-date value. If evaluation is successful, this state is + /// committed to the process. + DenseMap MutatedMemory; + + /// To 'execute' an alloca, we create a temporary global variable to represent + /// its body. This vector is needed so we can delete the temporary globals + /// when we are done. + SmallVector, 32> AllocaTmps; + + /// These global variables have been marked invariant by the static + /// constructor. + SmallPtrSet Invariants; + + /// These are constants we have checked and know to be simple enough to live + /// in a static initializer of a global. + SmallPtrSet SimpleConstants; + + const DataLayout &DL; + const TargetLibraryInfo *TLI; +}; + +} + +#endif Index: lib/Transforms/IPO/CMakeLists.txt =================================================================== --- lib/Transforms/IPO/CMakeLists.txt +++ lib/Transforms/IPO/CMakeLists.txt @@ -27,6 +27,7 @@ SampleProfile.cpp StripDeadPrototypes.cpp StripSymbols.cpp + WholeProgramDevirt.cpp ADDITIONAL_HEADER_DIRS ${LLVM_MAIN_INCLUDE_DIR}/llvm/Transforms Index: lib/Transforms/IPO/GlobalOpt.cpp =================================================================== --- lib/Transforms/IPO/GlobalOpt.cpp +++ lib/Transforms/IPO/GlobalOpt.cpp @@ -41,6 +41,7 @@ #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Utils/CtorUtils.h" +#include "llvm/Transforms/Utils/Evaluator.h" #include "llvm/Transforms/Utils/GlobalStatus.h" #include "llvm/Transforms/Utils/ModuleUtils.h" #include @@ -2106,138 +2107,6 @@ return Changed; } -static inline bool -isSimpleEnoughValueToCommit(Constant *C, - SmallPtrSetImpl &SimpleConstants, - const DataLayout &DL); - -/// Return true if the specified constant can be handled by the code generator. -/// We don't want to generate something like: -/// void *X = &X/42; -/// because the code generator doesn't have a relocation that can handle that. -/// -/// This function should be called if C was not found (but just got inserted) -/// in SimpleConstants to avoid having to rescan the same constants all the -/// time. -static bool -isSimpleEnoughValueToCommitHelper(Constant *C, - SmallPtrSetImpl &SimpleConstants, - const DataLayout &DL) { - // Simple global addresses are supported, do not allow dllimport or - // thread-local globals. - if (auto *GV = dyn_cast(C)) - return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal(); - - // Simple integer, undef, constant aggregate zero, etc are all supported. - if (C->getNumOperands() == 0 || isa(C)) - return true; - - // Aggregate values are safe if all their elements are. - if (isa(C) || isa(C) || - isa(C)) { - for (Value *Op : C->operands()) - if (!isSimpleEnoughValueToCommit(cast(Op), SimpleConstants, DL)) - return false; - return true; - } - - // We don't know exactly what relocations are allowed in constant expressions, - // so we allow &global+constantoffset, which is safe and uniformly supported - // across targets. - ConstantExpr *CE = cast(C); - switch (CE->getOpcode()) { - case Instruction::BitCast: - // Bitcast is fine if the casted value is fine. - return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); - - case Instruction::IntToPtr: - case Instruction::PtrToInt: - // int <=> ptr is fine if the int type is the same size as the - // pointer type. - if (DL.getTypeSizeInBits(CE->getType()) != - DL.getTypeSizeInBits(CE->getOperand(0)->getType())) - return false; - return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); - - // GEP is fine if it is simple + constant offset. - case Instruction::GetElementPtr: - for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) - if (!isa(CE->getOperand(i))) - return false; - return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); - - case Instruction::Add: - // We allow simple+cst. - if (!isa(CE->getOperand(1))) - return false; - return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); - } - return false; -} - -static inline bool -isSimpleEnoughValueToCommit(Constant *C, - SmallPtrSetImpl &SimpleConstants, - const DataLayout &DL) { - // If we already checked this constant, we win. - if (!SimpleConstants.insert(C).second) - return true; - // Check the constant. - return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL); -} - - -/// Return true if this constant is simple enough for us to understand. In -/// particular, if it is a cast to anything other than from one pointer type to -/// another pointer type, we punt. We basically just support direct accesses to -/// globals and GEP's of globals. This should be kept up to date with -/// CommitValueTo. -static bool isSimpleEnoughPointerToCommit(Constant *C) { - // Conservatively, avoid aggregate types. This is because we don't - // want to worry about them partially overlapping other stores. - if (!cast(C->getType())->getElementType()->isSingleValueType()) - return false; - - if (GlobalVariable *GV = dyn_cast(C)) - // Do not allow weak/*_odr/linkonce linkage or external globals. - return GV->hasUniqueInitializer(); - - if (ConstantExpr *CE = dyn_cast(C)) { - // Handle a constantexpr gep. - if (CE->getOpcode() == Instruction::GetElementPtr && - isa(CE->getOperand(0)) && - cast(CE)->isInBounds()) { - GlobalVariable *GV = cast(CE->getOperand(0)); - // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or - // external globals. - if (!GV->hasUniqueInitializer()) - return false; - - // The first index must be zero. - ConstantInt *CI = dyn_cast(*std::next(CE->op_begin())); - if (!CI || !CI->isZero()) return false; - - // The remaining indices must be compile-time known integers within the - // notional bounds of the corresponding static array types. - if (!CE->isGEPWithNoNotionalOverIndexing()) - return false; - - return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); - - // A constantexpr bitcast from a pointer to another pointer is a no-op, - // and we know how to evaluate it by moving the bitcast from the pointer - // operand to the value operand. - } else if (CE->getOpcode() == Instruction::BitCast && - isa(CE->getOperand(0))) { - // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or - // external globals. - return cast(CE->getOperand(0))->hasUniqueInitializer(); - } - } - - return false; -} - /// Evaluate a piece of a constantexpr store into a global initializer. This /// returns 'Init' modified to reflect 'Val' stored into it. At this point, the /// GEP operands of Addr [0, OpNo) have been stepped into. @@ -2301,529 +2170,6 @@ GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2)); } -namespace { - -/// This class evaluates LLVM IR, producing the Constant representing each SSA -/// instruction. Changes to global variables are stored in a mapping that can -/// be iterated over after the evaluation is complete. Once an evaluation call -/// fails, the evaluation object should not be reused. -class Evaluator { -public: - Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI) - : DL(DL), TLI(TLI) { - ValueStack.emplace_back(); - } - - ~Evaluator() { - for (auto &Tmp : AllocaTmps) - // If there are still users of the alloca, the program is doing something - // silly, e.g. storing the address of the alloca somewhere and using it - // later. Since this is undefined, we'll just make it be null. - if (!Tmp->use_empty()) - Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType())); - } - - /// Evaluate a call to function F, returning true if successful, false if we - /// can't evaluate it. ActualArgs contains the formal arguments for the - /// function. - bool EvaluateFunction(Function *F, Constant *&RetVal, - const SmallVectorImpl &ActualArgs); - - /// Evaluate all instructions in block BB, returning true if successful, false - /// if we can't evaluate it. NewBB returns the next BB that control flows - /// into, or null upon return. - bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB); - - Constant *getVal(Value *V) { - if (Constant *CV = dyn_cast(V)) return CV; - Constant *R = ValueStack.back().lookup(V); - assert(R && "Reference to an uncomputed value!"); - return R; - } - - void setVal(Value *V, Constant *C) { - ValueStack.back()[V] = C; - } - - const DenseMap &getMutatedMemory() const { - return MutatedMemory; - } - - const SmallPtrSetImpl &getInvariants() const { - return Invariants; - } - -private: - Constant *ComputeLoadResult(Constant *P); - - /// As we compute SSA register values, we store their contents here. The back - /// of the deque contains the current function and the stack contains the - /// values in the calling frames. - std::deque> ValueStack; - - /// This is used to detect recursion. In pathological situations we could hit - /// exponential behavior, but at least there is nothing unbounded. - SmallVector CallStack; - - /// For each store we execute, we update this map. Loads check this to get - /// the most up-to-date value. If evaluation is successful, this state is - /// committed to the process. - DenseMap MutatedMemory; - - /// To 'execute' an alloca, we create a temporary global variable to represent - /// its body. This vector is needed so we can delete the temporary globals - /// when we are done. - SmallVector, 32> AllocaTmps; - - /// These global variables have been marked invariant by the static - /// constructor. - SmallPtrSet Invariants; - - /// These are constants we have checked and know to be simple enough to live - /// in a static initializer of a global. - SmallPtrSet SimpleConstants; - - const DataLayout &DL; - const TargetLibraryInfo *TLI; -}; - -} // anonymous namespace - -/// Return the value that would be computed by a load from P after the stores -/// reflected by 'memory' have been performed. If we can't decide, return null. -Constant *Evaluator::ComputeLoadResult(Constant *P) { - // If this memory location has been recently stored, use the stored value: it - // is the most up-to-date. - DenseMap::const_iterator I = MutatedMemory.find(P); - if (I != MutatedMemory.end()) return I->second; - - // Access it. - if (GlobalVariable *GV = dyn_cast(P)) { - if (GV->hasDefinitiveInitializer()) - return GV->getInitializer(); - return nullptr; - } - - // Handle a constantexpr getelementptr. - if (ConstantExpr *CE = dyn_cast(P)) - if (CE->getOpcode() == Instruction::GetElementPtr && - isa(CE->getOperand(0))) { - GlobalVariable *GV = cast(CE->getOperand(0)); - if (GV->hasDefinitiveInitializer()) - return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); - } - - return nullptr; // don't know how to evaluate. -} - -/// Evaluate all instructions in block BB, returning true if successful, false -/// if we can't evaluate it. NewBB returns the next BB that control flows into, -/// or null upon return. -bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, - BasicBlock *&NextBB) { - // This is the main evaluation loop. - while (1) { - Constant *InstResult = nullptr; - - DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n"); - - if (StoreInst *SI = dyn_cast(CurInst)) { - if (!SI->isSimple()) { - DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n"); - return false; // no volatile/atomic accesses. - } - Constant *Ptr = getVal(SI->getOperand(1)); - if (ConstantExpr *CE = dyn_cast(Ptr)) { - DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr); - Ptr = ConstantFoldConstantExpression(CE, DL, TLI); - DEBUG(dbgs() << "; To: " << *Ptr << "\n"); - } - if (!isSimpleEnoughPointerToCommit(Ptr)) { - // If this is too complex for us to commit, reject it. - DEBUG(dbgs() << "Pointer is too complex for us to evaluate store."); - return false; - } - - Constant *Val = getVal(SI->getOperand(0)); - - // If this might be too difficult for the backend to handle (e.g. the addr - // of one global variable divided by another) then we can't commit it. - if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) { - DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val - << "\n"); - return false; - } - - if (ConstantExpr *CE = dyn_cast(Ptr)) { - if (CE->getOpcode() == Instruction::BitCast) { - DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n"); - // If we're evaluating a store through a bitcast, then we need - // to pull the bitcast off the pointer type and push it onto the - // stored value. - Ptr = CE->getOperand(0); - - Type *NewTy = cast(Ptr->getType())->getElementType(); - - // In order to push the bitcast onto the stored value, a bitcast - // from NewTy to Val's type must be legal. If it's not, we can try - // introspecting NewTy to find a legal conversion. - while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) { - // If NewTy is a struct, we can convert the pointer to the struct - // into a pointer to its first member. - // FIXME: This could be extended to support arrays as well. - if (StructType *STy = dyn_cast(NewTy)) { - NewTy = STy->getTypeAtIndex(0U); - - IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32); - Constant *IdxZero = ConstantInt::get(IdxTy, 0, false); - Constant * const IdxList[] = {IdxZero, IdxZero}; - - Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList); - if (ConstantExpr *CE = dyn_cast(Ptr)) - Ptr = ConstantFoldConstantExpression(CE, DL, TLI); - - // If we can't improve the situation by introspecting NewTy, - // we have to give up. - } else { - DEBUG(dbgs() << "Failed to bitcast constant ptr, can not " - "evaluate.\n"); - return false; - } - } - - // If we found compatible types, go ahead and push the bitcast - // onto the stored value. - Val = ConstantExpr::getBitCast(Val, NewTy); - - DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n"); - } - } - - MutatedMemory[Ptr] = Val; - } else if (BinaryOperator *BO = dyn_cast(CurInst)) { - InstResult = ConstantExpr::get(BO->getOpcode(), - getVal(BO->getOperand(0)), - getVal(BO->getOperand(1))); - DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult - << "\n"); - } else if (CmpInst *CI = dyn_cast(CurInst)) { - InstResult = ConstantExpr::getCompare(CI->getPredicate(), - getVal(CI->getOperand(0)), - getVal(CI->getOperand(1))); - DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult - << "\n"); - } else if (CastInst *CI = dyn_cast(CurInst)) { - InstResult = ConstantExpr::getCast(CI->getOpcode(), - getVal(CI->getOperand(0)), - CI->getType()); - DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult - << "\n"); - } else if (SelectInst *SI = dyn_cast(CurInst)) { - InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)), - getVal(SI->getOperand(1)), - getVal(SI->getOperand(2))); - DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult - << "\n"); - } else if (auto *EVI = dyn_cast(CurInst)) { - InstResult = ConstantExpr::getExtractValue( - getVal(EVI->getAggregateOperand()), EVI->getIndices()); - DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult - << "\n"); - } else if (auto *IVI = dyn_cast(CurInst)) { - InstResult = ConstantExpr::getInsertValue( - getVal(IVI->getAggregateOperand()), - getVal(IVI->getInsertedValueOperand()), IVI->getIndices()); - DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult - << "\n"); - } else if (GetElementPtrInst *GEP = dyn_cast(CurInst)) { - Constant *P = getVal(GEP->getOperand(0)); - SmallVector GEPOps; - for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); - i != e; ++i) - GEPOps.push_back(getVal(*i)); - InstResult = - ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps, - cast(GEP)->isInBounds()); - DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult - << "\n"); - } else if (LoadInst *LI = dyn_cast(CurInst)) { - - if (!LI->isSimple()) { - DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n"); - return false; // no volatile/atomic accesses. - } - - Constant *Ptr = getVal(LI->getOperand(0)); - if (ConstantExpr *CE = dyn_cast(Ptr)) { - Ptr = ConstantFoldConstantExpression(CE, DL, TLI); - DEBUG(dbgs() << "Found a constant pointer expression, constant " - "folding: " << *Ptr << "\n"); - } - InstResult = ComputeLoadResult(Ptr); - if (!InstResult) { - DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load." - "\n"); - return false; // Could not evaluate load. - } - - DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n"); - } else if (AllocaInst *AI = dyn_cast(CurInst)) { - if (AI->isArrayAllocation()) { - DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n"); - return false; // Cannot handle array allocs. - } - Type *Ty = AI->getAllocatedType(); - AllocaTmps.push_back( - make_unique(Ty, false, GlobalValue::InternalLinkage, - UndefValue::get(Ty), AI->getName())); - InstResult = AllocaTmps.back().get(); - DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n"); - } else if (isa(CurInst) || isa(CurInst)) { - CallSite CS(&*CurInst); - - // Debug info can safely be ignored here. - if (isa(CS.getInstruction())) { - DEBUG(dbgs() << "Ignoring debug info.\n"); - ++CurInst; - continue; - } - - // Cannot handle inline asm. - if (isa(CS.getCalledValue())) { - DEBUG(dbgs() << "Found inline asm, can not evaluate.\n"); - return false; - } - - if (IntrinsicInst *II = dyn_cast(CS.getInstruction())) { - if (MemSetInst *MSI = dyn_cast(II)) { - if (MSI->isVolatile()) { - DEBUG(dbgs() << "Can not optimize a volatile memset " << - "intrinsic.\n"); - return false; - } - Constant *Ptr = getVal(MSI->getDest()); - Constant *Val = getVal(MSI->getValue()); - Constant *DestVal = ComputeLoadResult(getVal(Ptr)); - if (Val->isNullValue() && DestVal && DestVal->isNullValue()) { - // This memset is a no-op. - DEBUG(dbgs() << "Ignoring no-op memset.\n"); - ++CurInst; - continue; - } - } - - if (II->getIntrinsicID() == Intrinsic::lifetime_start || - II->getIntrinsicID() == Intrinsic::lifetime_end) { - DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n"); - ++CurInst; - continue; - } - - if (II->getIntrinsicID() == Intrinsic::invariant_start) { - // We don't insert an entry into Values, as it doesn't have a - // meaningful return value. - if (!II->use_empty()) { - DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n"); - return false; - } - ConstantInt *Size = cast(II->getArgOperand(0)); - Value *PtrArg = getVal(II->getArgOperand(1)); - Value *Ptr = PtrArg->stripPointerCasts(); - if (GlobalVariable *GV = dyn_cast(Ptr)) { - Type *ElemTy = GV->getValueType(); - if (!Size->isAllOnesValue() && - Size->getValue().getLimitedValue() >= - DL.getTypeStoreSize(ElemTy)) { - Invariants.insert(GV); - DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV - << "\n"); - } else { - DEBUG(dbgs() << "Found a global var, but can not treat it as an " - "invariant.\n"); - } - } - // Continue even if we do nothing. - ++CurInst; - continue; - } else if (II->getIntrinsicID() == Intrinsic::assume) { - DEBUG(dbgs() << "Skipping assume intrinsic.\n"); - ++CurInst; - continue; - } - - DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n"); - return false; - } - - // Resolve function pointers. - Function *Callee = dyn_cast(getVal(CS.getCalledValue())); - if (!Callee || Callee->mayBeOverridden()) { - DEBUG(dbgs() << "Can not resolve function pointer.\n"); - return false; // Cannot resolve. - } - - SmallVector Formals; - for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i) - Formals.push_back(getVal(*i)); - - if (Callee->isDeclaration()) { - // If this is a function we can constant fold, do it. - if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) { - InstResult = C; - DEBUG(dbgs() << "Constant folded function call. Result: " << - *InstResult << "\n"); - } else { - DEBUG(dbgs() << "Can not constant fold function call.\n"); - return false; - } - } else { - if (Callee->getFunctionType()->isVarArg()) { - DEBUG(dbgs() << "Can not constant fold vararg function call.\n"); - return false; - } - - Constant *RetVal = nullptr; - // Execute the call, if successful, use the return value. - ValueStack.emplace_back(); - if (!EvaluateFunction(Callee, RetVal, Formals)) { - DEBUG(dbgs() << "Failed to evaluate function.\n"); - return false; - } - ValueStack.pop_back(); - InstResult = RetVal; - - if (InstResult) { - DEBUG(dbgs() << "Successfully evaluated function. Result: " << - InstResult << "\n\n"); - } else { - DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n"); - } - } - } else if (isa(CurInst)) { - DEBUG(dbgs() << "Found a terminator instruction.\n"); - - if (BranchInst *BI = dyn_cast(CurInst)) { - if (BI->isUnconditional()) { - NextBB = BI->getSuccessor(0); - } else { - ConstantInt *Cond = - dyn_cast(getVal(BI->getCondition())); - if (!Cond) return false; // Cannot determine. - - NextBB = BI->getSuccessor(!Cond->getZExtValue()); - } - } else if (SwitchInst *SI = dyn_cast(CurInst)) { - ConstantInt *Val = - dyn_cast(getVal(SI->getCondition())); - if (!Val) return false; // Cannot determine. - NextBB = SI->findCaseValue(Val).getCaseSuccessor(); - } else if (IndirectBrInst *IBI = dyn_cast(CurInst)) { - Value *Val = getVal(IBI->getAddress())->stripPointerCasts(); - if (BlockAddress *BA = dyn_cast(Val)) - NextBB = BA->getBasicBlock(); - else - return false; // Cannot determine. - } else if (isa(CurInst)) { - NextBB = nullptr; - } else { - // invoke, unwind, resume, unreachable. - DEBUG(dbgs() << "Can not handle terminator."); - return false; // Cannot handle this terminator. - } - - // We succeeded at evaluating this block! - DEBUG(dbgs() << "Successfully evaluated block.\n"); - return true; - } else { - // Did not know how to evaluate this! - DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction." - "\n"); - return false; - } - - if (!CurInst->use_empty()) { - if (ConstantExpr *CE = dyn_cast(InstResult)) - InstResult = ConstantFoldConstantExpression(CE, DL, TLI); - - setVal(&*CurInst, InstResult); - } - - // If we just processed an invoke, we finished evaluating the block. - if (InvokeInst *II = dyn_cast(CurInst)) { - NextBB = II->getNormalDest(); - DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n"); - return true; - } - - // Advance program counter. - ++CurInst; - } -} - -/// Evaluate a call to function F, returning true if successful, false if we -/// can't evaluate it. ActualArgs contains the formal arguments for the -/// function. -bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal, - const SmallVectorImpl &ActualArgs) { - // Check to see if this function is already executing (recursion). If so, - // bail out. TODO: we might want to accept limited recursion. - if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end()) - return false; - - CallStack.push_back(F); - - // Initialize arguments to the incoming values specified. - unsigned ArgNo = 0; - for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; - ++AI, ++ArgNo) - setVal(&*AI, ActualArgs[ArgNo]); - - // ExecutedBlocks - We only handle non-looping, non-recursive code. As such, - // we can only evaluate any one basic block at most once. This set keeps - // track of what we have executed so we can detect recursive cases etc. - SmallPtrSet ExecutedBlocks; - - // CurBB - The current basic block we're evaluating. - BasicBlock *CurBB = &F->front(); - - BasicBlock::iterator CurInst = CurBB->begin(); - - while (1) { - BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings. - DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n"); - - if (!EvaluateBlock(CurInst, NextBB)) - return false; - - if (!NextBB) { - // Successfully running until there's no next block means that we found - // the return. Fill it the return value and pop the call stack. - ReturnInst *RI = cast(CurBB->getTerminator()); - if (RI->getNumOperands()) - RetVal = getVal(RI->getOperand(0)); - CallStack.pop_back(); - return true; - } - - // Okay, we succeeded in evaluating this control flow. See if we have - // executed the new block before. If so, we have a looping function, - // which we cannot evaluate in reasonable time. - if (!ExecutedBlocks.insert(NextBB).second) - return false; // looped! - - // Okay, we have never been in this block before. Check to see if there - // are any PHI nodes. If so, evaluate them with information about where - // we came from. - PHINode *PN = nullptr; - for (CurInst = NextBB->begin(); - (PN = dyn_cast(CurInst)); ++CurInst) - setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB))); - - // Advance to the next block. - CurBB = NextBB; - } -} - /// Evaluate static constructors in the function, if we can. Return true if we /// can, false otherwise. static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, Index: lib/Transforms/IPO/IPO.cpp =================================================================== --- lib/Transforms/IPO/IPO.cpp +++ lib/Transforms/IPO/IPO.cpp @@ -53,6 +53,7 @@ initializeEliminateAvailableExternallyPass(Registry); initializeSampleProfileLoaderPass(Registry); initializeFunctionImportPassPass(Registry); + initializeWholeProgramDevirtPass(Registry); } void LLVMInitializeIPO(LLVMPassRegistryRef R) { Index: lib/Transforms/IPO/LowerBitSets.cpp =================================================================== --- lib/Transforms/IPO/LowerBitSets.cpp +++ lib/Transforms/IPO/LowerBitSets.cpp @@ -920,7 +920,7 @@ bool LowerBitSets::buildBitSets() { Function *BitSetTestFunc = M->getFunction(Intrinsic::getName(Intrinsic::bitset_test)); - if (!BitSetTestFunc) + if (!BitSetTestFunc || BitSetTestFunc->use_empty()) return false; // Equivalence class set containing bitsets and the globals they reference. Index: lib/Transforms/IPO/PassManagerBuilder.cpp =================================================================== --- lib/Transforms/IPO/PassManagerBuilder.cpp +++ lib/Transforms/IPO/PassManagerBuilder.cpp @@ -637,6 +637,16 @@ PM.add(createJumpThreadingPass()); } +void PassManagerBuilder::addEarlyLTOOptimizationPasses( + legacy::PassManagerBase &PM) { + // Remove unused virtual tables to improve the quality of code generated by + // whole-program devirtualization and bitset lowering. + PM.add(createGlobalDCEPass()); + + // Apply whole-program devirtualization and virtual constant propagation. + PM.add(createWholeProgramDevirtPass()); +} + void PassManagerBuilder::addLateLTOOptimizationPasses( legacy::PassManagerBase &PM) { // Delete basic blocks, which optimization passes may have killed. @@ -661,6 +671,9 @@ if (VerifyInput) PM.add(createVerifierPass()); + if (OptLevel != 0) + addEarlyLTOOptimizationPasses(PM); + if (OptLevel > 1) addLTOOptimizationPasses(PM); Index: lib/Transforms/IPO/WholeProgramDevirt.cpp =================================================================== --- /dev/null +++ lib/Transforms/IPO/WholeProgramDevirt.cpp @@ -0,0 +1,680 @@ +//===- WholeProgramDevirt.cpp - Whole program virtual call optimization ---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This pass implements whole program optimization of virtual calls in cases +// where we know (via bitset information) that the list of callee is fixed. This +// includes the following: +// - Single implementation devirtualization: if a virtual call has a single +// possible callee, replace all calls with a direct call to that callee. +// - Virtual constant propagation: if the virtual function's return type is an +// integer <=64 bits and all possible callees are readnone, for each class and +// each list of constant arguments: evaluate the function, store the return +// value alongside the virtual table, and rewrite each virtual call as a load +// from the virtual table. +// - Uniform return value optimization: if the conditions for virtual constant +// propagation hold and each function returns the same constant value, replace +// each virtual call with that constant. +// - Unique return value optimization for i1 return values: if the conditions +// for virtual constant propagation hold and a single vtable's function +// returns 0, or a single vtable's function returns 1, replace each virtual +// call with a comparison of the vptr against that vtable's address. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/IPO/WholeProgramDevirt.h" +#include "llvm/Transforms/IPO.h" +#include "llvm/ADT/MapVector.h" +#include "llvm/IR/CallSite.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DataLayout.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/Module.h" +#include "llvm/Pass.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Transforms/Utils/Evaluator.h" + +#include + +using namespace llvm; +using namespace wholeprogramdevirt; + +#define DEBUG_TYPE "wholeprogramdevirt" + +// Find the minimum offset that we may store a value of size Size bits at. If +// IsAfter is set, look for an offset before the object, otherwise look for an +// offset after the object. +uint64_t +wholeprogramdevirt::findLowestOffset(ArrayRef Targets, + bool IsAfter, uint64_t Size) { + // Find a minimum offset taking into account only vtable sizes. + uint64_t MinByte = 0; + for (const VirtualCallTarget &Target : Targets) { + if (IsAfter) + MinByte = std::max(MinByte, Target.minAfterBytes()); + else + MinByte = std::max(MinByte, Target.minBeforeBytes()); + } + + // Build a vector of arrays of bytes covering, for each target, a slice of the + // used region (see AccumBitVector::BytesUsed above) starting at MinByte. + // Effectively, this aligns the used regions to start at MinByte. + // + // In this example, A, B and C are vtables, # is a byte already allocated for + // a virtual function pointer, AAAA... (etc.) are the used regions for the + // vtables and Offset(X) is the value computed for the Offset variable below + // for X. + // + // Offset(A) + // | | + // |MinByte + // A: ################AAAAAAAA|AAAAAAAA + // B: ########BBBBBBBBBBBBBBBB|BBBB + // C: ########################|CCCCCCCCCCCCCCCC + // | Offset(B) | + // + // This code produces the slices of A, B and C that appear after the divider + // at MinByte. + std::vector> Used; + for (const VirtualCallTarget &Target : Targets) { + ArrayRef VTUsed = IsAfter ? Target.BS->Bits->After.BytesUsed + : Target.BS->Bits->Before.BytesUsed; + uint64_t Offset = IsAfter ? MinByte - Target.minAfterBytes() + : MinByte - Target.minBeforeBytes(); + + // Disregard used regions that are smaller than Offset. These are + // effectively all-free regions that do not need to be checked. + if (VTUsed.size() > Offset) + Used.push_back(VTUsed.slice(Offset)); + } + + if (Size == 1) { + // Find a free bit in each member of Used. + for (unsigned I = 0;; ++I) { + uint8_t BitsUsed = 0; + for (auto &&B : Used) + if (I < B.size()) + BitsUsed |= B[I]; + if (BitsUsed != 0xff) + return (MinByte + I) * 8 + + countTrailingZeros(uint8_t(~BitsUsed), ZB_Undefined); + } + } else { + // Find a free (Size/8) byte region in each member of Used. + // FIXME: see if alignment helps. + for (unsigned I = 0;; ++I) { + for (auto &&B : Used) { + unsigned Byte = 0; + while (I + Byte < B.size() && Byte < Size / 8) { + if (B[I + Byte]) + goto NextI; + ++Byte; + } + } + return (MinByte + I) * 8; + NextI:; + } + } +} + +void wholeprogramdevirt::setBeforeReturnValues( + MutableArrayRef Targets, uint64_t AllocBefore, + unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { + if (BitWidth == 1) + OffsetByte = -(AllocBefore / 8 + 1); + else + OffsetByte = -((AllocBefore + 7) / 8 + (BitWidth + 7) / 8); + OffsetBit = AllocBefore % 8; + + for (VirtualCallTarget &Target : Targets) { + if (BitWidth == 1) + Target.setBeforeBit(AllocBefore); + else + Target.setBeforeBytes(AllocBefore, (BitWidth + 7) / 8); + } +} + +void wholeprogramdevirt::setAfterReturnValues( + MutableArrayRef Targets, uint64_t AllocAfter, + unsigned BitWidth, int64_t &OffsetByte, uint64_t &OffsetBit) { + if (BitWidth == 1) + OffsetByte = AllocAfter / 8; + else + OffsetByte = (AllocAfter + 7) / 8; + OffsetBit = AllocAfter % 8; + + for (VirtualCallTarget &Target : Targets) { + if (BitWidth == 1) + Target.setAfterBit(AllocAfter); + else + Target.setAfterBytes(AllocAfter, (BitWidth + 7) / 8); + } +} + +VirtualCallTarget::VirtualCallTarget(Function *Fn, const BitSetInfo *BS) + : Fn(Fn), BS(BS), + IsBigEndian(Fn->getParent()->getDataLayout().isBigEndian()) {} + +namespace { + +// A slot in a set of virtual tables. The BitSetID identifies the set of virtual +// tables, and the ByteOffset is the offset in bytes from the address point to +// the virtual function pointer. +struct VTableSlot { + Metadata *BitSetID; + uint64_t ByteOffset; + bool operator<(const VTableSlot &other) const { + return BitSetID < other.BitSetID || + (BitSetID == other.BitSetID && ByteOffset < other.ByteOffset); + } +}; + +// A virtual call site. VTable is the loaded virtual table pointer, and CS is +// the indirect virtual call. +struct VirtualCallSite { + Value *VTable; + CallSite CS; + + void replaceAndErase(Value *New) { + CS->replaceAllUsesWith(New); + if (auto II = dyn_cast(CS.getInstruction())) { + BranchInst::Create(II->getUnwindDest(), CS.getInstruction()); + II->getUnwindDest()->removePredecessor(II->getParent()); + } + CS->eraseFromParent(); + } +}; + +struct SlotWithCallSites { + VTableSlot Slot; + std::vector CallSites; +}; + +struct WholeProgramDevirt : public ModulePass { + static char ID; + Module *M; + + std::vector CallSlots; + std::map CallSlotOffsetsPlusOne; + + WholeProgramDevirt() : ModulePass(ID) { + initializeWholeProgramDevirtPass(*PassRegistry::getPassRegistry()); + } + void addCallToSlot(VTableSlot Slot, Value *VTable, CallSite CS); + void findLoadCallsAtConstantOffset(Metadata *BitSet, Value *Ptr, + uint64_t Offset, Value *VTable); + void findCallsAtConstantOffset(Metadata *BitSet, Value *Ptr, uint64_t Offset, + Value *VTable); + bool runOnModule(Module &M); +}; + +} // anonymous namespace + +INITIALIZE_PASS_BEGIN(WholeProgramDevirt, "wholeprogramdevirt", + "Whole program devirtualization", false, false) +INITIALIZE_PASS_END(WholeProgramDevirt, "wholeprogramdevirt", + "Whole program devirtualization", false, false) +char WholeProgramDevirt::ID = 0; + +ModulePass *llvm::createWholeProgramDevirtPass() { + return new WholeProgramDevirt; +} + +void WholeProgramDevirt::addCallToSlot(VTableSlot Slot, Value *VTable, + CallSite CS) { + size_t &OffsetPlusOne = CallSlotOffsetsPlusOne[Slot]; + if (!OffsetPlusOne) { + CallSlots.emplace_back(); + CallSlots.back().Slot = Slot; + OffsetPlusOne = CallSlots.size(); + } + CallSlots[OffsetPlusOne - 1].CallSites.push_back({VTable, CS}); +} + +// Search for virtual calls that call FPtr and add them to CallSlots. +void WholeProgramDevirt::findCallsAtConstantOffset(Metadata *BitSet, + Value *FPtr, + uint64_t Offset, + Value *VTable) { + for (const Use &U : FPtr->uses()) { + Value *User = U.getUser(); + if (isa(User)) { + findCallsAtConstantOffset(BitSet, User, Offset, VTable); + } else if (auto CI = dyn_cast(User)) { + addCallToSlot({BitSet, Offset}, VTable, CI); + } else if (auto II = dyn_cast(User)) { + addCallToSlot({BitSet, Offset}, VTable, II); + } + } +} + +// Search for virtual calls that load from VPtr and add them to CallSlots. +void WholeProgramDevirt::findLoadCallsAtConstantOffset(Metadata *BitSet, + Value *VPtr, + uint64_t Offset, + Value *VTable) { + for (const Use &U : VPtr->uses()) { + Value *User = U.getUser(); + if (isa(User)) { + findLoadCallsAtConstantOffset(BitSet, User, Offset, VTable); + } else if (isa(User)) { + findCallsAtConstantOffset(BitSet, User, Offset, VTable); + } else if (auto GEP = dyn_cast(User)) { + // Take into account the GEP offset. + if (GEP->hasAllConstantIndices() && VPtr == GEP->getPointerOperand()) { + SmallVector Indices(GEP->op_begin() + 1, GEP->op_end()); + uint64_t GEPOffset = M->getDataLayout().getIndexedOffsetInType( + GEP->getSourceElementType(), Indices); + findLoadCallsAtConstantOffset(BitSet, User, Offset + GEPOffset, VTable); + } + } + } +} + +bool WholeProgramDevirt::runOnModule(Module &Mod) { + M = &Mod; + auto Int8Ty = Type::getInt8Ty(M->getContext()); + auto Int8PtrTy = Type::getInt8PtrTy(M->getContext()); + auto Int32Ty = Type::getInt32Ty(M->getContext()); + + Function *BitSetTestFunc = + M->getFunction(Intrinsic::getName(Intrinsic::bitset_test)); + if (!BitSetTestFunc || BitSetTestFunc->use_empty()) + return false; + + Function *AssumeFunc = M->getFunction(Intrinsic::getName(Intrinsic::assume)); + if (!AssumeFunc || AssumeFunc->use_empty()) + return false; + + // Find all virtual calls via a virtual table pointer %p under an assumption + // of the form llvm.assume(llvm.bitset.test(%p, %md)). This indicates that %p + // points to a vtable in the bitset %md. Group calls by (bitset, offset) pair + // (effectively the identity of the virtual function) and store to + // CallsBySlot. + std::set SeenPtrs; + for (auto I = BitSetTestFunc->use_begin(), E = BitSetTestFunc->use_end(); + I != E;) { + auto CI = cast(I->getUser()); + ++I; + + auto BitSetMDVal = dyn_cast(CI->getArgOperand(1)); + if (!BitSetMDVal) + report_fatal_error( + "Second argument of llvm.bitset.test must be metadata"); + auto BitSet = BitSetMDVal->getMetadata(); + + // Find llvm.assume intrinsics for this llvm.bitset.test call. + llvm::SmallVector Assumes; + for (const Use &CIU : CI->uses()) { + auto AssumeCI = cast(CIU.getUser()); + if (AssumeCI->getCalledValue() == AssumeFunc) + Assumes.push_back(AssumeCI); + } + + // If we found any, search for virtual calls based on %p and add them to + // CallsBySlot. + if (!Assumes.empty()) { + Value *Ptr = CI->getArgOperand(0)->stripPointerCasts(); + if (SeenPtrs.insert(Ptr).second) + findLoadCallsAtConstantOffset(BitSet, Ptr, 0, CI->getArgOperand(0)); + } + + // We no longer need the assumes or the bitset test. + for (auto Assume : Assumes) + Assume->eraseFromParent(); + if (CI->use_empty()) + CI->eraseFromParent(); + } + + // Rebuild llvm.bitsets metadata into a map for easy lookup. + DenseMap> BitSets; + NamedMDNode *BitSetNM = M->getNamedMetadata("llvm.bitsets"); + std::vector Bits; + if (BitSetNM) { + DenseMap GVToBits; + Bits.reserve(BitSetNM->getNumOperands()); + for (auto Op : BitSetNM->operands()) { + if (!Op->getOperand(1)) + continue; + auto BitSetID = Op->getOperand(0).get(); + + Constant *OpConst = + cast(Op->getOperand(1))->getValue(); + if (auto GA = dyn_cast(OpConst)) + OpConst = GA->getAliasee(); + auto OpGlobal = dyn_cast(OpConst); + if (!OpGlobal) + continue; + + uint64_t Offset = + cast( + cast(Op->getOperand(2))->getValue()) + ->getZExtValue(); + + VTableBits *&BitsPtr = GVToBits[OpGlobal]; + if (!BitsPtr) { + Bits.emplace_back(); + Bits.back().GV = OpGlobal; + Bits.back().ObjectSize = M->getDataLayout().getTypeAllocSize( + OpGlobal->getInitializer()->getType()); + BitsPtr = &Bits.back(); + } + BitSets[BitSetID].insert({BitsPtr, Offset}); + } + } + + // For each (bitset, offset) pair: + for (SlotWithCallSites &S : CallSlots) { + // Search each of the vtables in the bitset for the virtual function + // implementation at offset Offset, and add to TargetsForSlot. + std::vector TargetsForSlot; + for (const BitSetInfo &BS : BitSets[S.Slot.BitSetID]) { + auto VTableTy = + dyn_cast(BS.Bits->GV->getInitializer()->getType()); + if (!VTableTy) { + TargetsForSlot.clear(); + break; + } + uint64_t ElemSize = + M->getDataLayout().getTypeAllocSize(VTableTy->getElementType()); + uint64_t GlobalSlotOffset = BS.Offset + S.Slot.ByteOffset; + if (GlobalSlotOffset % ElemSize != 0) { + TargetsForSlot.clear(); + break; + } + auto CA = dyn_cast(BS.Bits->GV->getInitializer()); + if (!CA) { + TargetsForSlot.clear(); + break; + } + unsigned Op = GlobalSlotOffset / ElemSize; + if (Op >= CA->getNumOperands()) { + TargetsForSlot.clear(); + break; + } + auto Fn = dyn_cast(CA->getOperand(Op)->stripPointerCasts()); + if (!Fn) { + TargetsForSlot.clear(); + break; + } + // We can disregard __cxa_pure_virtual as a possible call target, as calls + // to pure virtuals are UB. + if (Fn->getName() == "__cxa_pure_virtual") + continue; + TargetsForSlot.push_back({Fn, &BS}); + } + + // Give up if we couldn't find any targets or if one of the vtables didn't + // look correct. + if (TargetsForSlot.empty()) + continue; + + // First, try single-implementation devirtualization: see if the program + // contains a single implementation of this virtual function. + Function *UniqueFn = TargetsForSlot[0].Fn; + for (auto &&Target : TargetsForSlot) { + if (UniqueFn != Target.Fn) { + UniqueFn = 0; + break; + } + } + + // If so, update each call site to call that implementation directly. + if (UniqueFn) { + for (auto &&VCallSite : S.CallSites) { + VCallSite.CS.setCalledFunction(ConstantExpr::getBitCast( + UniqueFn, VCallSite.CS.getCalledValue()->getType())); + } + continue; + } + + // Next, try virtual constant propagation. This only works if the function + // returns an integer. + auto RetType = dyn_cast(TargetsForSlot[0].Fn->getReturnType()); + if (!RetType) + continue; + unsigned BitWidth = RetType->getBitWidth(); + if (BitWidth > 64) + continue; + + // Make sure that each function does not access memory, takes at least one + // argument, does not use its first argument (which we assume is 'this'), + // and has the same return type. + bool AllFunctionsValid = true; + for (VirtualCallTarget &Target : TargetsForSlot) { + if (!Target.Fn->doesNotAccessMemory() || + Target.Fn->arg_empty() || + !Target.Fn->arg_begin()->use_empty() || + Target.Fn->getReturnType() != RetType) { + AllFunctionsValid = false; + break; + } + } + + if (!AllFunctionsValid) + continue; + + // Group call sites by the list of constant arguments they pass. + // The comparator ensures deterministic ordering. + struct ByAPIntValue { + bool operator()(const std::vector &A, + const std::vector &B) const { + return std::lexicographical_compare( + A.begin(), A.end(), B.begin(), B.end(), + [](ConstantInt *AI, ConstantInt *BI) { + return AI->getValue().ult(BI->getValue()); + }); + } + }; + std::map, std::vector, + ByAPIntValue> + VCallSitesByConstantArg; + for (auto &&VCallSite : S.CallSites) { + std::vector Args; + if (VCallSite.CS.getType() != RetType) + continue; + for (auto &&Arg : + make_range(VCallSite.CS.arg_begin() + 1, VCallSite.CS.arg_end())) { + if (!isa(Arg)) + break; + Args.push_back(cast(&Arg)); + } + if (Args.size() + 1 != VCallSite.CS.arg_size()) + continue; + + VCallSitesByConstantArg[Args].push_back(VCallSite); + } + + for (auto &&CSByConstantArg : VCallSitesByConstantArg) { + // Evaluate each function and store the result in each target's RetVal + // field. + bool AllTargetsValid = true; + for (VirtualCallTarget &Target : TargetsForSlot) { + if (Target.Fn->arg_size() != CSByConstantArg.first.size() + 1) { + AllTargetsValid = false; + break; + } + for (unsigned I = 0; I != CSByConstantArg.first.size(); ++I) { + if (Target.Fn->getFunctionType()->getParamType(I + 1) != + CSByConstantArg.first[I]->getType()) { + AllTargetsValid = false; + break; + } + } + if (!AllTargetsValid) + break; + + llvm::Evaluator Eval(M->getDataLayout(), nullptr); + llvm::Constant *RetVal; + llvm::SmallVector Args; + Args.push_back(llvm::Constant::getNullValue( + Target.Fn->getFunctionType()->getParamType(0))); + Args.insert(Args.end(), CSByConstantArg.first.begin(), + CSByConstantArg.first.end()); + if (!Eval.EvaluateFunction(Target.Fn, RetVal, Args) || + !isa(RetVal)) { + AllTargetsValid = false; + break; + } + Target.RetVal = cast(RetVal)->getZExtValue(); + } + + if (!AllTargetsValid) + continue; + + // Uniform return value optimization. If all functions return the same + // constant, replace all calls with that constant. + uint64_t TheRetVal = TargetsForSlot[0].RetVal; + bool UniformRetVals = true; + for (VirtualCallTarget &Target : TargetsForSlot) { + if (Target.RetVal != TheRetVal) { + UniformRetVals = false; + break; + } + } + + if (UniformRetVals) { + auto TheRetValConst = ConstantInt::get(RetType, TheRetVal); + for (auto Call : CSByConstantArg.second) + Call.replaceAndErase(TheRetValConst); + continue; + } + + // Try the unique return value optimization. IsOne controls whether we + // look for a 0 or a 1. + auto tryUniqueValueOpt = [&](bool IsOne) { + const BitSetInfo *UniqueBitSet = 0; + for (VirtualCallTarget &Target : TargetsForSlot) { + if (Target.RetVal == IsOne ? 1 : 0) { + if (UniqueBitSet) + return false; + UniqueBitSet = Target.BS; + } + } + // We should have found a unique bit set or bailed out by now. We already + // checked for a uniform return value above. + assert(UniqueBitSet); + // Replace each call with the comparison. + for (auto Call : CSByConstantArg.second) { + IRBuilder<> B(Call.CS.getInstruction()); + Value *OneAddr = B.CreateBitCast(UniqueBitSet->Bits->GV, Int8PtrTy); + OneAddr = B.CreateConstGEP1_64(OneAddr, UniqueBitSet->Offset); + Value *Cmp = B.CreateICmp(IsOne ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, + Call.VTable, OneAddr); + Call.replaceAndErase(Cmp); + } + return true; + }; + + if (BitWidth == 1) { + if (tryUniqueValueOpt(true)) + continue; + if (tryUniqueValueOpt(false)) + continue; + } + + // Find an allocation offset in bits in all vtables in the bitset. + uint64_t AllocBefore = + findLowestOffset(TargetsForSlot, /*IsAfter=*/false, BitWidth); + uint64_t AllocAfter = + findLowestOffset(TargetsForSlot, /*IsAfter=*/true, BitWidth); + + // Calculate the total amount of padding needed to store a value at both + // ends of the object. + uint64_t TotalPaddingBefore = 0, TotalPaddingAfter = 0; + for (auto &&Target : TargetsForSlot) { + TotalPaddingBefore += std::max( + (AllocBefore + 7) / 8 - Target.allocatedBeforeBytes() - 1, 0); + TotalPaddingAfter += std::max( + (AllocAfter + 7) / 8 - Target.allocatedAfterBytes() - 1, 0); + } + + // If the amount of padding is too large, give up. + // FIXME: do something smarter here. + if (std::min(TotalPaddingBefore, TotalPaddingAfter) > 128) + continue; + + // Calculate the offset to the value as a (possibly negative) byte offset + // and (if applicable) a bit offset, and store the values in the targets. + int64_t OffsetByte; + uint64_t OffsetBit; + if (TotalPaddingBefore <= TotalPaddingAfter) + setBeforeReturnValues(TargetsForSlot, AllocBefore, BitWidth, OffsetByte, + OffsetBit); + else + setAfterReturnValues(TargetsForSlot, AllocAfter, BitWidth, OffsetByte, + OffsetBit); + + // Rewrite each call to a load from OffsetByte/OffsetBit. + for (auto Call : CSByConstantArg.second) { + IRBuilder<> B(Call.CS.getInstruction()); + Value *Addr = B.CreateConstGEP1_64(Call.VTable, OffsetByte); + if (BitWidth == 1) { + Value *Bits = B.CreateLoad(Addr); + Value *Bit = ConstantInt::get(Int8Ty, 1 << OffsetBit); + Value *BitsAndBit = B.CreateAnd(Bits, Bit); + auto IsBitSet = + B.CreateICmpNE(BitsAndBit, ConstantInt::get(Int8Ty, 0)); + Call.replaceAndErase(IsBitSet); + } else { + IntegerType *IntTy = Type::getIntNTy(M->getContext(), BitWidth); + Value *ValAddr = B.CreateBitCast(Addr, IntTy->getPointerTo()); + Value *Val = B.CreateLoad(IntTy, ValAddr); + Call.replaceAndErase(Val); + } + } + } + } + + // Rebuild each global we touched as part of virtual constant propagation to + // include the before and after bytes. + for (VTableBits &B : Bits) { + if (B.Before.Bytes.empty() && B.After.Bytes.empty()) + continue; + + // Align each byte array to pointer width. + unsigned PointerSize = M->getDataLayout().getPointerSize(); + B.Before.Bytes.resize(alignTo(B.Before.Bytes.size(), PointerSize)); + B.After.Bytes.resize(alignTo(B.After.Bytes.size(), PointerSize)); + + // Before was stored in reverse order; flip it now. + for (unsigned I = 0; I != B.Before.Bytes.size() / 2; ++I) + std::swap(B.Before.Bytes[I], + B.Before.Bytes[B.Before.Bytes.size() - 1 - I]); + + // Build an anonymous global containing the before bytes, followed by the + // original initializer, followed by the after bytes. + auto NewInit = ConstantStruct::getAnon( + {ConstantDataArray::get(M->getContext(), B.Before.Bytes), + B.GV->getInitializer(), + ConstantDataArray::get(M->getContext(), B.After.Bytes)}); + auto NewGV = + new GlobalVariable(*M, NewInit->getType(), B.GV->isConstant(), + GlobalVariable::PrivateLinkage, NewInit, "", B.GV); + NewGV->setComdat(B.GV->getComdat()); + + // Build an alias named after the original global, pointing at the second + // element (the original initializer). + auto Alias = GlobalAlias::create( + B.GV->getInitializer()->getType(), 0, B.GV->getLinkage(), "", + ConstantExpr::getGetElementPtr( + NewInit->getType(), NewGV, + ArrayRef{ConstantInt::get(Int32Ty, 0), + ConstantInt::get(Int32Ty, 1)}), + M); + Alias->setVisibility(B.GV->getVisibility()); + Alias->takeName(B.GV); + + B.GV->replaceAllUsesWith(Alias); + B.GV->eraseFromParent(); + } + + return true; +} Index: lib/Transforms/Utils/CMakeLists.txt =================================================================== --- lib/Transforms/Utils/CMakeLists.txt +++ lib/Transforms/Utils/CMakeLists.txt @@ -11,6 +11,7 @@ CodeExtractor.cpp CtorUtils.cpp DemoteRegToStack.cpp + Evaluator.cpp FlattenCFG.cpp GlobalStatus.cpp InlineFunction.cpp Index: lib/Transforms/Utils/Evaluator.cpp =================================================================== --- /dev/null +++ lib/Transforms/Utils/Evaluator.cpp @@ -0,0 +1,596 @@ +//===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Function evaluator for LLVM IR. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/Utils/Evaluator.h" +#include "llvm/Analysis/ConstantFolding.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/CallSite.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/DiagnosticPrinter.h" +#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/Operator.h" +#include "llvm/Support/Debug.h" + +#define DEBUG_TYPE "evaluator" + +using namespace llvm; + +static inline bool +isSimpleEnoughValueToCommit(Constant *C, + SmallPtrSetImpl &SimpleConstants, + const DataLayout &DL); + +/// Return true if the specified constant can be handled by the code generator. +/// We don't want to generate something like: +/// void *X = &X/42; +/// because the code generator doesn't have a relocation that can handle that. +/// +/// This function should be called if C was not found (but just got inserted) +/// in SimpleConstants to avoid having to rescan the same constants all the +/// time. +static bool +isSimpleEnoughValueToCommitHelper(Constant *C, + SmallPtrSetImpl &SimpleConstants, + const DataLayout &DL) { + // Simple global addresses are supported, do not allow dllimport or + // thread-local globals. + if (auto *GV = dyn_cast(C)) + return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal(); + + // Simple integer, undef, constant aggregate zero, etc are all supported. + if (C->getNumOperands() == 0 || isa(C)) + return true; + + // Aggregate values are safe if all their elements are. + if (isa(C) || isa(C) || + isa(C)) { + for (Value *Op : C->operands()) + if (!isSimpleEnoughValueToCommit(cast(Op), SimpleConstants, DL)) + return false; + return true; + } + + // We don't know exactly what relocations are allowed in constant expressions, + // so we allow &global+constantoffset, which is safe and uniformly supported + // across targets. + ConstantExpr *CE = cast(C); + switch (CE->getOpcode()) { + case Instruction::BitCast: + // Bitcast is fine if the casted value is fine. + return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); + + case Instruction::IntToPtr: + case Instruction::PtrToInt: + // int <=> ptr is fine if the int type is the same size as the + // pointer type. + if (DL.getTypeSizeInBits(CE->getType()) != + DL.getTypeSizeInBits(CE->getOperand(0)->getType())) + return false; + return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); + + // GEP is fine if it is simple + constant offset. + case Instruction::GetElementPtr: + for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) + if (!isa(CE->getOperand(i))) + return false; + return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); + + case Instruction::Add: + // We allow simple+cst. + if (!isa(CE->getOperand(1))) + return false; + return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); + } + return false; +} + +static inline bool +isSimpleEnoughValueToCommit(Constant *C, + SmallPtrSetImpl &SimpleConstants, + const DataLayout &DL) { + // If we already checked this constant, we win. + if (!SimpleConstants.insert(C).second) + return true; + // Check the constant. + return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL); +} + +/// Return true if this constant is simple enough for us to understand. In +/// particular, if it is a cast to anything other than from one pointer type to +/// another pointer type, we punt. We basically just support direct accesses to +/// globals and GEP's of globals. This should be kept up to date with +/// CommitValueTo. +static bool isSimpleEnoughPointerToCommit(Constant *C) { + // Conservatively, avoid aggregate types. This is because we don't + // want to worry about them partially overlapping other stores. + if (!cast(C->getType())->getElementType()->isSingleValueType()) + return false; + + if (GlobalVariable *GV = dyn_cast(C)) + // Do not allow weak/*_odr/linkonce linkage or external globals. + return GV->hasUniqueInitializer(); + + if (ConstantExpr *CE = dyn_cast(C)) { + // Handle a constantexpr gep. + if (CE->getOpcode() == Instruction::GetElementPtr && + isa(CE->getOperand(0)) && + cast(CE)->isInBounds()) { + GlobalVariable *GV = cast(CE->getOperand(0)); + // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or + // external globals. + if (!GV->hasUniqueInitializer()) + return false; + + // The first index must be zero. + ConstantInt *CI = dyn_cast(*std::next(CE->op_begin())); + if (!CI || !CI->isZero()) return false; + + // The remaining indices must be compile-time known integers within the + // notional bounds of the corresponding static array types. + if (!CE->isGEPWithNoNotionalOverIndexing()) + return false; + + return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); + + // A constantexpr bitcast from a pointer to another pointer is a no-op, + // and we know how to evaluate it by moving the bitcast from the pointer + // operand to the value operand. + } else if (CE->getOpcode() == Instruction::BitCast && + isa(CE->getOperand(0))) { + // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or + // external globals. + return cast(CE->getOperand(0))->hasUniqueInitializer(); + } + } + + return false; +} + +/// Return the value that would be computed by a load from P after the stores +/// reflected by 'memory' have been performed. If we can't decide, return null. +Constant *Evaluator::ComputeLoadResult(Constant *P) { + // If this memory location has been recently stored, use the stored value: it + // is the most up-to-date. + DenseMap::const_iterator I = MutatedMemory.find(P); + if (I != MutatedMemory.end()) return I->second; + + // Access it. + if (GlobalVariable *GV = dyn_cast(P)) { + if (GV->hasDefinitiveInitializer()) + return GV->getInitializer(); + return nullptr; + } + + // Handle a constantexpr getelementptr. + if (ConstantExpr *CE = dyn_cast(P)) + if (CE->getOpcode() == Instruction::GetElementPtr && + isa(CE->getOperand(0))) { + GlobalVariable *GV = cast(CE->getOperand(0)); + if (GV->hasDefinitiveInitializer()) + return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); + } + + return nullptr; // don't know how to evaluate. +} + +/// Evaluate all instructions in block BB, returning true if successful, false +/// if we can't evaluate it. NewBB returns the next BB that control flows into, +/// or null upon return. +bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, + BasicBlock *&NextBB) { + // This is the main evaluation loop. + while (1) { + Constant *InstResult = nullptr; + + DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n"); + + if (StoreInst *SI = dyn_cast(CurInst)) { + if (!SI->isSimple()) { + DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n"); + return false; // no volatile/atomic accesses. + } + Constant *Ptr = getVal(SI->getOperand(1)); + if (ConstantExpr *CE = dyn_cast(Ptr)) { + DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr); + Ptr = ConstantFoldConstantExpression(CE, DL, TLI); + DEBUG(dbgs() << "; To: " << *Ptr << "\n"); + } + if (!isSimpleEnoughPointerToCommit(Ptr)) { + // If this is too complex for us to commit, reject it. + DEBUG(dbgs() << "Pointer is too complex for us to evaluate store."); + return false; + } + + Constant *Val = getVal(SI->getOperand(0)); + + // If this might be too difficult for the backend to handle (e.g. the addr + // of one global variable divided by another) then we can't commit it. + if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) { + DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val + << "\n"); + return false; + } + + if (ConstantExpr *CE = dyn_cast(Ptr)) { + if (CE->getOpcode() == Instruction::BitCast) { + DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n"); + // If we're evaluating a store through a bitcast, then we need + // to pull the bitcast off the pointer type and push it onto the + // stored value. + Ptr = CE->getOperand(0); + + Type *NewTy = cast(Ptr->getType())->getElementType(); + + // In order to push the bitcast onto the stored value, a bitcast + // from NewTy to Val's type must be legal. If it's not, we can try + // introspecting NewTy to find a legal conversion. + while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) { + // If NewTy is a struct, we can convert the pointer to the struct + // into a pointer to its first member. + // FIXME: This could be extended to support arrays as well. + if (StructType *STy = dyn_cast(NewTy)) { + NewTy = STy->getTypeAtIndex(0U); + + IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32); + Constant *IdxZero = ConstantInt::get(IdxTy, 0, false); + Constant * const IdxList[] = {IdxZero, IdxZero}; + + Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList); + if (ConstantExpr *CE = dyn_cast(Ptr)) + Ptr = ConstantFoldConstantExpression(CE, DL, TLI); + + // If we can't improve the situation by introspecting NewTy, + // we have to give up. + } else { + DEBUG(dbgs() << "Failed to bitcast constant ptr, can not " + "evaluate.\n"); + return false; + } + } + + // If we found compatible types, go ahead and push the bitcast + // onto the stored value. + Val = ConstantExpr::getBitCast(Val, NewTy); + + DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n"); + } + } + + MutatedMemory[Ptr] = Val; + } else if (BinaryOperator *BO = dyn_cast(CurInst)) { + InstResult = ConstantExpr::get(BO->getOpcode(), + getVal(BO->getOperand(0)), + getVal(BO->getOperand(1))); + DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult + << "\n"); + } else if (CmpInst *CI = dyn_cast(CurInst)) { + InstResult = ConstantExpr::getCompare(CI->getPredicate(), + getVal(CI->getOperand(0)), + getVal(CI->getOperand(1))); + DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult + << "\n"); + } else if (CastInst *CI = dyn_cast(CurInst)) { + InstResult = ConstantExpr::getCast(CI->getOpcode(), + getVal(CI->getOperand(0)), + CI->getType()); + DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult + << "\n"); + } else if (SelectInst *SI = dyn_cast(CurInst)) { + InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)), + getVal(SI->getOperand(1)), + getVal(SI->getOperand(2))); + DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult + << "\n"); + } else if (auto *EVI = dyn_cast(CurInst)) { + InstResult = ConstantExpr::getExtractValue( + getVal(EVI->getAggregateOperand()), EVI->getIndices()); + DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult + << "\n"); + } else if (auto *IVI = dyn_cast(CurInst)) { + InstResult = ConstantExpr::getInsertValue( + getVal(IVI->getAggregateOperand()), + getVal(IVI->getInsertedValueOperand()), IVI->getIndices()); + DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult + << "\n"); + } else if (GetElementPtrInst *GEP = dyn_cast(CurInst)) { + Constant *P = getVal(GEP->getOperand(0)); + SmallVector GEPOps; + for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); + i != e; ++i) + GEPOps.push_back(getVal(*i)); + InstResult = + ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps, + cast(GEP)->isInBounds()); + DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult + << "\n"); + } else if (LoadInst *LI = dyn_cast(CurInst)) { + + if (!LI->isSimple()) { + DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n"); + return false; // no volatile/atomic accesses. + } + + Constant *Ptr = getVal(LI->getOperand(0)); + if (ConstantExpr *CE = dyn_cast(Ptr)) { + Ptr = ConstantFoldConstantExpression(CE, DL, TLI); + DEBUG(dbgs() << "Found a constant pointer expression, constant " + "folding: " << *Ptr << "\n"); + } + InstResult = ComputeLoadResult(Ptr); + if (!InstResult) { + DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load." + "\n"); + return false; // Could not evaluate load. + } + + DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n"); + } else if (AllocaInst *AI = dyn_cast(CurInst)) { + if (AI->isArrayAllocation()) { + DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n"); + return false; // Cannot handle array allocs. + } + Type *Ty = AI->getAllocatedType(); + AllocaTmps.push_back( + make_unique(Ty, false, GlobalValue::InternalLinkage, + UndefValue::get(Ty), AI->getName())); + InstResult = AllocaTmps.back().get(); + DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n"); + } else if (isa(CurInst) || isa(CurInst)) { + CallSite CS(&*CurInst); + + // Debug info can safely be ignored here. + if (isa(CS.getInstruction())) { + DEBUG(dbgs() << "Ignoring debug info.\n"); + ++CurInst; + continue; + } + + // Cannot handle inline asm. + if (isa(CS.getCalledValue())) { + DEBUG(dbgs() << "Found inline asm, can not evaluate.\n"); + return false; + } + + if (IntrinsicInst *II = dyn_cast(CS.getInstruction())) { + if (MemSetInst *MSI = dyn_cast(II)) { + if (MSI->isVolatile()) { + DEBUG(dbgs() << "Can not optimize a volatile memset " << + "intrinsic.\n"); + return false; + } + Constant *Ptr = getVal(MSI->getDest()); + Constant *Val = getVal(MSI->getValue()); + Constant *DestVal = ComputeLoadResult(getVal(Ptr)); + if (Val->isNullValue() && DestVal && DestVal->isNullValue()) { + // This memset is a no-op. + DEBUG(dbgs() << "Ignoring no-op memset.\n"); + ++CurInst; + continue; + } + } + + if (II->getIntrinsicID() == Intrinsic::lifetime_start || + II->getIntrinsicID() == Intrinsic::lifetime_end) { + DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n"); + ++CurInst; + continue; + } + + if (II->getIntrinsicID() == Intrinsic::invariant_start) { + // We don't insert an entry into Values, as it doesn't have a + // meaningful return value. + if (!II->use_empty()) { + DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n"); + return false; + } + ConstantInt *Size = cast(II->getArgOperand(0)); + Value *PtrArg = getVal(II->getArgOperand(1)); + Value *Ptr = PtrArg->stripPointerCasts(); + if (GlobalVariable *GV = dyn_cast(Ptr)) { + Type *ElemTy = GV->getValueType(); + if (!Size->isAllOnesValue() && + Size->getValue().getLimitedValue() >= + DL.getTypeStoreSize(ElemTy)) { + Invariants.insert(GV); + DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV + << "\n"); + } else { + DEBUG(dbgs() << "Found a global var, but can not treat it as an " + "invariant.\n"); + } + } + // Continue even if we do nothing. + ++CurInst; + continue; + } else if (II->getIntrinsicID() == Intrinsic::assume) { + DEBUG(dbgs() << "Skipping assume intrinsic.\n"); + ++CurInst; + continue; + } + + DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n"); + return false; + } + + // Resolve function pointers. + Function *Callee = dyn_cast(getVal(CS.getCalledValue())); + if (!Callee || Callee->mayBeOverridden()) { + DEBUG(dbgs() << "Can not resolve function pointer.\n"); + return false; // Cannot resolve. + } + + SmallVector Formals; + for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i) + Formals.push_back(getVal(*i)); + + if (Callee->isDeclaration()) { + // If this is a function we can constant fold, do it. + if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) { + InstResult = C; + DEBUG(dbgs() << "Constant folded function call. Result: " << + *InstResult << "\n"); + } else { + DEBUG(dbgs() << "Can not constant fold function call.\n"); + return false; + } + } else { + if (Callee->getFunctionType()->isVarArg()) { + DEBUG(dbgs() << "Can not constant fold vararg function call.\n"); + return false; + } + + Constant *RetVal = nullptr; + // Execute the call, if successful, use the return value. + ValueStack.emplace_back(); + if (!EvaluateFunction(Callee, RetVal, Formals)) { + DEBUG(dbgs() << "Failed to evaluate function.\n"); + return false; + } + ValueStack.pop_back(); + InstResult = RetVal; + + if (InstResult) { + DEBUG(dbgs() << "Successfully evaluated function. Result: " + << *InstResult << "\n\n"); + } else { + DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n"); + } + } + } else if (isa(CurInst)) { + DEBUG(dbgs() << "Found a terminator instruction.\n"); + + if (BranchInst *BI = dyn_cast(CurInst)) { + if (BI->isUnconditional()) { + NextBB = BI->getSuccessor(0); + } else { + ConstantInt *Cond = + dyn_cast(getVal(BI->getCondition())); + if (!Cond) return false; // Cannot determine. + + NextBB = BI->getSuccessor(!Cond->getZExtValue()); + } + } else if (SwitchInst *SI = dyn_cast(CurInst)) { + ConstantInt *Val = + dyn_cast(getVal(SI->getCondition())); + if (!Val) return false; // Cannot determine. + NextBB = SI->findCaseValue(Val).getCaseSuccessor(); + } else if (IndirectBrInst *IBI = dyn_cast(CurInst)) { + Value *Val = getVal(IBI->getAddress())->stripPointerCasts(); + if (BlockAddress *BA = dyn_cast(Val)) + NextBB = BA->getBasicBlock(); + else + return false; // Cannot determine. + } else if (isa(CurInst)) { + NextBB = nullptr; + } else { + // invoke, unwind, resume, unreachable. + DEBUG(dbgs() << "Can not handle terminator."); + return false; // Cannot handle this terminator. + } + + // We succeeded at evaluating this block! + DEBUG(dbgs() << "Successfully evaluated block.\n"); + return true; + } else { + // Did not know how to evaluate this! + DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction." + "\n"); + return false; + } + + if (!CurInst->use_empty()) { + if (ConstantExpr *CE = dyn_cast(InstResult)) + InstResult = ConstantFoldConstantExpression(CE, DL, TLI); + + setVal(&*CurInst, InstResult); + } + + // If we just processed an invoke, we finished evaluating the block. + if (InvokeInst *II = dyn_cast(CurInst)) { + NextBB = II->getNormalDest(); + DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n"); + return true; + } + + // Advance program counter. + ++CurInst; + } +} + +/// Evaluate a call to function F, returning true if successful, false if we +/// can't evaluate it. ActualArgs contains the formal arguments for the +/// function. +bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal, + const SmallVectorImpl &ActualArgs) { + // Check to see if this function is already executing (recursion). If so, + // bail out. TODO: we might want to accept limited recursion. + if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end()) + return false; + + CallStack.push_back(F); + + // Initialize arguments to the incoming values specified. + unsigned ArgNo = 0; + for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; + ++AI, ++ArgNo) + setVal(&*AI, ActualArgs[ArgNo]); + + // ExecutedBlocks - We only handle non-looping, non-recursive code. As such, + // we can only evaluate any one basic block at most once. This set keeps + // track of what we have executed so we can detect recursive cases etc. + SmallPtrSet ExecutedBlocks; + + // CurBB - The current basic block we're evaluating. + BasicBlock *CurBB = &F->front(); + + BasicBlock::iterator CurInst = CurBB->begin(); + + while (1) { + BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings. + DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n"); + + if (!EvaluateBlock(CurInst, NextBB)) + return false; + + if (!NextBB) { + // Successfully running until there's no next block means that we found + // the return. Fill it the return value and pop the call stack. + ReturnInst *RI = cast(CurBB->getTerminator()); + if (RI->getNumOperands()) + RetVal = getVal(RI->getOperand(0)); + CallStack.pop_back(); + return true; + } + + // Okay, we succeeded in evaluating this control flow. See if we have + // executed the new block before. If so, we have a looping function, + // which we cannot evaluate in reasonable time. + if (!ExecutedBlocks.insert(NextBB).second) + return false; // looped! + + // Okay, we have never been in this block before. Check to see if there + // are any PHI nodes. If so, evaluate them with information about where + // we came from. + PHINode *PN = nullptr; + for (CurInst = NextBB->begin(); + (PN = dyn_cast(CurInst)); ++CurInst) + setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB))); + + // Advance to the next block. + CurBB = NextBB; + } +} + Index: test/Transforms/WholeProgramDevirt/constant-arg.ll =================================================================== --- /dev/null +++ test/Transforms/WholeProgramDevirt/constant-arg.ll @@ -0,0 +1,76 @@ +; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s + +; CHECK: private global { [8 x i8], [1 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\00\00\00\00\01", [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf1 to i8*)], [0 x i8] zeroinitializer } +; CHECK: private global { [8 x i8], [1 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\00\00\00\00\02", [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf2 to i8*)], [0 x i8] zeroinitializer } +; CHECK: private global { [8 x i8], [1 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\00\00\00\00\01", [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf4 to i8*)], [0 x i8] zeroinitializer } +; CHECK: private global { [8 x i8], [1 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\00\00\00\00\02", [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf8 to i8*)], [0 x i8] zeroinitializer } + +@vt1 = global [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf1 to i8*)] +@vt2 = global [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf2 to i8*)] +@vt4 = global [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf4 to i8*)] +@vt8 = global [1 x i8*] [i8* bitcast (i1 (i8*, i32)* @vf8 to i8*)] + +define i1 @vf1(i8* %this, i32 %arg) readnone { + %and = and i32 %arg, 1 + %cmp = icmp ne i32 %and, 0 + ret i1 %cmp +} + +define i1 @vf2(i8* %this, i32 %arg) readnone { + %and = and i32 %arg, 2 + %cmp = icmp ne i32 %and, 0 + ret i1 %cmp +} + +define i1 @vf4(i8* %this, i32 %arg) readnone { + %and = and i32 %arg, 4 + %cmp = icmp ne i32 %and, 0 + ret i1 %cmp +} + +define i1 @vf8(i8* %this, i32 %arg) readnone { + %and = and i32 %arg, 8 + %cmp = icmp ne i32 %and, 0 + ret i1 %cmp +} + +; CHECK: define i1 @call1 +define i1 @call1(i8* %obj) { + %vtableptr = bitcast i8* %obj to [1 x i8*]** + %vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr + %vtablei8 = bitcast [1 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*, i32)* + ; CHECK: getelementptr {{.*}} -1 + ; CHECK: and {{.*}}, 1 + %result = call i1 %fptr_casted(i8* %obj, i32 5) + ret i1 %result +} + +; CHECK: define i1 @call2 +define i1 @call2(i8* %obj) { + %vtableptr = bitcast i8* %obj to [1 x i8*]** + %vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr + %vtablei8 = bitcast [1 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*, i32)* + ; CHECK: getelementptr {{.*}} -1 + ; CHECK: and {{.*}}, 2 + %result = call i1 %fptr_casted(i8* %obj, i32 10) + ret i1 %result +} + +declare i1 @llvm.bitset.test(i8*, metadata) +declare void @llvm.assume(i1) + +!0 = !{!"bitset", [1 x i8*]* @vt1, i32 0} +!1 = !{!"bitset", [1 x i8*]* @vt2, i32 0} +!2 = !{!"bitset", [1 x i8*]* @vt4, i32 0} +!3 = !{!"bitset", [1 x i8*]* @vt8, i32 0} +!llvm.bitsets = !{!0, !1, !2, !3} Index: test/Transforms/WholeProgramDevirt/devirt-single-impl.ll =================================================================== --- /dev/null +++ test/Transforms/WholeProgramDevirt/devirt-single-impl.ll @@ -0,0 +1,30 @@ +; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s + +@vt1 = global [1 x i8*] [i8* bitcast (void (i8*)* @vf to i8*)] +@vt2 = global [1 x i8*] [i8* bitcast (void (i8*)* @vf to i8*)] + +define void @vf(i8* %this) { + ret void +} + +; CHECK: define void @call +define void @call(i8* %obj) { + %vtableptr = bitcast i8* %obj to [1 x i8*]** + %vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr + %vtablei8 = bitcast [1 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to void (i8*)* + ; CHECK: call void @vf( + call void %fptr_casted(i8* %obj) + ret void +} + +declare i1 @llvm.bitset.test(i8*, metadata) +declare void @llvm.assume(i1) + +!0 = !{!"bitset", [1 x i8*]* @vt1, i32 0} +!1 = !{!"bitset", [1 x i8*]* @vt2, i32 0} +!llvm.bitsets = !{!0, !1} Index: test/Transforms/WholeProgramDevirt/uniform-retval.ll =================================================================== --- /dev/null +++ test/Transforms/WholeProgramDevirt/uniform-retval.ll @@ -0,0 +1,35 @@ +; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s + +@vt1 = global [1 x i8*] [i8* bitcast (i32 (i8*)* @vf1 to i8*)] +@vt2 = global [1 x i8*] [i8* bitcast (i32 (i8*)* @vf2 to i8*)] + +define i32 @vf1(i8* %this) readnone { + ret i32 123 +} + +define i32 @vf2(i8* %this) readnone { + ret i32 123 +} + +; CHECK: define i32 @call +define i32 @call(i8* %obj) { + %vtableptr = bitcast i8* %obj to [1 x i8*]** + %vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr + %vtablei8 = bitcast [1 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i32 (i8*)* + %result = call i32 %fptr_casted(i8* %obj) + ; CHECK-NOT: call + ; CHECK: ret i32 123 + ret i32 %result +} + +declare i1 @llvm.bitset.test(i8*, metadata) +declare void @llvm.assume(i1) + +!0 = !{!"bitset", [1 x i8*]* @vt1, i32 0} +!1 = !{!"bitset", [1 x i8*]* @vt2, i32 0} +!llvm.bitsets = !{!0, !1} Index: test/Transforms/WholeProgramDevirt/unique-retval.ll =================================================================== --- /dev/null +++ test/Transforms/WholeProgramDevirt/unique-retval.ll @@ -0,0 +1,58 @@ +; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s + +@vt1 = global [1 x i8*] [i8* bitcast (i1 (i8*)* @vf0 to i8*)] +@vt2 = global [1 x i8*] [i8* bitcast (i1 (i8*)* @vf0 to i8*)] +@vt3 = global [1 x i8*] [i8* bitcast (i1 (i8*)* @vf1 to i8*)] +@vt4 = global [1 x i8*] [i8* bitcast (i1 (i8*)* @vf1 to i8*)] + +define i1 @vf0(i8* %this) readnone { + ret i1 0 +} + +define i1 @vf1(i8* %this) readnone { + ret i1 1 +} + +; CHECK: define i1 @call1 +define i1 @call1(i8* %obj) { + %vtableptr = bitcast i8* %obj to [1 x i8*]** + %vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr + ; CHECK: [[VT1:%[^ ]*]] = bitcast [1 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [1 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset1") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*)* + ; CHECK: [[RES1:%[^ ]*]] = icmp eq i8* [[VT1]], bitcast ([1 x i8*]* @vt3 to i8*) + %result = call i1 %fptr_casted(i8* %obj) + ; CHECK: ret i1 [[RES1]] + ret i1 %result +} + +; CHECK: define i1 @call2 +define i1 @call2(i8* %obj) { + %vtableptr = bitcast i8* %obj to [1 x i8*]** + %vtable = load [1 x i8*]*, [1 x i8*]** %vtableptr + ; CHECK: [[VT2:%[^ ]*]] = bitcast [1 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [1 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset2") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [1 x i8*], [1 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*)* + ; CHECK: [[RES1:%[^ ]*]] = icmp ne i8* [[VT1]], bitcast ([1 x i8*]* @vt2 to i8*) + %result = call i1 %fptr_casted(i8* %obj) + ret i1 %result +} + +declare i1 @llvm.bitset.test(i8*, metadata) +declare void @llvm.assume(i1) + +!0 = !{!"bitset1", [1 x i8*]* @vt1, i32 0} +!1 = !{!"bitset1", [1 x i8*]* @vt2, i32 0} +!2 = !{!"bitset1", [1 x i8*]* @vt3, i32 0} +!3 = !{!"bitset2", [1 x i8*]* @vt2, i32 0} +!4 = !{!"bitset2", [1 x i8*]* @vt3, i32 0} +!5 = !{!"bitset2", [1 x i8*]* @vt4, i32 0} +!llvm.bitsets = !{!0, !1, !2, !3, !4, !5} Index: test/Transforms/WholeProgramDevirt/virtual-const-prop-begin.ll =================================================================== --- /dev/null +++ test/Transforms/WholeProgramDevirt/virtual-const-prop-begin.ll @@ -0,0 +1,134 @@ +; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s + +; CHECK: [[VT1DATA:@[^ ]*]] = private global { [8 x i8], [3 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\01\01\00\00\00", [3 x i8*] [i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i32 (i8*)* @vf1i32 to i8*)], [0 x i8] zeroinitializer } +@vt1 = global [3 x i8*] [ +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i32 (i8*)* @vf1i32 to i8*) +] + +; CHECK: [[VT2DATA:@[^ ]*]] = private global { [8 x i8], [3 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\02\02\00\00\00", [3 x i8*] [i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i32 (i8*)* @vf2i32 to i8*)], [0 x i8] zeroinitializer } +@vt2 = global [3 x i8*] [ +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i32 (i8*)* @vf2i32 to i8*) +] + +; CHECK: [[VT3DATA:@[^ ]*]] = private global { [8 x i8], [3 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\01\03\00\00\00", [3 x i8*] [i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i32 (i8*)* @vf3i32 to i8*)], [0 x i8] zeroinitializer } +@vt3 = global [3 x i8*] [ +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i32 (i8*)* @vf3i32 to i8*) +] + +; CHECK: [[VT4DATA:@[^ ]*]] = private global { [8 x i8], [3 x i8*], [0 x i8] } { [8 x i8] c"\00\00\00\02\04\00\00\00", [3 x i8*] [i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i32 (i8*)* @vf4i32 to i8*)], [0 x i8] zeroinitializer } +@vt4 = global [3 x i8*] [ +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i32 (i8*)* @vf4i32 to i8*) +] + +@vt5 = global [3 x i8*] [ +i8* bitcast (void ()* @__cxa_pure_virtual to i8*), +i8* bitcast (void ()* @__cxa_pure_virtual to i8*), +i8* bitcast (void ()* @__cxa_pure_virtual to i8*) +] + +; CHECK: @vt1 = alias [3 x i8*], getelementptr inbounds ({ [8 x i8], [3 x i8*], [0 x i8] }, { [8 x i8], [3 x i8*], [0 x i8] }* [[VT1DATA]], i32 0, i32 1) +; CHECK: @vt2 = alias [3 x i8*], getelementptr inbounds ({ [8 x i8], [3 x i8*], [0 x i8] }, { [8 x i8], [3 x i8*], [0 x i8] }* [[VT2DATA]], i32 0, i32 1) +; CHECK: @vt3 = alias [3 x i8*], getelementptr inbounds ({ [8 x i8], [3 x i8*], [0 x i8] }, { [8 x i8], [3 x i8*], [0 x i8] }* [[VT3DATA]], i32 0, i32 1) +; CHECK: @vt4 = alias [3 x i8*], getelementptr inbounds ({ [8 x i8], [3 x i8*], [0 x i8] }, { [8 x i8], [3 x i8*], [0 x i8] }* [[VT4DATA]], i32 0, i32 1) + +define i1 @vf0i1(i8* %this) readnone { + ret i1 0 +} + +define i1 @vf1i1(i8* %this) readnone { + ret i1 1 +} + +define i32 @vf1i32(i8* %this) readnone { + ret i32 1 +} + +define i32 @vf2i32(i8* %this) readnone { + ret i32 2 +} + +define i32 @vf3i32(i8* %this) readnone { + ret i32 3 +} + +define i32 @vf4i32(i8* %this) readnone { + ret i32 4 +} + +; CHECK: define i1 @call1( +define i1 @call1(i8* %obj) { + %vtableptr = bitcast i8* %obj to [3 x i8*]** + %vtable = load [3 x i8*]*, [3 x i8*]** %vtableptr + ; CHECK: [[VT1:%[^ ]*]] = bitcast [3 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [3 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [3 x i8*], [3 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*)* + ; CHECK: [[VTGEP1:%[^ ]*]] = getelementptr i8, i8* [[VT1]], i64 -5 + ; CHECK: [[VTLOAD1:%[^ ]*]] = load i8, i8* [[VTGEP1]] + ; CHECK: [[VTAND1:%[^ ]*]] = and i8 [[VTLOAD1]], 2 + ; CHECK: [[VTCMP1:%[^ ]*]] = icmp ne i8 [[VTAND1]], 0 + %result = call i1 %fptr_casted(i8* %obj) + ; CHECK: ret i1 [[VTCMP1]] + ret i1 %result +} + +; CHECK: define i1 @call2( +define i1 @call2(i8* %obj) { + %vtableptr = bitcast i8* %obj to [3 x i8*]** + %vtable = load [3 x i8*]*, [3 x i8*]** %vtableptr + ; CHECK: [[VT2:%[^ ]*]] = bitcast [3 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [3 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [3 x i8*], [3 x i8*]* %vtable, i32 0, i32 1 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*)* + ; CHECK: [[VTGEP2:%[^ ]*]] = getelementptr i8, i8* [[VT2]], i64 -5 + ; CHECK: [[VTLOAD2:%[^ ]*]] = load i8, i8* [[VTGEP2]] + ; CHECK: [[VTAND2:%[^ ]*]] = and i8 [[VTLOAD2]], 1 + ; CHECK: [[VTCMP2:%[^ ]*]] = icmp ne i8 [[VTAND2]], 0 + %result = call i1 %fptr_casted(i8* %obj) + ; CHECK: ret i1 [[VTCMP2]] + ret i1 %result +} + +; CHECK: define i32 @call3( +define i32 @call3(i8* %obj) { + %vtableptr = bitcast i8* %obj to [3 x i8*]** + %vtable = load [3 x i8*]*, [3 x i8*]** %vtableptr + ; CHECK: [[VT3:%[^ ]*]] = bitcast [3 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [3 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [3 x i8*], [3 x i8*]* %vtable, i32 0, i32 2 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i32 (i8*)* + ; CHECK: [[VTGEP3:%[^ ]*]] = getelementptr i8, i8* [[VT3]], i64 -4 + ; CHECK: [[VTBC3:%[^ ]*]] = bitcast i8* [[VTGEP3]] to i32* + ; CHECK: [[VTLOAD3:%[^ ]*]] = load i32, i32* [[VTBC3]] + %result = call i32 %fptr_casted(i8* %obj) + ; CHECK: ret i32 [[VTLOAD3]] + ret i32 %result +} + +declare i1 @llvm.bitset.test(i8*, metadata) +declare void @llvm.assume(i1) +declare void @__cxa_pure_virtual() + +!0 = !{!"bitset", [3 x i8*]* @vt1, i32 0} +!1 = !{!"bitset", [3 x i8*]* @vt2, i32 0} +!2 = !{!"bitset", [3 x i8*]* @vt3, i32 0} +!3 = !{!"bitset", [3 x i8*]* @vt4, i32 0} +!4 = !{!"bitset", [3 x i8*]* @vt5, i32 0} +!llvm.bitsets = !{!0, !1, !2, !3, !4} Index: test/Transforms/WholeProgramDevirt/virtual-const-prop-end.ll =================================================================== --- /dev/null +++ test/Transforms/WholeProgramDevirt/virtual-const-prop-end.ll @@ -0,0 +1,128 @@ +; RUN: opt -S -wholeprogramdevirt %s | FileCheck %s + +; CHECK: [[VT1DATA:@[^ ]*]] = private global { [0 x i8], [4 x i8*], [8 x i8] } { [0 x i8] zeroinitializer, [4 x i8*] [i8* null, i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i32 (i8*)* @vf1i32 to i8*)], [8 x i8] c"\01\00\00\00\01\00\00\00" } +@vt1 = global [4 x i8*] [ +i8* null, +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i32 (i8*)* @vf1i32 to i8*) +] + +; CHECK: [[VT2DATA:@[^ ]*]] = private global { [0 x i8], [3 x i8*], [8 x i8] } { [0 x i8] zeroinitializer, [3 x i8*] [i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i32 (i8*)* @vf2i32 to i8*)], [8 x i8] c"\02\00\00\00\02\00\00\00" } +@vt2 = global [3 x i8*] [ +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i32 (i8*)* @vf2i32 to i8*) +] + +; CHECK: [[VT3DATA:@[^ ]*]] = private global { [0 x i8], [4 x i8*], [8 x i8] } { [0 x i8] zeroinitializer, [4 x i8*] [i8* null, i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i32 (i8*)* @vf3i32 to i8*)], [8 x i8] c"\03\00\00\00\01\00\00\00" } +@vt3 = global [4 x i8*] [ +i8* null, +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i32 (i8*)* @vf3i32 to i8*) +] + +; CHECK: [[VT4DATA:@[^ ]*]] = private global { [0 x i8], [3 x i8*], [8 x i8] } { [0 x i8] zeroinitializer, [3 x i8*] [i8* bitcast (i1 (i8*)* @vf1i1 to i8*), i8* bitcast (i1 (i8*)* @vf0i1 to i8*), i8* bitcast (i32 (i8*)* @vf4i32 to i8*)], [8 x i8] c"\04\00\00\00\02\00\00\00" } +@vt4 = global [3 x i8*] [ +i8* bitcast (i1 (i8*)* @vf1i1 to i8*), +i8* bitcast (i1 (i8*)* @vf0i1 to i8*), +i8* bitcast (i32 (i8*)* @vf4i32 to i8*) +] + +; CHECK: @vt1 = alias [4 x i8*], getelementptr inbounds ({ [0 x i8], [4 x i8*], [8 x i8] }, { [0 x i8], [4 x i8*], [8 x i8] }* [[VT1DATA]], i32 0, i32 1) +; CHECK: @vt2 = alias [3 x i8*], getelementptr inbounds ({ [0 x i8], [3 x i8*], [8 x i8] }, { [0 x i8], [3 x i8*], [8 x i8] }* [[VT2DATA]], i32 0, i32 1) +; CHECK: @vt3 = alias [4 x i8*], getelementptr inbounds ({ [0 x i8], [4 x i8*], [8 x i8] }, { [0 x i8], [4 x i8*], [8 x i8] }* [[VT3DATA]], i32 0, i32 1) +; CHECK: @vt4 = alias [3 x i8*], getelementptr inbounds ({ [0 x i8], [3 x i8*], [8 x i8] }, { [0 x i8], [3 x i8*], [8 x i8] }* [[VT4DATA]], i32 0, i32 1) + +define i1 @vf0i1(i8* %this) readnone { + ret i1 0 +} + +define i1 @vf1i1(i8* %this) readnone { + ret i1 1 +} + +define i32 @vf1i32(i8* %this) readnone { + ret i32 1 +} + +define i32 @vf2i32(i8* %this) readnone { + ret i32 2 +} + +define i32 @vf3i32(i8* %this) readnone { + ret i32 3 +} + +define i32 @vf4i32(i8* %this) readnone { + ret i32 4 +} + +; CHECK: define i1 @call1( +define i1 @call1(i8* %obj) { + %vtableptr = bitcast i8* %obj to [3 x i8*]** + %vtable = load [3 x i8*]*, [3 x i8*]** %vtableptr + ; CHECK: [[VT1:%[^ ]*]] = bitcast [3 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [3 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [3 x i8*], [3 x i8*]* %vtable, i32 0, i32 0 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*)* + ; CHECK: [[VTGEP1:%[^ ]*]] = getelementptr i8, i8* [[VT1]], i64 28 + ; CHECK: [[VTLOAD1:%[^ ]*]] = load i8, i8* [[VTGEP1]] + ; CHECK: [[VTAND1:%[^ ]*]] = and i8 [[VTLOAD1]], 2 + ; CHECK: [[VTCMP1:%[^ ]*]] = icmp ne i8 [[VTAND1]], 0 + %result = call i1 %fptr_casted(i8* %obj) + ; CHECK: ret i1 [[VTCMP1]] + ret i1 %result +} + +; CHECK: define i1 @call2( +define i1 @call2(i8* %obj) { + %vtableptr = bitcast i8* %obj to [3 x i8*]** + %vtable = load [3 x i8*]*, [3 x i8*]** %vtableptr + ; CHECK: [[VT2:%[^ ]*]] = bitcast [3 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [3 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [3 x i8*], [3 x i8*]* %vtable, i32 0, i32 1 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i1 (i8*)* + ; CHECK: [[VTGEP2:%[^ ]*]] = getelementptr i8, i8* [[VT2]], i64 28 + ; CHECK: [[VTLOAD2:%[^ ]*]] = load i8, i8* [[VTGEP2]] + ; CHECK: [[VTAND2:%[^ ]*]] = and i8 [[VTLOAD2]], 1 + ; CHECK: [[VTCMP2:%[^ ]*]] = icmp ne i8 [[VTAND2]], 0 + %result = call i1 %fptr_casted(i8* %obj) + ; CHECK: ret i1 [[VTCMP2]] + ret i1 %result +} + +; CHECK: define i32 @call3( +define i32 @call3(i8* %obj) { + %vtableptr = bitcast i8* %obj to [3 x i8*]** + %vtable = load [3 x i8*]*, [3 x i8*]** %vtableptr + ; CHECK: [[VT3:%[^ ]*]] = bitcast [3 x i8*]* {{.*}} to i8* + %vtablei8 = bitcast [3 x i8*]* %vtable to i8* + %p = call i1 @llvm.bitset.test(i8* %vtablei8, metadata !"bitset") + call void @llvm.assume(i1 %p) + %fptrptr = getelementptr [3 x i8*], [3 x i8*]* %vtable, i32 0, i32 2 + %fptr = load i8*, i8** %fptrptr + %fptr_casted = bitcast i8* %fptr to i32 (i8*)* + ; CHECK: [[VTGEP3:%[^ ]*]] = getelementptr i8, i8* [[VT3]], i64 24 + ; CHECK: [[VTBC3:%[^ ]*]] = bitcast i8* [[VTGEP3]] to i32* + ; CHECK: [[VTLOAD3:%[^ ]*]] = load i32, i32* [[VTBC3]] + %result = call i32 %fptr_casted(i8* %obj) + ; CHECK: ret i32 [[VTLOAD3]] + ret i32 %result +} + +declare i1 @llvm.bitset.test(i8*, metadata) +declare void @llvm.assume(i1) + +!0 = !{!"bitset", [4 x i8*]* @vt1, i32 8} +!1 = !{!"bitset", [3 x i8*]* @vt2, i32 0} +!2 = !{!"bitset", [4 x i8*]* @vt3, i32 8} +!3 = !{!"bitset", [3 x i8*]* @vt4, i32 0} +!llvm.bitsets = !{!0, !1, !2, !3} Index: test/tools/gold/X86/disable-verify.ll =================================================================== --- test/tools/gold/X86/disable-verify.ll +++ test/tools/gold/X86/disable-verify.ll @@ -14,7 +14,7 @@ ; -disable-verify should disable output verification from the optimization ; pipeline. -; CHECK: Pass Arguments: {{.*}} -verify -forceattrs +; CHECK: Pass Arguments: {{.*}} -verify - ; CHECK-NOT: -verify ; VERIFY: Pass Arguments: {{.*}} -verify {{.*}} -verify Index: unittests/Transforms/IPO/CMakeLists.txt =================================================================== --- unittests/Transforms/IPO/CMakeLists.txt +++ unittests/Transforms/IPO/CMakeLists.txt @@ -6,4 +6,5 @@ add_llvm_unittest(IPOTests LowerBitSets.cpp + WholeProgramDevirt.cpp ) Index: unittests/Transforms/IPO/WholeProgramDevirt.cpp =================================================================== --- /dev/null +++ unittests/Transforms/IPO/WholeProgramDevirt.cpp @@ -0,0 +1,164 @@ +//===- WholeProgramDevirt.cpp - Unit tests for whole-program devirt -------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/IPO/WholeProgramDevirt.h" +#include "gtest/gtest.h" + +using namespace llvm; +using namespace wholeprogramdevirt; + +TEST(WholeProgramDevirt, findLowestOffset) { + VTableBits VT1; + VT1.ObjectSize = 8; + VT1.Before.BytesUsed = {1 << 0}; + VT1.After.BytesUsed = {1 << 1}; + + VTableBits VT2; + VT2.ObjectSize = 8; + VT2.Before.BytesUsed = {1 << 1}; + VT2.After.BytesUsed = {1 << 0}; + + BitSetInfo BS1{&VT1, 0}; + BitSetInfo BS2{&VT2, 0}; + VirtualCallTarget Targets[] = { + {&BS1, /*IsBigEndian=*/false}, + {&BS2, /*IsBigEndian=*/false}, + }; + + EXPECT_EQ(2ull, findLowestOffset(Targets, /*IsAfter=*/false, 1)); + EXPECT_EQ(66ull, findLowestOffset(Targets, /*IsAfter=*/true, 1)); + + EXPECT_EQ(8ull, findLowestOffset(Targets, /*IsAfter=*/false, 8)); + EXPECT_EQ(72ull, findLowestOffset(Targets, /*IsAfter=*/true, 8)); + + BS1.Offset = 4; + EXPECT_EQ(33ull, findLowestOffset(Targets, /*IsAfter=*/false, 1)); + EXPECT_EQ(65ull, findLowestOffset(Targets, /*IsAfter=*/true, 1)); + + EXPECT_EQ(40ull, findLowestOffset(Targets, /*IsAfter=*/false, 8)); + EXPECT_EQ(72ull, findLowestOffset(Targets, /*IsAfter=*/true, 8)); + + BS1.Offset = 8; + BS2.Offset = 8; + EXPECT_EQ(66ull, findLowestOffset(Targets, /*IsAfter=*/false, 1)); + EXPECT_EQ(2ull, findLowestOffset(Targets, /*IsAfter=*/true, 1)); + + EXPECT_EQ(72ull, findLowestOffset(Targets, /*IsAfter=*/false, 8)); + EXPECT_EQ(8ull, findLowestOffset(Targets, /*IsAfter=*/true, 8)); + + VT1.After.BytesUsed = {0xff, 0, 0, 0, 0xff}; + VT2.After.BytesUsed = {0xff, 1, 0, 0, 0}; + EXPECT_EQ(16ull, findLowestOffset(Targets, /*IsAfter=*/true, 16)); + EXPECT_EQ(40ull, findLowestOffset(Targets, /*IsAfter=*/true, 32)); +} + +TEST(WholeProgramDevirt, setReturnValues) { + VTableBits VT1; + VT1.ObjectSize = 8; + + VTableBits VT2; + VT2.ObjectSize = 8; + + BitSetInfo BS1{&VT1, 0}; + BitSetInfo BS2{&VT2, 0}; + VirtualCallTarget Targets[] = { + {&BS1, /*IsBigEndian=*/false}, + {&BS2, /*IsBigEndian=*/false}, + }; + + BS1.Offset = 4; + BS2.Offset = 4; + + int64_t OffsetByte; + uint64_t OffsetBit; + + Targets[0].RetVal = 1; + Targets[1].RetVal = 0; + setBeforeReturnValues(Targets, 32, 1, OffsetByte, OffsetBit); + EXPECT_EQ(-5ll, OffsetByte); + EXPECT_EQ(0ull, OffsetBit); + EXPECT_EQ(std::vector{1}, VT1.Before.Bytes); + EXPECT_EQ(std::vector{1}, VT1.Before.BytesUsed); + EXPECT_EQ(std::vector{0}, VT2.Before.Bytes); + EXPECT_EQ(std::vector{1}, VT2.Before.BytesUsed); + + Targets[0].RetVal = 0; + Targets[1].RetVal = 1; + setBeforeReturnValues(Targets, 39, 1, OffsetByte, OffsetBit); + EXPECT_EQ(-5ll, OffsetByte); + EXPECT_EQ(7ull, OffsetBit); + EXPECT_EQ(std::vector{1}, VT1.Before.Bytes); + EXPECT_EQ(std::vector{0x81}, VT1.Before.BytesUsed); + EXPECT_EQ(std::vector{0x80}, VT2.Before.Bytes); + EXPECT_EQ(std::vector{0x81}, VT2.Before.BytesUsed); + + Targets[0].RetVal = 12; + Targets[1].RetVal = 34; + setBeforeReturnValues(Targets, 40, 8, OffsetByte, OffsetBit); + EXPECT_EQ(-6ll, OffsetByte); + EXPECT_EQ(0ull, OffsetBit); + EXPECT_EQ((std::vector{1, 12}), VT1.Before.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff}), VT1.Before.BytesUsed); + EXPECT_EQ((std::vector{0x80, 34}), VT2.Before.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff}), VT2.Before.BytesUsed); + + Targets[0].RetVal = 56; + Targets[1].RetVal = 78; + setBeforeReturnValues(Targets, 48, 16, OffsetByte, OffsetBit); + EXPECT_EQ(-8ll, OffsetByte); + EXPECT_EQ(0ull, OffsetBit); + EXPECT_EQ((std::vector{1, 12, 0, 56}), VT1.Before.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff, 0xff, 0xff}), + VT1.Before.BytesUsed); + EXPECT_EQ((std::vector{0x80, 34, 0, 78}), VT2.Before.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff, 0xff, 0xff}), + VT2.Before.BytesUsed); + + Targets[0].RetVal = 1; + Targets[1].RetVal = 0; + setAfterReturnValues(Targets, 32, 1, OffsetByte, OffsetBit); + EXPECT_EQ(4ll, OffsetByte); + EXPECT_EQ(0ull, OffsetBit); + EXPECT_EQ(std::vector{1}, VT1.After.Bytes); + EXPECT_EQ(std::vector{1}, VT1.After.BytesUsed); + EXPECT_EQ(std::vector{0}, VT2.After.Bytes); + EXPECT_EQ(std::vector{1}, VT2.After.BytesUsed); + + Targets[0].RetVal = 0; + Targets[1].RetVal = 1; + setAfterReturnValues(Targets, 39, 1, OffsetByte, OffsetBit); + EXPECT_EQ(4ll, OffsetByte); + EXPECT_EQ(7ull, OffsetBit); + EXPECT_EQ(std::vector{1}, VT1.After.Bytes); + EXPECT_EQ(std::vector{0x81}, VT1.After.BytesUsed); + EXPECT_EQ(std::vector{0x80}, VT2.After.Bytes); + EXPECT_EQ(std::vector{0x81}, VT2.After.BytesUsed); + + Targets[0].RetVal = 12; + Targets[1].RetVal = 34; + setAfterReturnValues(Targets, 40, 8, OffsetByte, OffsetBit); + EXPECT_EQ(5ll, OffsetByte); + EXPECT_EQ(0ull, OffsetBit); + EXPECT_EQ((std::vector{1, 12}), VT1.After.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff}), VT1.After.BytesUsed); + EXPECT_EQ((std::vector{0x80, 34}), VT2.After.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff}), VT2.After.BytesUsed); + + Targets[0].RetVal = 56; + Targets[1].RetVal = 78; + setAfterReturnValues(Targets, 48, 16, OffsetByte, OffsetBit); + EXPECT_EQ(6ll, OffsetByte); + EXPECT_EQ(0ull, OffsetBit); + EXPECT_EQ((std::vector{1, 12, 56, 0}), VT1.After.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff, 0xff, 0xff}), + VT1.After.BytesUsed); + EXPECT_EQ((std::vector{0x80, 34, 78, 0}), VT2.After.Bytes); + EXPECT_EQ((std::vector{0x81, 0xff, 0xff, 0xff}), + VT2.After.BytesUsed); +}