//===- InstCombineCompares.cpp --------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the visitICmp and visitFCmp functions. // //===----------------------------------------------------------------------===// #include "InstCombineInternal.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/MemoryBuiltins.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/VectorUtils.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/GetElementPtrTypeIterator.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Support/Debug.h" using namespace llvm; using namespace PatternMatch; #define DEBUG_TYPE "instcombine" // How many times is a select replaced by one of its operands? STATISTIC(NumSel, "Number of select opts"); // Initialization Routines static ConstantInt *getOne(Constant *C) { return ConstantInt::get(cast(C->getType()), 1); } static ConstantInt *ExtractElement(Constant *V, Constant *Idx) { return cast(ConstantExpr::getExtractElement(V, Idx)); } static bool HasAddOverflow(ConstantInt *Result, ConstantInt *In1, ConstantInt *In2, bool IsSigned) { if (!IsSigned) return Result->getValue().ult(In1->getValue()); if (In2->isNegative()) return Result->getValue().sgt(In1->getValue()); return Result->getValue().slt(In1->getValue()); } /// Compute Result = In1+In2, returning true if the result overflowed for this /// type. static bool AddWithOverflow(Constant *&Result, Constant *In1, Constant *In2, bool IsSigned = false) { Result = ConstantExpr::getAdd(In1, In2); if (VectorType *VTy = dyn_cast(In1->getType())) { for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); if (HasAddOverflow(ExtractElement(Result, Idx), ExtractElement(In1, Idx), ExtractElement(In2, Idx), IsSigned)) return true; } return false; } return HasAddOverflow(cast(Result), cast(In1), cast(In2), IsSigned); } static bool HasSubOverflow(ConstantInt *Result, ConstantInt *In1, ConstantInt *In2, bool IsSigned) { if (!IsSigned) return Result->getValue().ugt(In1->getValue()); if (In2->isNegative()) return Result->getValue().slt(In1->getValue()); return Result->getValue().sgt(In1->getValue()); } /// Compute Result = In1-In2, returning true if the result overflowed for this /// type. static bool SubWithOverflow(Constant *&Result, Constant *In1, Constant *In2, bool IsSigned = false) { Result = ConstantExpr::getSub(In1, In2); if (VectorType *VTy = dyn_cast(In1->getType())) { for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); if (HasSubOverflow(ExtractElement(Result, Idx), ExtractElement(In1, Idx), ExtractElement(In2, Idx), IsSigned)) return true; } return false; } return HasSubOverflow(cast(Result), cast(In1), cast(In2), IsSigned); } /// Given an icmp instruction, return true if any use of this comparison is a /// branch on sign bit comparison. static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) { for (auto *U : I.users()) if (isa(U)) return isSignBit; return false; } /// Given an exploded icmp instruction, return true if the comparison only /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the /// result of the comparison is true when the input value is signed. static bool isSignBitCheck(ICmpInst::Predicate Pred, ConstantInt *RHS, bool &TrueIfSigned) { switch (Pred) { case ICmpInst::ICMP_SLT: // True if LHS s< 0 TrueIfSigned = true; return RHS->isZero(); case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 TrueIfSigned = true; return RHS->isAllOnesValue(); case ICmpInst::ICMP_SGT: // True if LHS s> -1 TrueIfSigned = false; return RHS->isAllOnesValue(); case ICmpInst::ICMP_UGT: // True if LHS u> RHS and RHS == high-bit-mask - 1 TrueIfSigned = true; return RHS->isMaxValue(true); case ICmpInst::ICMP_UGE: // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) TrueIfSigned = true; return RHS->getValue().isSignBit(); default: return false; } } /// Returns true if the exploded icmp can be expressed as a signed comparison /// to zero and updates the predicate accordingly. /// The signedness of the comparison is preserved. static bool isSignTest(ICmpInst::Predicate &Pred, const ConstantInt *RHS) { if (!ICmpInst::isSigned(Pred)) return false; if (RHS->isZero()) return ICmpInst::isRelational(Pred); if (RHS->isOne()) { if (Pred == ICmpInst::ICMP_SLT) { Pred = ICmpInst::ICMP_SLE; return true; } } else if (RHS->isAllOnesValue()) { if (Pred == ICmpInst::ICMP_SGT) { Pred = ICmpInst::ICMP_SGE; return true; } } return false; } /// Return true if the constant is of the form 1+0+. This is the same as /// lowones(~X). static bool isHighOnes(const ConstantInt *CI) { return (~CI->getValue() + 1).isPowerOf2(); } /// Given a signed integer type and a set of known zero and one bits, compute /// the maximum and minimum values that could have the specified known zero and /// known one bits, returning them in Min/Max. static void ComputeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero, const APInt &KnownOne, APInt &Min, APInt &Max) { assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && KnownZero.getBitWidth() == Min.getBitWidth() && KnownZero.getBitWidth() == Max.getBitWidth() && "KnownZero, KnownOne and Min, Max must have equal bitwidth."); APInt UnknownBits = ~(KnownZero|KnownOne); // The minimum value is when all unknown bits are zeros, EXCEPT for the sign // bit if it is unknown. Min = KnownOne; Max = KnownOne|UnknownBits; if (UnknownBits.isNegative()) { // Sign bit is unknown Min.setBit(Min.getBitWidth()-1); Max.clearBit(Max.getBitWidth()-1); } } /// Given an unsigned integer type and a set of known zero and one bits, compute /// the maximum and minimum values that could have the specified known zero and /// known one bits, returning them in Min/Max. static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero, const APInt &KnownOne, APInt &Min, APInt &Max) { assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && KnownZero.getBitWidth() == Min.getBitWidth() && KnownZero.getBitWidth() == Max.getBitWidth() && "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); APInt UnknownBits = ~(KnownZero|KnownOne); // The minimum value is when the unknown bits are all zeros. Min = KnownOne; // The maximum value is when the unknown bits are all ones. Max = KnownOne|UnknownBits; } /// This is called when we see this pattern: /// cmp pred (load (gep GV, ...)), cmpcst /// where GV is a global variable with a constant initializer. Try to simplify /// this into some simple computation that does not need the load. For example /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". /// /// If AndCst is non-null, then the loaded value is masked with that constant /// before doing the comparison. This handles cases like "A[i]&4 == 0". Instruction *InstCombiner:: FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI, ConstantInt *AndCst) { Constant *Init = GV->getInitializer(); if (!isa(Init) && !isa(Init)) return nullptr; uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays. // There are many forms of this optimization we can handle, for now, just do // the simple index into a single-dimensional array. // // Require: GEP GV, 0, i {{, constant indices}} if (GEP->getNumOperands() < 3 || !isa(GEP->getOperand(1)) || !cast(GEP->getOperand(1))->isZero() || isa(GEP->getOperand(2))) return nullptr; // Check that indices after the variable are constants and in-range for the // type they index. Collect the indices. This is typically for arrays of // structs. SmallVector LaterIndices; Type *EltTy = Init->getType()->getArrayElementType(); for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { ConstantInt *Idx = dyn_cast(GEP->getOperand(i)); if (!Idx) return nullptr; // Variable index. uint64_t IdxVal = Idx->getZExtValue(); if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index. if (StructType *STy = dyn_cast(EltTy)) EltTy = STy->getElementType(IdxVal); else if (ArrayType *ATy = dyn_cast(EltTy)) { if (IdxVal >= ATy->getNumElements()) return nullptr; EltTy = ATy->getElementType(); } else { return nullptr; // Unknown type. } LaterIndices.push_back(IdxVal); } enum { Overdefined = -3, Undefined = -2 }; // Variables for our state machines. // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form // "i == 47 | i == 87", where 47 is the first index the condition is true for, // and 87 is the second (and last) index. FirstTrueElement is -2 when // undefined, otherwise set to the first true element. SecondTrueElement is // -2 when undefined, -3 when overdefined and >= 0 when that index is true. int FirstTrueElement = Undefined, SecondTrueElement = Undefined; // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the // form "i != 47 & i != 87". Same state transitions as for true elements. int FirstFalseElement = Undefined, SecondFalseElement = Undefined; /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these /// define a state machine that triggers for ranges of values that the index /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. /// This is -2 when undefined, -3 when overdefined, and otherwise the last /// index in the range (inclusive). We use -2 for undefined here because we /// use relative comparisons and don't want 0-1 to match -1. int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; // MagicBitvector - This is a magic bitvector where we set a bit if the // comparison is true for element 'i'. If there are 64 elements or less in // the array, this will fully represent all the comparison results. uint64_t MagicBitvector = 0; // Scan the array and see if one of our patterns matches. Constant *CompareRHS = cast(ICI.getOperand(1)); for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { Constant *Elt = Init->getAggregateElement(i); if (!Elt) return nullptr; // If this is indexing an array of structures, get the structure element. if (!LaterIndices.empty()) Elt = ConstantExpr::getExtractValue(Elt, LaterIndices); // If the element is masked, handle it. if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); // Find out if the comparison would be true or false for the i'th element. Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, CompareRHS, DL, TLI); // If the result is undef for this element, ignore it. if (isa(C)) { // Extend range state machines to cover this element in case there is an // undef in the middle of the range. if (TrueRangeEnd == (int)i-1) TrueRangeEnd = i; if (FalseRangeEnd == (int)i-1) FalseRangeEnd = i; continue; } // If we can't compute the result for any of the elements, we have to give // up evaluating the entire conditional. if (!isa(C)) return nullptr; // Otherwise, we know if the comparison is true or false for this element, // update our state machines. bool IsTrueForElt = !cast(C)->isZero(); // State machine for single/double/range index comparison. if (IsTrueForElt) { // Update the TrueElement state machine. if (FirstTrueElement == Undefined) FirstTrueElement = TrueRangeEnd = i; // First true element. else { // Update double-compare state machine. if (SecondTrueElement == Undefined) SecondTrueElement = i; else SecondTrueElement = Overdefined; // Update range state machine. if (TrueRangeEnd == (int)i-1) TrueRangeEnd = i; else TrueRangeEnd = Overdefined; } } else { // Update the FalseElement state machine. if (FirstFalseElement == Undefined) FirstFalseElement = FalseRangeEnd = i; // First false element. else { // Update double-compare state machine. if (SecondFalseElement == Undefined) SecondFalseElement = i; else SecondFalseElement = Overdefined; // Update range state machine. if (FalseRangeEnd == (int)i-1) FalseRangeEnd = i; else FalseRangeEnd = Overdefined; } } // If this element is in range, update our magic bitvector. if (i < 64 && IsTrueForElt) MagicBitvector |= 1ULL << i; // If all of our states become overdefined, bail out early. Since the // predicate is expensive, only check it every 8 elements. This is only // really useful for really huge arrays. if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && FalseRangeEnd == Overdefined) return nullptr; } // Now that we've scanned the entire array, emit our new comparison(s). We // order the state machines in complexity of the generated code. Value *Idx = GEP->getOperand(2); // If the index is larger than the pointer size of the target, truncate the // index down like the GEP would do implicitly. We don't have to do this for // an inbounds GEP because the index can't be out of range. if (!GEP->isInBounds()) { Type *IntPtrTy = DL.getIntPtrType(GEP->getType()); unsigned PtrSize = IntPtrTy->getIntegerBitWidth(); if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize) Idx = Builder->CreateTrunc(Idx, IntPtrTy); } // If the comparison is only true for one or two elements, emit direct // comparisons. if (SecondTrueElement != Overdefined) { // None true -> false. if (FirstTrueElement == Undefined) return replaceInstUsesWith(ICI, Builder->getFalse()); Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); // True for one element -> 'i == 47'. if (SecondTrueElement == Undefined) return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); // True for two elements -> 'i == 47 | i == 72'. Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); return BinaryOperator::CreateOr(C1, C2); } // If the comparison is only false for one or two elements, emit direct // comparisons. if (SecondFalseElement != Overdefined) { // None false -> true. if (FirstFalseElement == Undefined) return replaceInstUsesWith(ICI, Builder->getTrue()); Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); // False for one element -> 'i != 47'. if (SecondFalseElement == Undefined) return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); // False for two elements -> 'i != 47 & i != 72'. Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); return BinaryOperator::CreateAnd(C1, C2); } // If the comparison can be replaced with a range comparison for the elements // where it is true, emit the range check. if (TrueRangeEnd != Overdefined) { assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); // Generate (i-FirstTrue) getType(), -FirstTrueElement); Idx = Builder->CreateAdd(Idx, Offs); } Value *End = ConstantInt::get(Idx->getType(), TrueRangeEnd-FirstTrueElement+1); return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); } // False range check. if (FalseRangeEnd != Overdefined) { assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). if (FirstFalseElement) { Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); Idx = Builder->CreateAdd(Idx, Offs); } Value *End = ConstantInt::get(Idx->getType(), FalseRangeEnd-FirstFalseElement); return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); } // If a magic bitvector captures the entire comparison state // of this load, replace it with computation that does: // ((magic_cst >> i) & 1) != 0 { Type *Ty = nullptr; // Look for an appropriate type: // - The type of Idx if the magic fits // - The smallest fitting legal type if we have a DataLayout // - Default to i32 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) Ty = Idx->getType(); else Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount); if (Ty) { Value *V = Builder->CreateIntCast(Idx, Ty, false); V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); } } return nullptr; } /// Return a value that can be used to compare the *offset* implied by a GEP to /// zero. For example, if we have &A[i], we want to return 'i' for /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales /// are involved. The above expression would also be legal to codegen as /// "icmp ne (i*4), 0" (assuming A is a pointer to i32). /// This latter form is less amenable to optimization though, and we are allowed /// to generate the first by knowing that pointer arithmetic doesn't overflow. /// /// If we can't emit an optimized form for this expression, this returns null. /// static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC, const DataLayout &DL) { gep_type_iterator GTI = gep_type_begin(GEP); // Check to see if this gep only has a single variable index. If so, and if // any constant indices are a multiple of its scale, then we can compute this // in terms of the scale of the variable index. For example, if the GEP // implies an offset of "12 + i*4", then we can codegen this as "3 + i", // because the expression will cross zero at the same point. unsigned i, e = GEP->getNumOperands(); int64_t Offset = 0; for (i = 1; i != e; ++i, ++GTI) { if (ConstantInt *CI = dyn_cast(GEP->getOperand(i))) { // Compute the aggregate offset of constant indices. if (CI->isZero()) continue; // Handle a struct index, which adds its field offset to the pointer. if (StructType *STy = dyn_cast(*GTI)) { Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); } else { uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); Offset += Size*CI->getSExtValue(); } } else { // Found our variable index. break; } } // If there are no variable indices, we must have a constant offset, just // evaluate it the general way. if (i == e) return nullptr; Value *VariableIdx = GEP->getOperand(i); // Determine the scale factor of the variable element. For example, this is // 4 if the variable index is into an array of i32. uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType()); // Verify that there are no other variable indices. If so, emit the hard way. for (++i, ++GTI; i != e; ++i, ++GTI) { ConstantInt *CI = dyn_cast(GEP->getOperand(i)); if (!CI) return nullptr; // Compute the aggregate offset of constant indices. if (CI->isZero()) continue; // Handle a struct index, which adds its field offset to the pointer. if (StructType *STy = dyn_cast(*GTI)) { Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); } else { uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); Offset += Size*CI->getSExtValue(); } } // Okay, we know we have a single variable index, which must be a // pointer/array/vector index. If there is no offset, life is simple, return // the index. Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType()); unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth(); if (Offset == 0) { // Cast to intptrty in case a truncation occurs. If an extension is needed, // we don't need to bother extending: the extension won't affect where the // computation crosses zero. if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) { VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy); } return VariableIdx; } // Otherwise, there is an index. The computation we will do will be modulo // the pointer size, so get it. uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); Offset &= PtrSizeMask; VariableScale &= PtrSizeMask; // To do this transformation, any constant index must be a multiple of the // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a // multiple of the variable scale. int64_t NewOffs = Offset / (int64_t)VariableScale; if (Offset != NewOffs*(int64_t)VariableScale) return nullptr; // Okay, we can do this evaluation. Start by converting the index to intptr. if (VariableIdx->getType() != IntPtrTy) VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy, true /*Signed*/); Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset"); } /// Returns true if we can rewrite Start as a GEP with pointer Base /// and some integer offset. The nodes that need to be re-written /// for this transformation will be added to Explored. static bool canRewriteGEPAsOffset(Value *Start, Value *Base, const DataLayout &DL, SetVector &Explored) { SmallVector WorkList(1, Start); Explored.insert(Base); // The following traversal gives us an order which can be used // when doing the final transformation. Since in the final // transformation we create the PHI replacement instructions first, // we don't have to get them in any particular order. // // However, for other instructions we will have to traverse the // operands of an instruction first, which means that we have to // do a post-order traversal. while (!WorkList.empty()) { SetVector PHIs; while (!WorkList.empty()) { if (Explored.size() >= 100) return false; Value *V = WorkList.back(); if (Explored.count(V) != 0) { WorkList.pop_back(); continue; } if (!isa(V) && !isa(V) && !isa(V) && !isa(V)) // We've found some value that we can't explore which is different from // the base. Therefore we can't do this transformation. return false; if (isa(V) || isa(V)) { auto *CI = dyn_cast(V); if (!CI->isNoopCast(DL)) return false; if (Explored.count(CI->getOperand(0)) == 0) WorkList.push_back(CI->getOperand(0)); } if (auto *GEP = dyn_cast(V)) { // We're limiting the GEP to having one index. This will preserve // the original pointer type. We could handle more cases in the // future. if (GEP->getNumIndices() != 1 || !GEP->isInBounds() || GEP->getType() != Start->getType()) return false; if (Explored.count(GEP->getOperand(0)) == 0) WorkList.push_back(GEP->getOperand(0)); } if (WorkList.back() == V) { WorkList.pop_back(); // We've finished visiting this node, mark it as such. Explored.insert(V); } if (auto *PN = dyn_cast(V)) { // We cannot transform PHIs on unsplittable basic blocks. if (isa(PN->getParent()->getTerminator())) return false; Explored.insert(PN); PHIs.insert(PN); } } // Explore the PHI nodes further. for (auto *PN : PHIs) for (Value *Op : PN->incoming_values()) if (Explored.count(Op) == 0) WorkList.push_back(Op); } // Make sure that we can do this. Since we can't insert GEPs in a basic // block before a PHI node, we can't easily do this transformation if // we have PHI node users of transformed instructions. for (Value *Val : Explored) { for (Value *Use : Val->uses()) { auto *PHI = dyn_cast(Use); auto *Inst = dyn_cast(Val); if (Inst == Base || Inst == PHI || !Inst || !PHI || Explored.count(PHI) == 0) continue; if (PHI->getParent() == Inst->getParent()) return false; } } return true; } // Sets the appropriate insert point on Builder where we can add // a replacement Instruction for V (if that is possible). static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before = true) { if (auto *PHI = dyn_cast(V)) { Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt()); return; } if (auto *I = dyn_cast(V)) { if (!Before) I = &*std::next(I->getIterator()); Builder.SetInsertPoint(I); return; } if (auto *A = dyn_cast(V)) { // Set the insertion point in the entry block. BasicBlock &Entry = A->getParent()->getEntryBlock(); Builder.SetInsertPoint(&*Entry.getFirstInsertionPt()); return; } // Otherwise, this is a constant and we don't need to set a new // insertion point. assert(isa(V) && "Setting insertion point for unknown value!"); } /// Returns a re-written value of Start as an indexed GEP using Base as a /// pointer. static Value *rewriteGEPAsOffset(Value *Start, Value *Base, const DataLayout &DL, SetVector &Explored) { // Perform all the substitutions. This is a bit tricky because we can // have cycles in our use-def chains. // 1. Create the PHI nodes without any incoming values. // 2. Create all the other values. // 3. Add the edges for the PHI nodes. // 4. Emit GEPs to get the original pointers. // 5. Remove the original instructions. Type *IndexType = IntegerType::get( Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType())); DenseMap NewInsts; NewInsts[Base] = ConstantInt::getNullValue(IndexType); // Create the new PHI nodes, without adding any incoming values. for (Value *Val : Explored) { if (Val == Base) continue; // Create empty phi nodes. This avoids cyclic dependencies when creating // the remaining instructions. if (auto *PHI = dyn_cast(Val)) NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(), PHI->getName() + ".idx", PHI); } IRBuilder<> Builder(Base->getContext()); // Create all the other instructions. for (Value *Val : Explored) { if (NewInsts.find(Val) != NewInsts.end()) continue; if (auto *CI = dyn_cast(Val)) { NewInsts[CI] = NewInsts[CI->getOperand(0)]; continue; } if (auto *GEP = dyn_cast(Val)) { Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)] : GEP->getOperand(1); setInsertionPoint(Builder, GEP); // Indices might need to be sign extended. GEPs will magically do // this, but we need to do it ourselves here. if (Index->getType()->getScalarSizeInBits() != NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) { Index = Builder.CreateSExtOrTrunc( Index, NewInsts[GEP->getOperand(0)]->getType(), GEP->getOperand(0)->getName() + ".sext"); } auto *Op = NewInsts[GEP->getOperand(0)]; if (isa(Op) && dyn_cast(Op)->isZero()) NewInsts[GEP] = Index; else NewInsts[GEP] = Builder.CreateNSWAdd( Op, Index, GEP->getOperand(0)->getName() + ".add"); continue; } if (isa(Val)) continue; llvm_unreachable("Unexpected instruction type"); } // Add the incoming values to the PHI nodes. for (Value *Val : Explored) { if (Val == Base) continue; // All the instructions have been created, we can now add edges to the // phi nodes. if (auto *PHI = dyn_cast(Val)) { PHINode *NewPhi = static_cast(NewInsts[PHI]); for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) { Value *NewIncoming = PHI->getIncomingValue(I); if (NewInsts.find(NewIncoming) != NewInsts.end()) NewIncoming = NewInsts[NewIncoming]; NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I)); } } } for (Value *Val : Explored) { if (Val == Base) continue; // Depending on the type, for external users we have to emit // a GEP or a GEP + ptrtoint. setInsertionPoint(Builder, Val, false); // If required, create an inttoptr instruction for Base. Value *NewBase = Base; if (!Base->getType()->isPointerTy()) NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(), Start->getName() + "to.ptr"); Value *GEP = Builder.CreateInBoundsGEP( Start->getType()->getPointerElementType(), NewBase, makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr"); if (!Val->getType()->isPointerTy()) { Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(), Val->getName() + ".conv"); GEP = Cast; } Val->replaceAllUsesWith(GEP); } return NewInsts[Start]; } /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express /// the input Value as a constant indexed GEP. Returns a pair containing /// the GEPs Pointer and Index. static std::pair getAsConstantIndexedAddress(Value *V, const DataLayout &DL) { Type *IndexType = IntegerType::get(V->getContext(), DL.getPointerTypeSizeInBits(V->getType())); Constant *Index = ConstantInt::getNullValue(IndexType); while (true) { if (GEPOperator *GEP = dyn_cast(V)) { // We accept only inbouds GEPs here to exclude the possibility of // overflow. if (!GEP->isInBounds()) break; if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 && GEP->getType() == V->getType()) { V = GEP->getOperand(0); Constant *GEPIndex = static_cast(GEP->getOperand(1)); Index = ConstantExpr::getAdd( Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType)); continue; } break; } if (auto *CI = dyn_cast(V)) { if (!CI->isNoopCast(DL)) break; V = CI->getOperand(0); continue; } if (auto *CI = dyn_cast(V)) { if (!CI->isNoopCast(DL)) break; V = CI->getOperand(0); continue; } break; } return {V, Index}; } /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant. /// We can look through PHIs, GEPs and casts in order to determine a common base /// between GEPLHS and RHS. static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, ICmpInst::Predicate Cond, const DataLayout &DL) { if (!GEPLHS->hasAllConstantIndices()) return nullptr; Value *PtrBase, *Index; std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL); // The set of nodes that will take part in this transformation. SetVector Nodes; if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes)) return nullptr; // We know we can re-write this as // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) // Since we've only looked through inbouds GEPs we know that we // can't have overflow on either side. We can therefore re-write // this as: // OFFSET1 cmp OFFSET2 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes); // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written // GEP having PtrBase as the pointer base, and has returned in NewRHS the // offset. Since Index is the offset of LHS to the base pointer, we will now // compare the offsets instead of comparing the pointers. return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS); } /// Fold comparisons between a GEP instruction and something else. At this point /// we know that the GEP is on the LHS of the comparison. Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS, ICmpInst::Predicate Cond, Instruction &I) { // Don't transform signed compares of GEPs into index compares. Even if the // GEP is inbounds, the final add of the base pointer can have signed overflow // and would change the result of the icmp. // e.g. "&foo[0] (RHS)) RHS = RHS->stripPointerCasts(); Value *PtrBase = GEPLHS->getOperand(0); if (PtrBase == RHS && GEPLHS->isInBounds()) { // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). // This transformation (ignoring the base and scales) is valid because we // know pointers can't overflow since the gep is inbounds. See if we can // output an optimized form. Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this, DL); // If not, synthesize the offset the hard way. if (!Offset) Offset = EmitGEPOffset(GEPLHS); return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, Constant::getNullValue(Offset->getType())); } else if (GEPOperator *GEPRHS = dyn_cast(RHS)) { // If the base pointers are different, but the indices are the same, just // compare the base pointer. if (PtrBase != GEPRHS->getOperand(0)) { bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); IndicesTheSame &= GEPLHS->getOperand(0)->getType() == GEPRHS->getOperand(0)->getType(); if (IndicesTheSame) for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { IndicesTheSame = false; break; } // If all indices are the same, just compare the base pointers. if (IndicesTheSame) return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); // If we're comparing GEPs with two base pointers that only differ in type // and both GEPs have only constant indices or just one use, then fold // the compare with the adjusted indices. if (GEPLHS->isInBounds() && GEPRHS->isInBounds() && (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && PtrBase->stripPointerCasts() == GEPRHS->getOperand(0)->stripPointerCasts()) { Value *LOffset = EmitGEPOffset(GEPLHS); Value *ROffset = EmitGEPOffset(GEPRHS); // If we looked through an addrspacecast between different sized address // spaces, the LHS and RHS pointers are different sized // integers. Truncate to the smaller one. Type *LHSIndexTy = LOffset->getType(); Type *RHSIndexTy = ROffset->getType(); if (LHSIndexTy != RHSIndexTy) { if (LHSIndexTy->getPrimitiveSizeInBits() < RHSIndexTy->getPrimitiveSizeInBits()) { ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy); } else LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy); } Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond), LOffset, ROffset); return replaceInstUsesWith(I, Cmp); } // Otherwise, the base pointers are different and the indices are // different. Try convert this to an indexed compare by looking through // PHIs/casts. return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); } // If one of the GEPs has all zero indices, recurse. if (GEPLHS->hasAllZeroIndices()) return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0), ICmpInst::getSwappedPredicate(Cond), I); // If the other GEP has all zero indices, recurse. if (GEPRHS->hasAllZeroIndices()) return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { // If the GEPs only differ by one index, compare it. unsigned NumDifferences = 0; // Keep track of # differences. unsigned DiffOperand = 0; // The operand that differs. for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { // Irreconcilable differences. NumDifferences = 2; break; } else { if (NumDifferences++) break; DiffOperand = i; } } if (NumDifferences == 0) // SAME GEP? return replaceInstUsesWith(I, // No comparison is needed here. Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond))); else if (NumDifferences == 1 && GEPsInBounds) { Value *LHSV = GEPLHS->getOperand(DiffOperand); Value *RHSV = GEPRHS->getOperand(DiffOperand); // Make sure we do a signed comparison here. return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); } } // Only lower this if the icmp is the only user of the GEP or if we expect // the result to fold to a constant! if (GEPsInBounds && (isa(GEPLHS) || GEPLHS->hasOneUse()) && (isa(GEPRHS) || GEPRHS->hasOneUse())) { // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) Value *L = EmitGEPOffset(GEPLHS); Value *R = EmitGEPOffset(GEPRHS); return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); } } // Try convert this to an indexed compare by looking through PHIs/casts as a // last resort. return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); } Instruction *InstCombiner::FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca, Value *Other) { assert(ICI.isEquality() && "Cannot fold non-equality comparison."); // It would be tempting to fold away comparisons between allocas and any // pointer not based on that alloca (e.g. an argument). However, even // though such pointers cannot alias, they can still compare equal. // // But LLVM doesn't specify where allocas get their memory, so if the alloca // doesn't escape we can argue that it's impossible to guess its value, and we // can therefore act as if any such guesses are wrong. // // The code below checks that the alloca doesn't escape, and that it's only // used in a comparison once (the current instruction). The // single-comparison-use condition ensures that we're trivially folding all // comparisons against the alloca consistently, and avoids the risk of // erroneously folding a comparison of the pointer with itself. unsigned MaxIter = 32; // Break cycles and bound to constant-time. SmallVector Worklist; for (Use &U : Alloca->uses()) { if (Worklist.size() >= MaxIter) return nullptr; Worklist.push_back(&U); } unsigned NumCmps = 0; while (!Worklist.empty()) { assert(Worklist.size() <= MaxIter); Use *U = Worklist.pop_back_val(); Value *V = U->getUser(); --MaxIter; if (isa(V) || isa(V) || isa(V) || isa(V)) { // Track the uses. } else if (isa(V)) { // Loading from the pointer doesn't escape it. continue; } else if (auto *SI = dyn_cast(V)) { // Storing *to* the pointer is fine, but storing the pointer escapes it. if (SI->getValueOperand() == U->get()) return nullptr; continue; } else if (isa(V)) { if (NumCmps++) return nullptr; // Found more than one cmp. continue; } else if (auto *Intrin = dyn_cast(V)) { switch (Intrin->getIntrinsicID()) { // These intrinsics don't escape or compare the pointer. Memset is safe // because we don't allow ptrtoint. Memcpy and memmove are safe because // we don't allow stores, so src cannot point to V. case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: case Intrinsic::dbg_declare: case Intrinsic::dbg_value: case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: continue; default: return nullptr; } } else { return nullptr; } for (Use &U : V->uses()) { if (Worklist.size() >= MaxIter) return nullptr; Worklist.push_back(&U); } } Type *CmpTy = CmpInst::makeCmpResultType(Other->getType()); return replaceInstUsesWith( ICI, ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate()))); } /// Fold "icmp pred (X+CI), X". Instruction *InstCombiner::FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI, ICmpInst::Predicate Pred) { // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, // so the values can never be equal. Similarly for all other "or equals" // operators. // (X+1) X >u (MAXUINT-1) --> X == 255 // (X+2) X >u (MAXUINT-2) --> X > 253 // (X+MAXUINT) X >u (MAXUINT-MAXUINT) --> X != 0 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { Value *R = ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI); return new ICmpInst(ICmpInst::ICMP_UGT, X, R); } // (X+1) >u X --> X X != 255 // (X+2) >u X --> X X u X --> X X X == 0 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI)); unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits(); ConstantInt *SMax = ConstantInt::get(X->getContext(), APInt::getSignedMaxValue(BitWidth)); // (X+ 1) X >s (MAXSINT-1) --> X == 127 // (X+ 2) X >s (MAXSINT-2) --> X >s 125 // (X+MAXSINT) X >s (MAXSINT-MAXSINT) --> X >s 0 // (X+MINSINT) X >s (MAXSINT-MINSINT) --> X >s -1 // (X+ -2) X >s (MAXSINT- -2) --> X >s 126 // (X+ -1) X >s (MAXSINT- -1) --> X != 127 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI)); // (X+ 1) >s X --> X X != 127 // (X+ 2) >s X --> X X s X --> X X s X --> X X s X --> X X s X --> X X == -128 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); Constant *C = Builder->getInt(CI->getValue()-1); return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C)); } /// Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS and CmpRHS are /// both known to be integer constants. Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, ConstantInt *DivRHS) { ConstantInt *CmpRHS = cast(ICI.getOperand(1)); const APInt &CmpRHSV = CmpRHS->getValue(); // FIXME: If the operand types don't match the type of the divide // then don't attempt this transform. The code below doesn't have the // logic to deal with a signed divide and an unsigned compare (and // vice versa). This is because (x /s C1) getOpcode() == Instruction::SDiv; if (!ICI.isEquality() && DivIsSigned != ICI.isSigned()) return nullptr; if (DivRHS->isZero()) return nullptr; // The ProdOV computation fails on divide by zero. if (DivIsSigned && DivRHS->isAllOnesValue()) return nullptr; // The overflow computation also screws up here if (DivRHS->isOne()) { // This eliminates some funny cases with INT_MIN. ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X. return &ICI; } // Compute Prod = CI * DivRHS. We are essentially solving an equation // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and // C2 (CI). By solving for X we can turn this into a range check // instead of computing a divide. Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS); // Determine if the product overflows by seeing if the product is // not equal to the divide. Make sure we do the same kind of divide // as in the LHS instruction that we're folding. bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; // Get the ICmp opcode ICmpInst::Predicate Pred = ICI.getPredicate(); // If the division is known to be exact, then there is no remainder from the // divide, so the covered range size is unit, otherwise it is the divisor. ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS; // Figure out the interval that is being checked. For example, a comparison // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). // Compute this interval based on the constants involved and the signedness of // the compare/divide. This computes a half-open interval, keeping track of // whether either value in the interval overflows. After analysis each // overflow variable is set to 0 if it's corresponding bound variable is valid // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. int LoOverflow = 0, HiOverflow = 0; Constant *LoBound = nullptr, *HiBound = nullptr; if (!DivIsSigned) { // udiv // e.g. X/5 op 3 --> [15, 20) LoBound = Prod; HiOverflow = LoOverflow = ProdOV; if (!HiOverflow) { // If this is not an exact divide, then many values in the range collapse // to the same result value. HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false); } } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0. if (CmpRHSV == 0) { // (X / pos) op 0 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) LoBound = ConstantExpr::getNeg(SubOne(RangeSize)); HiBound = RangeSize; } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) HiOverflow = LoOverflow = ProdOV; if (!HiOverflow) HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true); } else { // (X / pos) op neg // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) HiBound = AddOne(Prod); LoOverflow = HiOverflow = ProdOV ? -1 : 0; if (!LoOverflow) { ConstantInt *DivNeg =cast(ConstantExpr::getNeg(RangeSize)); LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; } } } else if (DivRHS->isNegative()) { // Divisor is < 0. if (DivI->isExact()) RangeSize = cast(ConstantExpr::getNeg(RangeSize)); if (CmpRHSV == 0) { // (X / neg) op 0 // e.g. X/-5 op 0 --> [-4, 5) LoBound = AddOne(RangeSize); HiBound = cast(ConstantExpr::getNeg(RangeSize)); if (HiBound == DivRHS) { // -INTMIN = INTMIN HiOverflow = 1; // [INTMIN+1, overflow) HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN } } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos // e.g. X/-5 op 3 --> [-19, -14) HiBound = AddOne(Prod); HiOverflow = LoOverflow = ProdOV ? -1 : 0; if (!LoOverflow) LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; } else { // (X / neg) op neg LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) LoOverflow = HiOverflow = ProdOV; if (!HiOverflow) HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true); } // Dividing by a negative swaps the condition. LT <-> GT Pred = ICmpInst::getSwappedPredicate(Pred); } Value *X = DivI->getOperand(0); switch (Pred) { default: llvm_unreachable("Unhandled icmp opcode!"); case ICmpInst::ICMP_EQ: if (LoOverflow && HiOverflow) return replaceInstUsesWith(ICI, Builder->getFalse()); if (HiOverflow) return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, X, LoBound); if (LoOverflow) return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, X, HiBound); return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true)); case ICmpInst::ICMP_NE: if (LoOverflow && HiOverflow) return replaceInstUsesWith(ICI, Builder->getTrue()); if (HiOverflow) return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, X, LoBound); if (LoOverflow) return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, X, HiBound); return replaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false)); case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_SLT: if (LoOverflow == +1) // Low bound is greater than input range. return replaceInstUsesWith(ICI, Builder->getTrue()); if (LoOverflow == -1) // Low bound is less than input range. return replaceInstUsesWith(ICI, Builder->getFalse()); return new ICmpInst(Pred, X, LoBound); case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_SGT: if (HiOverflow == +1) // High bound greater than input range. return replaceInstUsesWith(ICI, Builder->getFalse()); if (HiOverflow == -1) // High bound less than input range. return replaceInstUsesWith(ICI, Builder->getTrue()); if (Pred == ICmpInst::ICMP_UGT) return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); } } /// Handle "icmp(([al]shr X, cst1), cst2)". Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr, ConstantInt *ShAmt) { const APInt &CmpRHSV = cast(ICI.getOperand(1))->getValue(); // Check that the shift amount is in range. If not, don't perform // undefined shifts. When the shift is visited it will be // simplified. uint32_t TypeBits = CmpRHSV.getBitWidth(); uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); if (ShAmtVal >= TypeBits || ShAmtVal == 0) return nullptr; if (!ICI.isEquality()) { // If we have an unsigned comparison and an ashr, we can't simplify this. // Similarly for signed comparisons with lshr. if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr)) return nullptr; // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv // by a power of 2. Since we already have logic to simplify these, // transform to div and then simplify the resultant comparison. if (Shr->getOpcode() == Instruction::AShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1)) return nullptr; // Revisit the shift (to delete it). Worklist.Add(Shr); Constant *DivCst = ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal)); Value *Tmp = Shr->getOpcode() == Instruction::AShr ? Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) : Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()); ICI.setOperand(0, Tmp); // If the builder folded the binop, just return it. BinaryOperator *TheDiv = dyn_cast(Tmp); if (!TheDiv) return &ICI; // Otherwise, fold this div/compare. assert(TheDiv->getOpcode() == Instruction::SDiv || TheDiv->getOpcode() == Instruction::UDiv); Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast(DivCst)); assert(Res && "This div/cst should have folded!"); return Res; } // If we are comparing against bits always shifted out, the // comparison cannot succeed. APInt Comp = CmpRHSV << ShAmtVal; ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp); if (Shr->getOpcode() == Instruction::LShr) Comp = Comp.lshr(ShAmtVal); else Comp = Comp.ashr(ShAmtVal); if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero. bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; Constant *Cst = Builder->getInt1(IsICMP_NE); return replaceInstUsesWith(ICI, Cst); } // Otherwise, check to see if the bits shifted out are known to be zero. // If so, we can compare against the unshifted value: // (X & 4) >> 1 == 2 --> (X & 4) == 4. if (Shr->hasOneUse() && Shr->isExact()) return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS); if (Shr->hasOneUse()) { // Otherwise strength reduce the shift into an and. APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); Constant *Mask = Builder->getInt(Val); Value *And = Builder->CreateAnd(Shr->getOperand(0), Mask, Shr->getName()+".mask"); return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS); } return nullptr; } /// Handle "(icmp eq/ne (ashr/lshr const2, A), const1)" -> /// (icmp eq/ne A, Log2(const2/const1)) -> /// (icmp eq/ne A, Log2(const2) - Log2(const1)). Instruction *InstCombiner::FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A, ConstantInt *CI1, ConstantInt *CI2) { assert(I.isEquality() && "Cannot fold icmp gt/lt"); auto getConstant = [&I, this](bool IsTrue) { if (I.getPredicate() == I.ICMP_NE) IsTrue = !IsTrue; return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue)); }; auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { if (I.getPredicate() == I.ICMP_NE) Pred = CmpInst::getInversePredicate(Pred); return new ICmpInst(Pred, LHS, RHS); }; const APInt &AP1 = CI1->getValue(); const APInt &AP2 = CI2->getValue(); // Don't bother doing any work for cases which InstSimplify handles. if (AP2 == 0) return nullptr; bool IsAShr = isa(Op); if (IsAShr) { if (AP2.isAllOnesValue()) return nullptr; if (AP2.isNegative() != AP1.isNegative()) return nullptr; if (AP2.sgt(AP1)) return nullptr; } if (!AP1) // 'A' must be large enough to shift out the highest set bit. return getICmp(I.ICMP_UGT, A, ConstantInt::get(A->getType(), AP2.logBase2())); if (AP1 == AP2) return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); int Shift; if (IsAShr && AP1.isNegative()) Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes(); else Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros(); if (Shift > 0) { if (IsAShr && AP1 == AP2.ashr(Shift)) { // There are multiple solutions if we are comparing against -1 and the LHS // of the ashr is not a power of two. if (AP1.isAllOnesValue() && !AP2.isPowerOf2()) return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift)); return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); } else if (AP1 == AP2.lshr(Shift)) { return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); } } // Shifting const2 will never be equal to const1. return getConstant(false); } /// Handle "(icmp eq/ne (shl const2, A), const1)" -> /// (icmp eq/ne A, TrailingZeros(const1) - TrailingZeros(const2)). Instruction *InstCombiner::FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A, ConstantInt *CI1, ConstantInt *CI2) { assert(I.isEquality() && "Cannot fold icmp gt/lt"); auto getConstant = [&I, this](bool IsTrue) { if (I.getPredicate() == I.ICMP_NE) IsTrue = !IsTrue; return replaceInstUsesWith(I, ConstantInt::get(I.getType(), IsTrue)); }; auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { if (I.getPredicate() == I.ICMP_NE) Pred = CmpInst::getInversePredicate(Pred); return new ICmpInst(Pred, LHS, RHS); }; const APInt &AP1 = CI1->getValue(); const APInt &AP2 = CI2->getValue(); // Don't bother doing any work for cases which InstSimplify handles. if (AP2 == 0) return nullptr; unsigned AP2TrailingZeros = AP2.countTrailingZeros(); if (!AP1 && AP2TrailingZeros != 0) return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros)); if (AP1 == AP2) return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); // Get the distance between the lowest bits that are set. int Shift = AP1.countTrailingZeros() - AP2TrailingZeros; if (Shift > 0 && AP2.shl(Shift) == AP1) return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); // Shifting const2 will never be equal to const1. return getConstant(false); } /// Handle "icmp (instr, intcst)". Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHSI, ConstantInt *RHS) { const APInt &RHSV = RHS->getValue(); switch (LHSI->getOpcode()) { case Instruction::Trunc: if (RHS->isOne() && RHSV.getBitWidth() > 1) { // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1 Value *V = nullptr; if (ICI.getPredicate() == ICmpInst::ICMP_SLT && match(LHSI->getOperand(0), m_Signum(m_Value(V)))) return new ICmpInst(ICmpInst::ICMP_SLT, V, ConstantInt::get(V->getType(), 1)); } if (ICI.isEquality() && LHSI->hasOneUse()) { // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all // of the high bits truncated out of x are known. unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(), SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits(); APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); computeKnownBits(LHSI->getOperand(0), KnownZero, KnownOne, 0, &ICI); // If all the high bits are known, we can do this xform. if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) { // Pull in the high bits from known-ones set. APInt NewRHS = RHS->getValue().zext(SrcBits); NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits); return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), Builder->getInt(NewRHS)); } } break; case Instruction::Xor: // (icmp pred (xor X, XorCst), CI) if (ConstantInt *XorCst = dyn_cast(LHSI->getOperand(1))) { // If this is a comparison that tests the signbit (X < 0) or (x > -1), // fold the xor. if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) || (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) { Value *CompareVal = LHSI->getOperand(0); // If the sign bit of the XorCst is not set, there is no change to // the operation, just stop using the Xor. if (!XorCst->isNegative()) { ICI.setOperand(0, CompareVal); Worklist.Add(LHSI); return &ICI; } // Was the old condition true if the operand is positive? bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT; // If so, the new one isn't. isTrueIfPositive ^= true; if (isTrueIfPositive) return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS)); else return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS)); } if (LHSI->hasOneUse()) { // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit)) if (!ICI.isEquality() && XorCst->getValue().isSignBit()) { const APInt &SignBit = XorCst->getValue(); ICmpInst::Predicate Pred = ICI.isSigned() ? ICI.getUnsignedPredicate() : ICI.getSignedPredicate(); return new ICmpInst(Pred, LHSI->getOperand(0), Builder->getInt(RHSV ^ SignBit)); } // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A) if (!ICI.isEquality() && XorCst->isMaxValue(true)) { const APInt &NotSignBit = XorCst->getValue(); ICmpInst::Predicate Pred = ICI.isSigned() ? ICI.getUnsignedPredicate() : ICI.getSignedPredicate(); Pred = ICI.getSwappedPredicate(Pred); return new ICmpInst(Pred, LHSI->getOperand(0), Builder->getInt(RHSV ^ NotSignBit)); } } // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C) // iff -C is a power of 2 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && XorCst->getValue() == ~RHSV && (RHSV + 1).isPowerOf2()) return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCst); // (icmp ult (xor X, C), -C) -> (icmp uge X, C) // iff -C is a power of 2 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && XorCst->getValue() == -RHSV && RHSV.isPowerOf2()) return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCst); } break; case Instruction::And: // (icmp pred (and X, AndCst), RHS) if (LHSI->hasOneUse() && isa(LHSI->getOperand(1)) && LHSI->getOperand(0)->hasOneUse()) { ConstantInt *AndCst = cast(LHSI->getOperand(1)); // If the LHS is an AND of a truncating cast, we can widen the // and/compare to be the input width without changing the value // produced, eliminating a cast. if (TruncInst *Cast = dyn_cast(LHSI->getOperand(0))) { // We can do this transformation if either the AND constant does not // have its sign bit set or if it is an equality comparison. // Extending a relational comparison when we're checking the sign // bit would not work. if (ICI.isEquality() || (!AndCst->isNegative() && RHSV.isNonNegative())) { Value *NewAnd = Builder->CreateAnd(Cast->getOperand(0), ConstantExpr::getZExt(AndCst, Cast->getSrcTy())); NewAnd->takeName(LHSI); return new ICmpInst(ICI.getPredicate(), NewAnd, ConstantExpr::getZExt(RHS, Cast->getSrcTy())); } } // If the LHS is an AND of a zext, and we have an equality compare, we can // shrink the and/compare to the smaller type, eliminating the cast. if (ZExtInst *Cast = dyn_cast(LHSI->getOperand(0))) { IntegerType *Ty = cast(Cast->getSrcTy()); // Make sure we don't compare the upper bits, SimplifyDemandedBits // should fold the icmp to true/false in that case. if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) { Value *NewAnd = Builder->CreateAnd(Cast->getOperand(0), ConstantExpr::getTrunc(AndCst, Ty)); NewAnd->takeName(LHSI); return new ICmpInst(ICI.getPredicate(), NewAnd, ConstantExpr::getTrunc(RHS, Ty)); } } // If this is: (X >> C1) & C2 != C3 (where any shift and any compare // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This // happens a LOT in code produced by the C front-end, for bitfield // access. BinaryOperator *Shift = dyn_cast(LHSI->getOperand(0)); if (Shift && !Shift->isShift()) Shift = nullptr; ConstantInt *ShAmt; ShAmt = Shift ? dyn_cast(Shift->getOperand(1)) : nullptr; // This seemingly simple opportunity to fold away a shift turns out to // be rather complicated. See PR17827 // ( http://llvm.org/bugs/show_bug.cgi?id=17827 ) for details. if (ShAmt) { bool CanFold = false; unsigned ShiftOpcode = Shift->getOpcode(); if (ShiftOpcode == Instruction::AShr) { // There may be some constraints that make this possible, // but nothing simple has been discovered yet. CanFold = false; } else if (ShiftOpcode == Instruction::Shl) { // For a left shift, we can fold if the comparison is not signed. // We can also fold a signed comparison if the mask value and // comparison value are not negative. These constraints may not be // obvious, but we can prove that they are correct using an SMT // solver. if (!ICI.isSigned() || (!AndCst->isNegative() && !RHS->isNegative())) CanFold = true; } else if (ShiftOpcode == Instruction::LShr) { // For a logical right shift, we can fold if the comparison is not // signed. We can also fold a signed comparison if the shifted mask // value and the shifted comparison value are not negative. // These constraints may not be obvious, but we can prove that they // are correct using an SMT solver. if (!ICI.isSigned()) CanFold = true; else { ConstantInt *ShiftedAndCst = cast(ConstantExpr::getShl(AndCst, ShAmt)); ConstantInt *ShiftedRHSCst = cast(ConstantExpr::getShl(RHS, ShAmt)); if (!ShiftedAndCst->isNegative() && !ShiftedRHSCst->isNegative()) CanFold = true; } } if (CanFold) { Constant *NewCst; if (ShiftOpcode == Instruction::Shl) NewCst = ConstantExpr::getLShr(RHS, ShAmt); else NewCst = ConstantExpr::getShl(RHS, ShAmt); // Check to see if we are shifting out any of the bits being // compared. if (ConstantExpr::get(ShiftOpcode, NewCst, ShAmt) != RHS) { // If we shifted bits out, the fold is not going to work out. // As a special case, check to see if this means that the // result is always true or false now. if (ICI.getPredicate() == ICmpInst::ICMP_EQ) return replaceInstUsesWith(ICI, Builder->getFalse()); if (ICI.getPredicate() == ICmpInst::ICMP_NE) return replaceInstUsesWith(ICI, Builder->getTrue()); } else { ICI.setOperand(1, NewCst); Constant *NewAndCst; if (ShiftOpcode == Instruction::Shl) NewAndCst = ConstantExpr::getLShr(AndCst, ShAmt); else NewAndCst = ConstantExpr::getShl(AndCst, ShAmt); LHSI->setOperand(1, NewAndCst); LHSI->setOperand(0, Shift->getOperand(0)); Worklist.Add(Shift); // Shift is dead. return &ICI; } } } // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is // preferable because it allows the C<hasOneUse() && RHSV == 0 && ICI.isEquality() && !Shift->isArithmeticShift() && !isa(Shift->getOperand(0))) { // Compute C << Y. Value *NS; if (Shift->getOpcode() == Instruction::LShr) { NS = Builder->CreateShl(AndCst, Shift->getOperand(1)); } else { // Insert a logical shift. NS = Builder->CreateLShr(AndCst, Shift->getOperand(1)); } // Compute X & (C << Y). Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName()); ICI.setOperand(0, NewAnd); return &ICI; } // (icmp pred (and (or (lshr X, Y), X), 1), 0) --> // (icmp pred (and X, (or (shl 1, Y), 1), 0)) // // iff pred isn't signed { Value *X, *Y, *LShr; if (!ICI.isSigned() && RHSV == 0) { if (match(LHSI->getOperand(1), m_One())) { Constant *One = cast(LHSI->getOperand(1)); Value *Or = LHSI->getOperand(0); if (match(Or, m_Or(m_Value(LShr), m_Value(X))) && match(LShr, m_LShr(m_Specific(X), m_Value(Y)))) { unsigned UsesRemoved = 0; if (LHSI->hasOneUse()) ++UsesRemoved; if (Or->hasOneUse()) ++UsesRemoved; if (LShr->hasOneUse()) ++UsesRemoved; Value *NewOr = nullptr; // Compute X & ((1 << Y) | 1) if (auto *C = dyn_cast(Y)) { if (UsesRemoved >= 1) NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One); } else { if (UsesRemoved >= 3) NewOr = Builder->CreateOr(Builder->CreateShl(One, Y, LShr->getName(), /*HasNUW=*/true), One, Or->getName()); } if (NewOr) { Value *NewAnd = Builder->CreateAnd(X, NewOr, LHSI->getName()); ICI.setOperand(0, NewAnd); return &ICI; } } } } } // Replace ((X & AndCst) > RHSV) with ((X & AndCst) != 0), if any // bit set in (X & AndCst) will produce a result greater than RHSV. if (ICI.getPredicate() == ICmpInst::ICMP_UGT) { unsigned NTZ = AndCst->getValue().countTrailingZeros(); if ((NTZ < AndCst->getBitWidth()) && APInt::getOneBitSet(AndCst->getBitWidth(), NTZ).ugt(RHSV)) return new ICmpInst(ICmpInst::ICMP_NE, LHSI, Constant::getNullValue(RHS->getType())); } } // Try to optimize things like "A[i]&42 == 0" to index computations. if (LoadInst *LI = dyn_cast(LHSI->getOperand(0))) { if (GetElementPtrInst *GEP = dyn_cast(LI->getOperand(0))) if (GlobalVariable *GV = dyn_cast(GEP->getOperand(0))) if (GV->isConstant() && GV->hasDefinitiveInitializer() && !LI->isVolatile() && isa(LHSI->getOperand(1))) { ConstantInt *C = cast(LHSI->getOperand(1)); if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) return Res; } } // X & -C == -C -> X > u ~C // X & -C != -C -> X <= u ~C // iff C is a power of 2 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2()) return new ICmpInst( ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE, LHSI->getOperand(0), SubOne(RHS)); // (icmp eq (and %A, C), 0) -> (icmp sgt (trunc %A), -1) // iff C is a power of 2 if (ICI.isEquality() && LHSI->hasOneUse() && match(RHS, m_Zero())) { if (auto *CI = dyn_cast(LHSI->getOperand(1))) { const APInt &AI = CI->getValue(); int32_t ExactLogBase2 = AI.exactLogBase2(); if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) { Type *NTy = IntegerType::get(ICI.getContext(), ExactLogBase2 + 1); Value *Trunc = Builder->CreateTrunc(LHSI->getOperand(0), NTy); return new ICmpInst(ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_SLT, Trunc, Constant::getNullValue(NTy)); } } } break; case Instruction::Or: { if (RHS->isOne()) { // icmp slt signum(V) 1 --> icmp slt V, 1 Value *V = nullptr; if (ICI.getPredicate() == ICmpInst::ICMP_SLT && match(LHSI, m_Signum(m_Value(V)))) return new ICmpInst(ICmpInst::ICMP_SLT, V, ConstantInt::get(V->getType(), 1)); } if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse()) break; Value *P, *Q; if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 // -> and (icmp eq P, null), (icmp eq Q, null). Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P, Constant::getNullValue(P->getType())); Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q, Constant::getNullValue(Q->getType())); Instruction *Op; if (ICI.getPredicate() == ICmpInst::ICMP_EQ) Op = BinaryOperator::CreateAnd(ICIP, ICIQ); else Op = BinaryOperator::CreateOr(ICIP, ICIQ); return Op; } break; } case Instruction::Mul: { // (icmp pred (mul X, Val), CI) ConstantInt *Val = dyn_cast(LHSI->getOperand(1)); if (!Val) break; // If this is a signed comparison to 0 and the mul is sign preserving, // use the mul LHS operand instead. ICmpInst::Predicate pred = ICI.getPredicate(); if (isSignTest(pred, RHS) && !Val->isZero() && cast(LHSI)->hasNoSignedWrap()) return new ICmpInst(Val->isNegative() ? ICmpInst::getSwappedPredicate(pred) : pred, LHSI->getOperand(0), Constant::getNullValue(RHS->getType())); break; } case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI) uint32_t TypeBits = RHSV.getBitWidth(); ConstantInt *ShAmt = dyn_cast(LHSI->getOperand(1)); if (!ShAmt) { Value *X; // (1 << X) pred P2 -> X pred Log2(P2) if (match(LHSI, m_Shl(m_One(), m_Value(X)))) { bool RHSVIsPowerOf2 = RHSV.isPowerOf2(); ICmpInst::Predicate Pred = ICI.getPredicate(); if (ICI.isUnsigned()) { if (!RHSVIsPowerOf2) { // (1 << X) < 30 -> X <= 4 // (1 << X) <= 30 -> X <= 4 // (1 << X) >= 30 -> X > 4 // (1 << X) > 30 -> X > 4 if (Pred == ICmpInst::ICMP_ULT) Pred = ICmpInst::ICMP_ULE; else if (Pred == ICmpInst::ICMP_UGE) Pred = ICmpInst::ICMP_UGT; } unsigned RHSLog2 = RHSV.logBase2(); // (1 << X) >= 2147483648 -> X >= 31 -> X == 31 // (1 << X) < 2147483648 -> X < 31 -> X != 31 if (RHSLog2 == TypeBits-1) { if (Pred == ICmpInst::ICMP_UGE) Pred = ICmpInst::ICMP_EQ; else if (Pred == ICmpInst::ICMP_ULT) Pred = ICmpInst::ICMP_NE; } return new ICmpInst(Pred, X, ConstantInt::get(RHS->getType(), RHSLog2)); } else if (ICI.isSigned()) { if (RHSV.isAllOnesValue()) { // (1 << X) <= -1 -> X == 31 if (Pred == ICmpInst::ICMP_SLE) return new ICmpInst(ICmpInst::ICMP_EQ, X, ConstantInt::get(RHS->getType(), TypeBits-1)); // (1 << X) > -1 -> X != 31 if (Pred == ICmpInst::ICMP_SGT) return new ICmpInst(ICmpInst::ICMP_NE, X, ConstantInt::get(RHS->getType(), TypeBits-1)); } else if (!RHSV) { // (1 << X) < 0 -> X == 31 // (1 << X) <= 0 -> X == 31 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) return new ICmpInst(ICmpInst::ICMP_EQ, X, ConstantInt::get(RHS->getType(), TypeBits-1)); // (1 << X) >= 0 -> X != 31 // (1 << X) > 0 -> X != 31 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) return new ICmpInst(ICmpInst::ICMP_NE, X, ConstantInt::get(RHS->getType(), TypeBits-1)); } } else if (ICI.isEquality()) { if (RHSVIsPowerOf2) return new ICmpInst( Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2())); } } break; } // Check that the shift amount is in range. If not, don't perform // undefined shifts. When the shift is visited it will be // simplified. if (ShAmt->uge(TypeBits)) break; if (ICI.isEquality()) { // If we are comparing against bits always shifted out, the // comparison cannot succeed. Constant *Comp = ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt); if (Comp != RHS) {// Comparing against a bit that we know is zero. bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; Constant *Cst = Builder->getInt1(IsICMP_NE); return replaceInstUsesWith(ICI, Cst); } // If the shift is NUW, then it is just shifting out zeros, no need for an // AND. if (cast(LHSI)->hasNoUnsignedWrap()) return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), ConstantExpr::getLShr(RHS, ShAmt)); // If the shift is NSW and we compare to 0, then it is just shifting out // sign bits, no need for an AND either. if (cast(LHSI)->hasNoSignedWrap() && RHSV == 0) return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), ConstantExpr::getLShr(RHS, ShAmt)); if (LHSI->hasOneUse()) { // Otherwise strength reduce the shift into an and. uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits, TypeBits - ShAmtVal)); Value *And = Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask"); return new ICmpInst(ICI.getPredicate(), And, ConstantExpr::getLShr(RHS, ShAmt)); } } // If this is a signed comparison to 0 and the shift is sign preserving, // use the shift LHS operand instead. ICmpInst::Predicate pred = ICI.getPredicate(); if (isSignTest(pred, RHS) && cast(LHSI)->hasNoSignedWrap()) return new ICmpInst(pred, LHSI->getOperand(0), Constant::getNullValue(RHS->getType())); // Otherwise, if this is a comparison of the sign bit, simplify to and/test. bool TrueIfSigned = false; if (LHSI->hasOneUse() && isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) { // (X << 31) (X&1) != 0 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(), APInt::getOneBitSet(TypeBits, TypeBits-ShAmt->getZExtValue()-1)); Value *And = Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask"); return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, And, Constant::getNullValue(And->getType())); } // Transform (icmp pred iM (shl iM %v, N), CI) // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N)) // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N. // This enables to get rid of the shift in favor of a trunc which can be // free on the target. It has the additional benefit of comparing to a // smaller constant, which will be target friendly. unsigned Amt = ShAmt->getLimitedValue(TypeBits-1); if (LHSI->hasOneUse() && Amt != 0 && RHSV.countTrailingZeros() >= Amt) { Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt); Constant *NCI = ConstantExpr::getTrunc( ConstantExpr::getAShr(RHS, ConstantInt::get(RHS->getType(), Amt)), NTy); return new ICmpInst(ICI.getPredicate(), Builder->CreateTrunc(LHSI->getOperand(0), NTy), NCI); } break; } case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI) case Instruction::AShr: { // Handle equality comparisons of shift-by-constant. BinaryOperator *BO = cast(LHSI); if (ConstantInt *ShAmt = dyn_cast(LHSI->getOperand(1))) { if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt)) return Res; } // Handle exact shr's. if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) { if (RHSV.isMinValue()) return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS); } break; } case Instruction::UDiv: if (ConstantInt *DivLHS = dyn_cast(LHSI->getOperand(0))) { Value *X = LHSI->getOperand(1); const APInt &C1 = RHS->getValue(); const APInt &C2 = DivLHS->getValue(); assert(C2 != 0 && "udiv 0, X should have been simplified already."); // (icmp ugt (udiv C2, X), C1) -> (icmp ule X, C2/(C1+1)) if (ICI.getPredicate() == ICmpInst::ICMP_UGT) { assert(!C1.isMaxValue() && "icmp ugt X, UINT_MAX should have been simplified already."); return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(X->getType(), C2.udiv(C1 + 1))); } // (icmp ult (udiv C2, X), C1) -> (icmp ugt X, C2/C1) if (ICI.getPredicate() == ICmpInst::ICMP_ULT) { assert(C1 != 0 && "icmp ult X, 0 should have been simplified already."); return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(X->getType(), C2.udiv(C1))); } } // fall-through case Instruction::SDiv: // Fold: icmp pred ([us]div X, C1), C2 -> range test // Fold this div into the comparison, producing a range check. // Determine, based on the divide type, what the range is being // checked. If there is an overflow on the low or high side, remember // it, otherwise compute the range [low, hi) bounding the new value. // See: InsertRangeTest above for the kinds of replacements possible. if (ConstantInt *DivRHS = dyn_cast(LHSI->getOperand(1))) if (Instruction *R = FoldICmpDivCst(ICI, cast(LHSI), DivRHS)) return R; break; case Instruction::Sub: { ConstantInt *LHSC = dyn_cast(LHSI->getOperand(0)); if (!LHSC) break; const APInt &LHSV = LHSC->getValue(); // C1-X (X|(C2-1)) == C1 // iff C1 & (C2-1) == C2-1 // C2 is a power of 2 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() && RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1)) return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateOr(LHSI->getOperand(1), RHSV - 1), LHSC); // C1-X >u C2 -> (X|C2) != C1 // iff C1 & C2 == C2 // C2+1 is a power of 2 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() && (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV) return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC); break; } case Instruction::Add: // Fold: icmp pred (add X, C1), C2 if (!ICI.isEquality()) { ConstantInt *LHSC = dyn_cast(LHSI->getOperand(1)); if (!LHSC) break; const APInt &LHSV = LHSC->getValue(); ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV) .subtract(LHSV); if (ICI.isSigned()) { if (CR.getLower().isSignBit()) { return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0), Builder->getInt(CR.getUpper())); } else if (CR.getUpper().isSignBit()) { return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0), Builder->getInt(CR.getLower())); } } else { if (CR.getLower().isMinValue()) { return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), Builder->getInt(CR.getUpper())); } else if (CR.getUpper().isMinValue()) { return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), Builder->getInt(CR.getLower())); } } // X-C1 (X & -C2) == C1 // iff C1 & (C2-1) == 0 // C2 is a power of 2 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() && RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0) return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(LHSI->getOperand(0), -RHSV), ConstantExpr::getNeg(LHSC)); // X-C1 >u C2 -> (X & ~C2) != C1 // iff C1 & C2 == 0 // C2+1 is a power of 2 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() && (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0) return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(LHSI->getOperand(0), ~RHSV), ConstantExpr::getNeg(LHSC)); } break; } // Simplify icmp_eq and icmp_ne instructions with integer constant RHS. if (ICI.isEquality()) { bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; // If the first operand is (add|sub|and|or|xor|rem) with a constant, and // the second operand is a constant, simplify a bit. if (BinaryOperator *BO = dyn_cast(LHSI)) { switch (BO->getOpcode()) { case Instruction::SRem: // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. if (RHSV == 0 && isa(BO->getOperand(1)) &&BO->hasOneUse()){ const APInt &V = cast(BO->getOperand(1))->getValue(); if (V.sgt(1) && V.isPowerOf2()) { Value *NewRem = Builder->CreateURem(BO->getOperand(0), BO->getOperand(1), BO->getName()); return new ICmpInst(ICI.getPredicate(), NewRem, Constant::getNullValue(BO->getType())); } } break; case Instruction::Add: // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. if (ConstantInt *BOp1C = dyn_cast(BO->getOperand(1))) { if (BO->hasOneUse()) return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), ConstantExpr::getSub(RHS, BOp1C)); } else if (RHSV == 0) { // Replace ((add A, B) != 0) with (A != -B) if A or B is // efficiently invertible, or if the add has just this one use. Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); if (Value *NegVal = dyn_castNegVal(BOp1)) return new ICmpInst(ICI.getPredicate(), BOp0, NegVal); if (Value *NegVal = dyn_castNegVal(BOp0)) return new ICmpInst(ICI.getPredicate(), NegVal, BOp1); if (BO->hasOneUse()) { Value *Neg = Builder->CreateNeg(BOp1); Neg->takeName(BO); return new ICmpInst(ICI.getPredicate(), BOp0, Neg); } } break; case Instruction::Xor: if (BO->hasOneUse()) { if (Constant *BOC = dyn_cast(BO->getOperand(1))) { // For the xor case, we can xor two constants together, eliminating // the explicit xor. return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), ConstantExpr::getXor(RHS, BOC)); } else if (RHSV == 0) { // Replace ((xor A, B) != 0) with (A != B) return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), BO->getOperand(1)); } } break; case Instruction::Sub: if (BO->hasOneUse()) { if (ConstantInt *BOp0C = dyn_cast(BO->getOperand(0))) { // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants. return new ICmpInst(ICI.getPredicate(), BO->getOperand(1), ConstantExpr::getSub(BOp0C, RHS)); } else if (RHSV == 0) { // Replace ((sub A, B) != 0) with (A != B) return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), BO->getOperand(1)); } } break; case Instruction::Or: // If bits are being or'd in that are not present in the constant we // are comparing against, then the comparison could never succeed! if (ConstantInt *BOC = dyn_cast(BO->getOperand(1))) { Constant *NotCI = ConstantExpr::getNot(RHS); if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue()) return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE)); // Comparing if all bits outside of a constant mask are set? // Replace (X | C) == -1 with (X & ~C) == ~C. // This removes the -1 constant. if (BO->hasOneUse() && RHS->isAllOnesValue()) { Constant *NotBOC = ConstantExpr::getNot(BOC); Value *And = Builder->CreateAnd(BO->getOperand(0), NotBOC); return new ICmpInst(ICI.getPredicate(), And, NotBOC); } } break; case Instruction::And: if (ConstantInt *BOC = dyn_cast(BO->getOperand(1))) { // If bits are being compared against that are and'd out, then the // comparison can never succeed! if ((RHSV & ~BOC->getValue()) != 0) return replaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE)); // If we have ((X & C) == C), turn it into ((X & C) != 0). if (RHS == BOC && RHSV.isPowerOf2()) return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, LHSI, Constant::getNullValue(RHS->getType())); // Don't perform the following transforms if the AND has multiple uses if (!BO->hasOneUse()) break; // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 if (BOC->getValue().isSignBit()) { Value *X = BO->getOperand(0); Constant *Zero = Constant::getNullValue(X->getType()); ICmpInst::Predicate pred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; return new ICmpInst(pred, X, Zero); } // ((X & ~7) == 0) --> X < 8 if (RHSV == 0 && isHighOnes(BOC)) { Value *X = BO->getOperand(0); Constant *NegX = ConstantExpr::getNeg(BOC); ICmpInst::Predicate pred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; return new ICmpInst(pred, X, NegX); } } break; case Instruction::Mul: if (RHSV == 0 && BO->hasNoSignedWrap()) { if (ConstantInt *BOC = dyn_cast(BO->getOperand(1))) { // The trivial case (mul X, 0) is handled by InstSimplify // General case : (mul X, C) != 0 iff X != 0 // (mul X, C) == 0 iff X == 0 if (!BOC->isZero()) return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), Constant::getNullValue(RHS->getType())); } } break; default: break; } } else if (IntrinsicInst *II = dyn_cast(LHSI)) { // Handle icmp {eq|ne} , intcst. switch (II->getIntrinsicID()) { case Intrinsic::bswap: Worklist.Add(II); ICI.setOperand(0, II->getArgOperand(0)); ICI.setOperand(1, Builder->getInt(RHSV.byteSwap())); return &ICI; case Intrinsic::ctlz: case Intrinsic::cttz: // ctz(A) == bitwidth(a) -> A == 0 and likewise for != if (RHSV == RHS->getType()->getBitWidth()) { Worklist.Add(II); ICI.setOperand(0, II->getArgOperand(0)); ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0)); return &ICI; } break; case Intrinsic::ctpop: // popcount(A) == 0 -> A == 0 and likewise for != if (RHS->isZero()) { Worklist.Add(II); ICI.setOperand(0, II->getArgOperand(0)); ICI.setOperand(1, RHS); return &ICI; } break; default: break; } } } return nullptr; } /// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so /// far. Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICmp) { const CastInst *LHSCI = cast(ICmp.getOperand(0)); Value *LHSCIOp = LHSCI->getOperand(0); Type *SrcTy = LHSCIOp->getType(); Type *DestTy = LHSCI->getType(); Value *RHSCIOp; // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the // integer type is the same size as the pointer type. if (LHSCI->getOpcode() == Instruction::PtrToInt && DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) { Value *RHSOp = nullptr; if (auto *RHSC = dyn_cast(ICmp.getOperand(1))) { Value *RHSCIOp = RHSC->getOperand(0); if (RHSCIOp->getType()->getPointerAddressSpace() == LHSCIOp->getType()->getPointerAddressSpace()) { RHSOp = RHSC->getOperand(0); // If the pointer types don't match, insert a bitcast. if (LHSCIOp->getType() != RHSOp->getType()) RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType()); } } else if (auto *RHSC = dyn_cast(ICmp.getOperand(1))) { RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); } if (RHSOp) return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp); } // The code below only handles extension cast instructions, so far. // Enforce this. if (LHSCI->getOpcode() != Instruction::ZExt && LHSCI->getOpcode() != Instruction::SExt) return nullptr; bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; bool isSignedCmp = ICmp.isSigned(); if (auto *CI = dyn_cast(ICmp.getOperand(1))) { // Not an extension from the same type? RHSCIOp = CI->getOperand(0); if (RHSCIOp->getType() != LHSCIOp->getType()) return nullptr; // If the signedness of the two casts doesn't agree (i.e. one is a sext // and the other is a zext), then we can't handle this. if (CI->getOpcode() != LHSCI->getOpcode()) return nullptr; // Deal with equality cases early. if (ICmp.isEquality()) return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); // A signed comparison of sign extended values simplifies into a // signed comparison. if (isSignedCmp && isSignedExt) return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); // The other three cases all fold into an unsigned comparison. return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp); } // If we aren't dealing with a constant on the RHS, exit early. auto *C = dyn_cast(ICmp.getOperand(1)); if (!C) return nullptr; // Compute the constant that would happen if we truncated to SrcTy then // re-extended to DestTy. Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy); Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy); // If the re-extended constant didn't change... if (Res2 == C) { // Deal with equality cases early. if (ICmp.isEquality()) return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); // A signed comparison of sign extended values simplifies into a // signed comparison. if (isSignedExt && isSignedCmp) return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); // The other three cases all fold into an unsigned comparison. return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1); } // The re-extended constant changed, partly changed (in the case of a vector), // or could not be determined to be equal (in the case of a constant // expression), so the constant cannot be represented in the shorter type. // Consequently, we cannot emit a simple comparison. // All the cases that fold to true or false will have already been handled // by SimplifyICmpInst, so only deal with the tricky case. if (isSignedCmp || !isSignedExt || !isa(C)) return nullptr; // Evaluate the comparison for LT (we invert for GT below). LE and GE cases // should have been folded away previously and not enter in here. // We're performing an unsigned comp with a sign extended value. // This is true if the input is >= 0. [aka >s -1] Constant *NegOne = Constant::getAllOnesValue(SrcTy); Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName()); // Finally, return the value computed. if (ICmp.getPredicate() == ICmpInst::ICMP_ULT) return replaceInstUsesWith(ICmp, Result); assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); return BinaryOperator::CreateNot(Result); } /// The caller has matched a pattern of the form: /// I = icmp ugt (add (add A, B), CI2), CI1 /// If this is of the form: /// sum = a + b /// if (sum+128 >u 255) /// Then replace it with llvm.sadd.with.overflow.i8. /// static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombiner &IC) { // The transformation we're trying to do here is to transform this into an // llvm.sadd.with.overflow. To do this, we have to replace the original add // with a narrower add, and discard the add-with-constant that is part of the // range check (if we can't eliminate it, this isn't profitable). // In order to eliminate the add-with-constant, the compare can be its only // use. Instruction *AddWithCst = cast(I.getOperand(0)); if (!AddWithCst->hasOneUse()) return nullptr; // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. if (!CI2->getValue().isPowerOf2()) return nullptr; unsigned NewWidth = CI2->getValue().countTrailingZeros(); if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return nullptr; // The width of the new add formed is 1 more than the bias. ++NewWidth; // Check to see that CI1 is an all-ones value with NewWidth bits. if (CI1->getBitWidth() == NewWidth || CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) return nullptr; // This is only really a signed overflow check if the inputs have been // sign-extended; check for that condition. For example, if CI2 is 2^31 and // the operands of the add are 64 bits wide, we need at least 33 sign bits. unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1; if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits || IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits) return nullptr; // In order to replace the original add with a narrower // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant // and truncates that discard the high bits of the add. Verify that this is // the case. Instruction *OrigAdd = cast(AddWithCst->getOperand(0)); for (User *U : OrigAdd->users()) { if (U == AddWithCst) continue; // Only accept truncates for now. We would really like a nice recursive // predicate like SimplifyDemandedBits, but which goes downwards the use-def // chain to see which bits of a value are actually demanded. If the // original add had another add which was then immediately truncated, we // could still do the transformation. TruncInst *TI = dyn_cast(U); if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth) return nullptr; } // If the pattern matches, truncate the inputs to the narrower type and // use the sadd_with_overflow intrinsic to efficiently compute both the // result and the overflow bit. Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); Value *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::sadd_with_overflow, NewType); InstCombiner::BuilderTy *Builder = IC.Builder; // Put the new code above the original add, in case there are any uses of the // add between the add and the compare. Builder->SetInsertPoint(OrigAdd); Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc"); Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc"); CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd"); Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result"); Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType()); // The inner add was the result of the narrow add, zero extended to the // wider type. Replace it with the result computed by the intrinsic. IC.replaceInstUsesWith(*OrigAdd, ZExt); // The original icmp gets replaced with the overflow value. return ExtractValueInst::Create(Call, 1, "sadd.overflow"); } bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, Value *RHS, Instruction &OrigI, Value *&Result, Constant *&Overflow) { if (OrigI.isCommutative() && isa(LHS) && !isa(RHS)) std::swap(LHS, RHS); auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) { Result = OpResult; Overflow = OverflowVal; if (ReuseName) Result->takeName(&OrigI); return true; }; // If the overflow check was an add followed by a compare, the insertion point // may be pointing to the compare. We want to insert the new instructions // before the add in case there are uses of the add between the add and the // compare. Builder->SetInsertPoint(&OrigI); switch (OCF) { case OCF_INVALID: llvm_unreachable("bad overflow check kind!"); case OCF_UNSIGNED_ADD: { OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI); if (OR == OverflowResult::NeverOverflows) return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(), true); if (OR == OverflowResult::AlwaysOverflows) return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true); } // FALL THROUGH uadd into sadd case OCF_SIGNED_ADD: { // X + 0 -> {X, false} if (match(RHS, m_Zero())) return SetResult(LHS, Builder->getFalse(), false); // We can strength reduce this signed add into a regular add if we can prove // that it will never overflow. if (OCF == OCF_SIGNED_ADD) if (WillNotOverflowSignedAdd(LHS, RHS, OrigI)) return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(), true); break; } case OCF_UNSIGNED_SUB: case OCF_SIGNED_SUB: { // X - 0 -> {X, false} if (match(RHS, m_Zero())) return SetResult(LHS, Builder->getFalse(), false); if (OCF == OCF_SIGNED_SUB) { if (WillNotOverflowSignedSub(LHS, RHS, OrigI)) return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(), true); } else { if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI)) return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(), true); } break; } case OCF_UNSIGNED_MUL: { OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI); if (OR == OverflowResult::NeverOverflows) return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(), true); if (OR == OverflowResult::AlwaysOverflows) return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true); } // FALL THROUGH case OCF_SIGNED_MUL: // X * undef -> undef if (isa(RHS)) return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false); // X * 0 -> {0, false} if (match(RHS, m_Zero())) return SetResult(RHS, Builder->getFalse(), false); // X * 1 -> {X, false} if (match(RHS, m_One())) return SetResult(LHS, Builder->getFalse(), false); if (OCF == OCF_SIGNED_MUL) if (WillNotOverflowSignedMul(LHS, RHS, OrigI)) return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(), true); break; } return false; } /// \brief Recognize and process idiom involving test for multiplication /// overflow. /// /// The caller has matched a pattern of the form: /// I = cmp u (mul(zext A, zext B), V /// The function checks if this is a test for overflow and if so replaces /// multiplication with call to 'mul.with.overflow' intrinsic. /// /// \param I Compare instruction. /// \param MulVal Result of 'mult' instruction. It is one of the arguments of /// the compare instruction. Must be of integer type. /// \param OtherVal The other argument of compare instruction. /// \returns Instruction which must replace the compare instruction, NULL if no /// replacement required. static Instruction *ProcessUMulZExtIdiom(ICmpInst &I, Value *MulVal, Value *OtherVal, InstCombiner &IC) { // Don't bother doing this transformation for pointers, don't do it for // vectors. if (!isa(MulVal->getType())) return nullptr; assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal); assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal); auto *MulInstr = dyn_cast(MulVal); if (!MulInstr) return nullptr; assert(MulInstr->getOpcode() == Instruction::Mul); auto *LHS = cast(MulInstr->getOperand(0)), *RHS = cast(MulInstr->getOperand(1)); assert(LHS->getOpcode() == Instruction::ZExt); assert(RHS->getOpcode() == Instruction::ZExt); Value *A = LHS->getOperand(0), *B = RHS->getOperand(0); // Calculate type and width of the result produced by mul.with.overflow. Type *TyA = A->getType(), *TyB = B->getType(); unsigned WidthA = TyA->getPrimitiveSizeInBits(), WidthB = TyB->getPrimitiveSizeInBits(); unsigned MulWidth; Type *MulType; if (WidthB > WidthA) { MulWidth = WidthB; MulType = TyB; } else { MulWidth = WidthA; MulType = TyA; } // In order to replace the original mul with a narrower mul.with.overflow, // all uses must ignore upper bits of the product. The number of used low // bits must be not greater than the width of mul.with.overflow. if (MulVal->hasNUsesOrMore(2)) for (User *U : MulVal->users()) { if (U == &I) continue; if (TruncInst *TI = dyn_cast(U)) { // Check if truncation ignores bits above MulWidth. unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits(); if (TruncWidth > MulWidth) return nullptr; } else if (BinaryOperator *BO = dyn_cast(U)) { // Check if AND ignores bits above MulWidth. if (BO->getOpcode() != Instruction::And) return nullptr; if (ConstantInt *CI = dyn_cast(BO->getOperand(1))) { const APInt &CVal = CI->getValue(); if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth) return nullptr; } } else { // Other uses prohibit this transformation. return nullptr; } } // Recognize patterns switch (I.getPredicate()) { case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: // Recognize pattern: // mulval = mul(zext A, zext B) // cmp eq/neq mulval, zext trunc mulval if (ZExtInst *Zext = dyn_cast(OtherVal)) if (Zext->hasOneUse()) { Value *ZextArg = Zext->getOperand(0); if (TruncInst *Trunc = dyn_cast(ZextArg)) if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth) break; //Recognized } // Recognize pattern: // mulval = mul(zext A, zext B) // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits. ConstantInt *CI; Value *ValToMask; if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) { if (ValToMask != MulVal) return nullptr; const APInt &CVal = CI->getValue() + 1; if (CVal.isPowerOf2()) { unsigned MaskWidth = CVal.logBase2(); if (MaskWidth == MulWidth) break; // Recognized } } return nullptr; case ICmpInst::ICMP_UGT: // Recognize pattern: // mulval = mul(zext A, zext B) // cmp ugt mulval, max if (ConstantInt *CI = dyn_cast(OtherVal)) { APInt MaxVal = APInt::getMaxValue(MulWidth); MaxVal = MaxVal.zext(CI->getBitWidth()); if (MaxVal.eq(CI->getValue())) break; // Recognized } return nullptr; case ICmpInst::ICMP_UGE: // Recognize pattern: // mulval = mul(zext A, zext B) // cmp uge mulval, max+1 if (ConstantInt *CI = dyn_cast(OtherVal)) { APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); if (MaxVal.eq(CI->getValue())) break; // Recognized } return nullptr; case ICmpInst::ICMP_ULE: // Recognize pattern: // mulval = mul(zext A, zext B) // cmp ule mulval, max if (ConstantInt *CI = dyn_cast(OtherVal)) { APInt MaxVal = APInt::getMaxValue(MulWidth); MaxVal = MaxVal.zext(CI->getBitWidth()); if (MaxVal.eq(CI->getValue())) break; // Recognized } return nullptr; case ICmpInst::ICMP_ULT: // Recognize pattern: // mulval = mul(zext A, zext B) // cmp ule mulval, max + 1 if (ConstantInt *CI = dyn_cast(OtherVal)) { APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); if (MaxVal.eq(CI->getValue())) break; // Recognized } return nullptr; default: return nullptr; } InstCombiner::BuilderTy *Builder = IC.Builder; Builder->SetInsertPoint(MulInstr); // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B) Value *MulA = A, *MulB = B; if (WidthA < MulWidth) MulA = Builder->CreateZExt(A, MulType); if (WidthB < MulWidth) MulB = Builder->CreateZExt(B, MulType); Value *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::umul_with_overflow, MulType); CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul"); IC.Worklist.Add(MulInstr); // If there are uses of mul result other than the comparison, we know that // they are truncation or binary AND. Change them to use result of // mul.with.overflow and adjust properly mask/size. if (MulVal->hasNUsesOrMore(2)) { Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value"); for (User *U : MulVal->users()) { if (U == &I || U == OtherVal) continue; if (TruncInst *TI = dyn_cast(U)) { if (TI->getType()->getPrimitiveSizeInBits() == MulWidth) IC.replaceInstUsesWith(*TI, Mul); else TI->setOperand(0, Mul); } else if (BinaryOperator *BO = dyn_cast(U)) { assert(BO->getOpcode() == Instruction::And); // Replace (mul & mask) --> zext (mul.with.overflow & short_mask) ConstantInt *CI = cast(BO->getOperand(1)); APInt ShortMask = CI->getValue().trunc(MulWidth); Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask); Instruction *Zext = cast(Builder->CreateZExt(ShortAnd, BO->getType())); IC.Worklist.Add(Zext); IC.replaceInstUsesWith(*BO, Zext); } else { llvm_unreachable("Unexpected Binary operation"); } IC.Worklist.Add(cast(U)); } } if (isa(OtherVal)) IC.Worklist.Add(cast(OtherVal)); // The original icmp gets replaced with the overflow value, maybe inverted // depending on predicate. bool Inverse = false; switch (I.getPredicate()) { case ICmpInst::ICMP_NE: break; case ICmpInst::ICMP_EQ: Inverse = true; break; case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_UGE: if (I.getOperand(0) == MulVal) break; Inverse = true; break; case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: if (I.getOperand(1) == MulVal) break; Inverse = true; break; default: llvm_unreachable("Unexpected predicate"); } if (Inverse) { Value *Res = Builder->CreateExtractValue(Call, 1); return BinaryOperator::CreateNot(Res); } return ExtractValueInst::Create(Call, 1); } /// When performing a comparison against a constant, it is possible that not all /// the bits in the LHS are demanded. This helper method computes the mask that /// IS demanded. static APInt DemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth, bool isSignCheck) { if (isSignCheck) return APInt::getSignBit(BitWidth); ConstantInt *CI = dyn_cast(I.getOperand(1)); if (!CI) return APInt::getAllOnesValue(BitWidth); const APInt &RHS = CI->getValue(); switch (I.getPredicate()) { // For a UGT comparison, we don't care about any bits that // correspond to the trailing ones of the comparand. The value of these // bits doesn't impact the outcome of the comparison, because any value // greater than the RHS must differ in a bit higher than these due to carry. case ICmpInst::ICMP_UGT: { unsigned trailingOnes = RHS.countTrailingOnes(); APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes); return ~lowBitsSet; } // Similarly, for a ULT comparison, we don't care about the trailing zeros. // Any value less than the RHS must differ in a higher bit because of carries. case ICmpInst::ICMP_ULT: { unsigned trailingZeros = RHS.countTrailingZeros(); APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros); return ~lowBitsSet; } default: return APInt::getAllOnesValue(BitWidth); } } /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst /// should be swapped. /// The decision is based on how many times these two operands are reused /// as subtract operands and their positions in those instructions. /// The rational is that several architectures use the same instruction for /// both subtract and cmp, thus it is better if the order of those operands /// match. /// \return true if Op0 and Op1 should be swapped. static bool swapMayExposeCSEOpportunities(const Value * Op0, const Value * Op1) { // Filter out pointer value as those cannot appears directly in subtract. // FIXME: we may want to go through inttoptrs or bitcasts. if (Op0->getType()->isPointerTy()) return false; // Count every uses of both Op0 and Op1 in a subtract. // Each time Op0 is the first operand, count -1: swapping is bad, the // subtract has already the same layout as the compare. // Each time Op0 is the second operand, count +1: swapping is good, the // subtract has a different layout as the compare. // At the end, if the benefit is greater than 0, Op0 should come second to // expose more CSE opportunities. int GlobalSwapBenefits = 0; for (const User *U : Op0->users()) { const BinaryOperator *BinOp = dyn_cast(U); if (!BinOp || BinOp->getOpcode() != Instruction::Sub) continue; // If Op0 is the first argument, this is not beneficial to swap the // arguments. int LocalSwapBenefits = -1; unsigned Op1Idx = 1; if (BinOp->getOperand(Op1Idx) == Op0) { Op1Idx = 0; LocalSwapBenefits = 1; } if (BinOp->getOperand(Op1Idx) != Op1) continue; GlobalSwapBenefits += LocalSwapBenefits; } return GlobalSwapBenefits > 0; } /// \brief Check that one use is in the same block as the definition and all /// other uses are in blocks dominated by a given block /// /// \param DI Definition /// \param UI Use /// \param DB Block that must dominate all uses of \p DI outside /// the parent block /// \return true when \p UI is the only use of \p DI in the parent block /// and all other uses of \p DI are in blocks dominated by \p DB. /// bool InstCombiner::dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const { assert(DI && UI && "Instruction not defined\n"); // ignore incomplete definitions if (!DI->getParent()) return false; // DI and UI must be in the same block if (DI->getParent() != UI->getParent()) return false; // Protect from self-referencing blocks if (DI->getParent() == DB) return false; // DominatorTree available? if (!DT) return false; for (const User *U : DI->users()) { auto *Usr = cast(U); if (Usr != UI && !DT->dominates(DB, Usr->getParent())) return false; } return true; } /// Return true when the instruction sequence within a block is select-cmp-br. static bool isChainSelectCmpBranch(const SelectInst *SI) { const BasicBlock *BB = SI->getParent(); if (!BB) return false; auto *BI = dyn_cast_or_null(BB->getTerminator()); if (!BI || BI->getNumSuccessors() != 2) return false; auto *IC = dyn_cast(BI->getCondition()); if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI)) return false; return true; } /// \brief True when a select result is replaced by one of its operands /// in select-icmp sequence. This will eventually result in the elimination /// of the select. /// /// \param SI Select instruction /// \param Icmp Compare instruction /// \param SIOpd Operand that replaces the select /// /// Notes: /// - The replacement is global and requires dominator information /// - The caller is responsible for the actual replacement /// /// Example: /// /// entry: /// %4 = select i1 %3, %C* %0, %C* null /// %5 = icmp eq %C* %4, null /// br i1 %5, label %9, label %7 /// ... /// ;