Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
35266 views
//===- InstCombineCompares.cpp --------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the visitICmp and visitFCmp functions.9//10//===----------------------------------------------------------------------===//1112#include "InstCombineInternal.h"13#include "llvm/ADT/APSInt.h"14#include "llvm/ADT/ScopeExit.h"15#include "llvm/ADT/SetVector.h"16#include "llvm/ADT/Statistic.h"17#include "llvm/Analysis/CaptureTracking.h"18#include "llvm/Analysis/CmpInstAnalysis.h"19#include "llvm/Analysis/ConstantFolding.h"20#include "llvm/Analysis/InstructionSimplify.h"21#include "llvm/Analysis/Utils/Local.h"22#include "llvm/Analysis/VectorUtils.h"23#include "llvm/IR/ConstantRange.h"24#include "llvm/IR/DataLayout.h"25#include "llvm/IR/InstrTypes.h"26#include "llvm/IR/IntrinsicInst.h"27#include "llvm/IR/PatternMatch.h"28#include "llvm/Support/KnownBits.h"29#include "llvm/Transforms/InstCombine/InstCombiner.h"30#include <bitset>3132using namespace llvm;33using namespace PatternMatch;3435#define DEBUG_TYPE "instcombine"3637// How many times is a select replaced by one of its operands?38STATISTIC(NumSel, "Number of select opts");394041/// Compute Result = In1+In2, returning true if the result overflowed for this42/// type.43static bool addWithOverflow(APInt &Result, const APInt &In1,44const APInt &In2, bool IsSigned = false) {45bool Overflow;46if (IsSigned)47Result = In1.sadd_ov(In2, Overflow);48else49Result = In1.uadd_ov(In2, Overflow);5051return Overflow;52}5354/// Compute Result = In1-In2, returning true if the result overflowed for this55/// type.56static bool subWithOverflow(APInt &Result, const APInt &In1,57const APInt &In2, bool IsSigned = false) {58bool Overflow;59if (IsSigned)60Result = In1.ssub_ov(In2, Overflow);61else62Result = In1.usub_ov(In2, Overflow);6364return Overflow;65}6667/// Given an icmp instruction, return true if any use of this comparison is a68/// branch on sign bit comparison.69static bool hasBranchUse(ICmpInst &I) {70for (auto *U : I.users())71if (isa<BranchInst>(U))72return true;73return false;74}7576/// Returns true if the exploded icmp can be expressed as a signed comparison77/// to zero and updates the predicate accordingly.78/// The signedness of the comparison is preserved.79/// TODO: Refactor with decomposeBitTestICmp()?80static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {81if (!ICmpInst::isSigned(Pred))82return false;8384if (C.isZero())85return ICmpInst::isRelational(Pred);8687if (C.isOne()) {88if (Pred == ICmpInst::ICMP_SLT) {89Pred = ICmpInst::ICMP_SLE;90return true;91}92} else if (C.isAllOnes()) {93if (Pred == ICmpInst::ICMP_SGT) {94Pred = ICmpInst::ICMP_SGE;95return true;96}97}9899return false;100}101102/// This is called when we see this pattern:103/// cmp pred (load (gep GV, ...)), cmpcst104/// where GV is a global variable with a constant initializer. Try to simplify105/// this into some simple computation that does not need the load. For example106/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".107///108/// If AndCst is non-null, then the loaded value is masked with that constant109/// before doing the comparison. This handles cases like "A[i]&4 == 0".110Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(111LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,112ConstantInt *AndCst) {113if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||114GV->getValueType() != GEP->getSourceElementType() || !GV->isConstant() ||115!GV->hasDefinitiveInitializer())116return nullptr;117118Constant *Init = GV->getInitializer();119if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))120return nullptr;121122uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();123// Don't blow up on huge arrays.124if (ArrayElementCount > MaxArraySizeForCombine)125return nullptr;126127// There are many forms of this optimization we can handle, for now, just do128// the simple index into a single-dimensional array.129//130// Require: GEP GV, 0, i {{, constant indices}}131if (GEP->getNumOperands() < 3 || !isa<ConstantInt>(GEP->getOperand(1)) ||132!cast<ConstantInt>(GEP->getOperand(1))->isZero() ||133isa<Constant>(GEP->getOperand(2)))134return nullptr;135136// Check that indices after the variable are constants and in-range for the137// type they index. Collect the indices. This is typically for arrays of138// structs.139SmallVector<unsigned, 4> LaterIndices;140141Type *EltTy = Init->getType()->getArrayElementType();142for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {143ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));144if (!Idx)145return nullptr; // Variable index.146147uint64_t IdxVal = Idx->getZExtValue();148if ((unsigned)IdxVal != IdxVal)149return nullptr; // Too large array index.150151if (StructType *STy = dyn_cast<StructType>(EltTy))152EltTy = STy->getElementType(IdxVal);153else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {154if (IdxVal >= ATy->getNumElements())155return nullptr;156EltTy = ATy->getElementType();157} else {158return nullptr; // Unknown type.159}160161LaterIndices.push_back(IdxVal);162}163164enum { Overdefined = -3, Undefined = -2 };165166// Variables for our state machines.167168// FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form169// "i == 47 | i == 87", where 47 is the first index the condition is true for,170// and 87 is the second (and last) index. FirstTrueElement is -2 when171// undefined, otherwise set to the first true element. SecondTrueElement is172// -2 when undefined, -3 when overdefined and >= 0 when that index is true.173int FirstTrueElement = Undefined, SecondTrueElement = Undefined;174175// FirstFalseElement/SecondFalseElement - Used to emit a comparison of the176// form "i != 47 & i != 87". Same state transitions as for true elements.177int FirstFalseElement = Undefined, SecondFalseElement = Undefined;178179/// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these180/// define a state machine that triggers for ranges of values that the index181/// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.182/// This is -2 when undefined, -3 when overdefined, and otherwise the last183/// index in the range (inclusive). We use -2 for undefined here because we184/// use relative comparisons and don't want 0-1 to match -1.185int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;186187// MagicBitvector - This is a magic bitvector where we set a bit if the188// comparison is true for element 'i'. If there are 64 elements or less in189// the array, this will fully represent all the comparison results.190uint64_t MagicBitvector = 0;191192// Scan the array and see if one of our patterns matches.193Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));194for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {195Constant *Elt = Init->getAggregateElement(i);196if (!Elt)197return nullptr;198199// If this is indexing an array of structures, get the structure element.200if (!LaterIndices.empty()) {201Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);202if (!Elt)203return nullptr;204}205206// If the element is masked, handle it.207if (AndCst) {208Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);209if (!Elt)210return nullptr;211}212213// Find out if the comparison would be true or false for the i'th element.214Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,215CompareRHS, DL, &TLI);216if (!C)217return nullptr;218219// If the result is undef for this element, ignore it.220if (isa<UndefValue>(C)) {221// Extend range state machines to cover this element in case there is an222// undef in the middle of the range.223if (TrueRangeEnd == (int)i - 1)224TrueRangeEnd = i;225if (FalseRangeEnd == (int)i - 1)226FalseRangeEnd = i;227continue;228}229230// If we can't compute the result for any of the elements, we have to give231// up evaluating the entire conditional.232if (!isa<ConstantInt>(C))233return nullptr;234235// Otherwise, we know if the comparison is true or false for this element,236// update our state machines.237bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();238239// State machine for single/double/range index comparison.240if (IsTrueForElt) {241// Update the TrueElement state machine.242if (FirstTrueElement == Undefined)243FirstTrueElement = TrueRangeEnd = i; // First true element.244else {245// Update double-compare state machine.246if (SecondTrueElement == Undefined)247SecondTrueElement = i;248else249SecondTrueElement = Overdefined;250251// Update range state machine.252if (TrueRangeEnd == (int)i - 1)253TrueRangeEnd = i;254else255TrueRangeEnd = Overdefined;256}257} else {258// Update the FalseElement state machine.259if (FirstFalseElement == Undefined)260FirstFalseElement = FalseRangeEnd = i; // First false element.261else {262// Update double-compare state machine.263if (SecondFalseElement == Undefined)264SecondFalseElement = i;265else266SecondFalseElement = Overdefined;267268// Update range state machine.269if (FalseRangeEnd == (int)i - 1)270FalseRangeEnd = i;271else272FalseRangeEnd = Overdefined;273}274}275276// If this element is in range, update our magic bitvector.277if (i < 64 && IsTrueForElt)278MagicBitvector |= 1ULL << i;279280// If all of our states become overdefined, bail out early. Since the281// predicate is expensive, only check it every 8 elements. This is only282// really useful for really huge arrays.283if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&284SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&285FalseRangeEnd == Overdefined)286return nullptr;287}288289// Now that we've scanned the entire array, emit our new comparison(s). We290// order the state machines in complexity of the generated code.291Value *Idx = GEP->getOperand(2);292293// If the index is larger than the pointer offset size of the target, truncate294// the index down like the GEP would do implicitly. We don't have to do this295// for an inbounds GEP because the index can't be out of range.296if (!GEP->isInBounds()) {297Type *PtrIdxTy = DL.getIndexType(GEP->getType());298unsigned OffsetSize = PtrIdxTy->getIntegerBitWidth();299if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > OffsetSize)300Idx = Builder.CreateTrunc(Idx, PtrIdxTy);301}302303// If inbounds keyword is not present, Idx * ElementSize can overflow.304// Let's assume that ElementSize is 2 and the wanted value is at offset 0.305// Then, there are two possible values for Idx to match offset 0:306// 0x00..00, 0x80..00.307// Emitting 'icmp eq Idx, 0' isn't correct in this case because the308// comparison is false if Idx was 0x80..00.309// We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.310unsigned ElementSize =311DL.getTypeAllocSize(Init->getType()->getArrayElementType());312auto MaskIdx = [&](Value *Idx) {313if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {314Value *Mask = ConstantInt::get(Idx->getType(), -1);315Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));316Idx = Builder.CreateAnd(Idx, Mask);317}318return Idx;319};320321// If the comparison is only true for one or two elements, emit direct322// comparisons.323if (SecondTrueElement != Overdefined) {324Idx = MaskIdx(Idx);325// None true -> false.326if (FirstTrueElement == Undefined)327return replaceInstUsesWith(ICI, Builder.getFalse());328329Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);330331// True for one element -> 'i == 47'.332if (SecondTrueElement == Undefined)333return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);334335// True for two elements -> 'i == 47 | i == 72'.336Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);337Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);338Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);339return BinaryOperator::CreateOr(C1, C2);340}341342// If the comparison is only false for one or two elements, emit direct343// comparisons.344if (SecondFalseElement != Overdefined) {345Idx = MaskIdx(Idx);346// None false -> true.347if (FirstFalseElement == Undefined)348return replaceInstUsesWith(ICI, Builder.getTrue());349350Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);351352// False for one element -> 'i != 47'.353if (SecondFalseElement == Undefined)354return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);355356// False for two elements -> 'i != 47 & i != 72'.357Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);358Value *SecondFalseIdx =359ConstantInt::get(Idx->getType(), SecondFalseElement);360Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);361return BinaryOperator::CreateAnd(C1, C2);362}363364// If the comparison can be replaced with a range comparison for the elements365// where it is true, emit the range check.366if (TrueRangeEnd != Overdefined) {367assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");368Idx = MaskIdx(Idx);369370// Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).371if (FirstTrueElement) {372Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);373Idx = Builder.CreateAdd(Idx, Offs);374}375376Value *End =377ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);378return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);379}380381// False range check.382if (FalseRangeEnd != Overdefined) {383assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");384Idx = MaskIdx(Idx);385// Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).386if (FirstFalseElement) {387Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);388Idx = Builder.CreateAdd(Idx, Offs);389}390391Value *End =392ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);393return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);394}395396// If a magic bitvector captures the entire comparison state397// of this load, replace it with computation that does:398// ((magic_cst >> i) & 1) != 0399{400Type *Ty = nullptr;401402// Look for an appropriate type:403// - The type of Idx if the magic fits404// - The smallest fitting legal type405if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())406Ty = Idx->getType();407else408Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);409410if (Ty) {411Idx = MaskIdx(Idx);412Value *V = Builder.CreateIntCast(Idx, Ty, false);413V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);414V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);415return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));416}417}418419return nullptr;420}421422/// Returns true if we can rewrite Start as a GEP with pointer Base423/// and some integer offset. The nodes that need to be re-written424/// for this transformation will be added to Explored.425static bool canRewriteGEPAsOffset(Value *Start, Value *Base,426const DataLayout &DL,427SetVector<Value *> &Explored) {428SmallVector<Value *, 16> WorkList(1, Start);429Explored.insert(Base);430431// The following traversal gives us an order which can be used432// when doing the final transformation. Since in the final433// transformation we create the PHI replacement instructions first,434// we don't have to get them in any particular order.435//436// However, for other instructions we will have to traverse the437// operands of an instruction first, which means that we have to438// do a post-order traversal.439while (!WorkList.empty()) {440SetVector<PHINode *> PHIs;441442while (!WorkList.empty()) {443if (Explored.size() >= 100)444return false;445446Value *V = WorkList.back();447448if (Explored.contains(V)) {449WorkList.pop_back();450continue;451}452453if (!isa<GetElementPtrInst>(V) && !isa<PHINode>(V))454// We've found some value that we can't explore which is different from455// the base. Therefore we can't do this transformation.456return false;457458if (auto *GEP = dyn_cast<GEPOperator>(V)) {459// Only allow inbounds GEPs with at most one variable offset.460auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };461if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)462return false;463464if (!Explored.contains(GEP->getOperand(0)))465WorkList.push_back(GEP->getOperand(0));466}467468if (WorkList.back() == V) {469WorkList.pop_back();470// We've finished visiting this node, mark it as such.471Explored.insert(V);472}473474if (auto *PN = dyn_cast<PHINode>(V)) {475// We cannot transform PHIs on unsplittable basic blocks.476if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))477return false;478Explored.insert(PN);479PHIs.insert(PN);480}481}482483// Explore the PHI nodes further.484for (auto *PN : PHIs)485for (Value *Op : PN->incoming_values())486if (!Explored.contains(Op))487WorkList.push_back(Op);488}489490// Make sure that we can do this. Since we can't insert GEPs in a basic491// block before a PHI node, we can't easily do this transformation if492// we have PHI node users of transformed instructions.493for (Value *Val : Explored) {494for (Value *Use : Val->uses()) {495496auto *PHI = dyn_cast<PHINode>(Use);497auto *Inst = dyn_cast<Instruction>(Val);498499if (Inst == Base || Inst == PHI || !Inst || !PHI ||500!Explored.contains(PHI))501continue;502503if (PHI->getParent() == Inst->getParent())504return false;505}506}507return true;508}509510// Sets the appropriate insert point on Builder where we can add511// a replacement Instruction for V (if that is possible).512static void setInsertionPoint(IRBuilder<> &Builder, Value *V,513bool Before = true) {514if (auto *PHI = dyn_cast<PHINode>(V)) {515BasicBlock *Parent = PHI->getParent();516Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());517return;518}519if (auto *I = dyn_cast<Instruction>(V)) {520if (!Before)521I = &*std::next(I->getIterator());522Builder.SetInsertPoint(I);523return;524}525if (auto *A = dyn_cast<Argument>(V)) {526// Set the insertion point in the entry block.527BasicBlock &Entry = A->getParent()->getEntryBlock();528Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());529return;530}531// Otherwise, this is a constant and we don't need to set a new532// insertion point.533assert(isa<Constant>(V) && "Setting insertion point for unknown value!");534}535536/// Returns a re-written value of Start as an indexed GEP using Base as a537/// pointer.538static Value *rewriteGEPAsOffset(Value *Start, Value *Base,539const DataLayout &DL,540SetVector<Value *> &Explored,541InstCombiner &IC) {542// Perform all the substitutions. This is a bit tricky because we can543// have cycles in our use-def chains.544// 1. Create the PHI nodes without any incoming values.545// 2. Create all the other values.546// 3. Add the edges for the PHI nodes.547// 4. Emit GEPs to get the original pointers.548// 5. Remove the original instructions.549Type *IndexType = IntegerType::get(550Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));551552DenseMap<Value *, Value *> NewInsts;553NewInsts[Base] = ConstantInt::getNullValue(IndexType);554555// Create the new PHI nodes, without adding any incoming values.556for (Value *Val : Explored) {557if (Val == Base)558continue;559// Create empty phi nodes. This avoids cyclic dependencies when creating560// the remaining instructions.561if (auto *PHI = dyn_cast<PHINode>(Val))562NewInsts[PHI] =563PHINode::Create(IndexType, PHI->getNumIncomingValues(),564PHI->getName() + ".idx", PHI->getIterator());565}566IRBuilder<> Builder(Base->getContext());567568// Create all the other instructions.569for (Value *Val : Explored) {570if (NewInsts.contains(Val))571continue;572573if (auto *GEP = dyn_cast<GEPOperator>(Val)) {574setInsertionPoint(Builder, GEP);575Value *Op = NewInsts[GEP->getOperand(0)];576Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);577if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())578NewInsts[GEP] = OffsetV;579else580NewInsts[GEP] = Builder.CreateNSWAdd(581Op, OffsetV, GEP->getOperand(0)->getName() + ".add");582continue;583}584if (isa<PHINode>(Val))585continue;586587llvm_unreachable("Unexpected instruction type");588}589590// Add the incoming values to the PHI nodes.591for (Value *Val : Explored) {592if (Val == Base)593continue;594// All the instructions have been created, we can now add edges to the595// phi nodes.596if (auto *PHI = dyn_cast<PHINode>(Val)) {597PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);598for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {599Value *NewIncoming = PHI->getIncomingValue(I);600601if (NewInsts.contains(NewIncoming))602NewIncoming = NewInsts[NewIncoming];603604NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));605}606}607}608609for (Value *Val : Explored) {610if (Val == Base)611continue;612613setInsertionPoint(Builder, Val, false);614// Create GEP for external users.615Value *NewVal = Builder.CreateInBoundsGEP(616Builder.getInt8Ty(), Base, NewInsts[Val], Val->getName() + ".ptr");617IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);618// Add old instruction to worklist for DCE. We don't directly remove it619// here because the original compare is one of the users.620IC.addToWorklist(cast<Instruction>(Val));621}622623return NewInsts[Start];624}625626/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.627/// We can look through PHIs, GEPs and casts in order to determine a common base628/// between GEPLHS and RHS.629static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,630ICmpInst::Predicate Cond,631const DataLayout &DL,632InstCombiner &IC) {633// FIXME: Support vector of pointers.634if (GEPLHS->getType()->isVectorTy())635return nullptr;636637if (!GEPLHS->hasAllConstantIndices())638return nullptr;639640APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);641Value *PtrBase =642GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,643/*AllowNonInbounds*/ false);644645// Bail if we looked through addrspacecast.646if (PtrBase->getType() != GEPLHS->getType())647return nullptr;648649// The set of nodes that will take part in this transformation.650SetVector<Value *> Nodes;651652if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes))653return nullptr;654655// We know we can re-write this as656// ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)657// Since we've only looked through inbouds GEPs we know that we658// can't have overflow on either side. We can therefore re-write659// this as:660// OFFSET1 cmp OFFSET2661Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes, IC);662663// RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written664// GEP having PtrBase as the pointer base, and has returned in NewRHS the665// offset. Since Index is the offset of LHS to the base pointer, we will now666// compare the offsets instead of comparing the pointers.667return new ICmpInst(ICmpInst::getSignedPredicate(Cond),668IC.Builder.getInt(Offset), NewRHS);669}670671/// Fold comparisons between a GEP instruction and something else. At this point672/// we know that the GEP is on the LHS of the comparison.673Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,674ICmpInst::Predicate Cond,675Instruction &I) {676// Don't transform signed compares of GEPs into index compares. Even if the677// GEP is inbounds, the final add of the base pointer can have signed overflow678// and would change the result of the icmp.679// e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be680// the maximum signed value for the pointer type.681if (ICmpInst::isSigned(Cond))682return nullptr;683684// Look through bitcasts and addrspacecasts. We do not however want to remove685// 0 GEPs.686if (!isa<GetElementPtrInst>(RHS))687RHS = RHS->stripPointerCasts();688689Value *PtrBase = GEPLHS->getOperand(0);690if (PtrBase == RHS && (GEPLHS->isInBounds() || ICmpInst::isEquality(Cond))) {691// ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).692Value *Offset = EmitGEPOffset(GEPLHS);693return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,694Constant::getNullValue(Offset->getType()));695}696697if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&698isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&699!NullPointerIsDefined(I.getFunction(),700RHS->getType()->getPointerAddressSpace())) {701// For most address spaces, an allocation can't be placed at null, but null702// itself is treated as a 0 size allocation in the in bounds rules. Thus,703// the only valid inbounds address derived from null, is null itself.704// Thus, we have four cases to consider:705// 1) Base == nullptr, Offset == 0 -> inbounds, null706// 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds707// 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)708// 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)709//710// (Note if we're indexing a type of size 0, that simply collapses into one711// of the buckets above.)712//713// In general, we're allowed to make values less poison (i.e. remove714// sources of full UB), so in this case, we just select between the two715// non-poison cases (1 and 4 above).716//717// For vectors, we apply the same reasoning on a per-lane basis.718auto *Base = GEPLHS->getPointerOperand();719if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {720auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();721Base = Builder.CreateVectorSplat(EC, Base);722}723return new ICmpInst(Cond, Base,724ConstantExpr::getPointerBitCastOrAddrSpaceCast(725cast<Constant>(RHS), Base->getType()));726} else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {727// If the base pointers are different, but the indices are the same, just728// compare the base pointer.729if (PtrBase != GEPRHS->getOperand(0)) {730bool IndicesTheSame =731GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&732GEPLHS->getPointerOperand()->getType() ==733GEPRHS->getPointerOperand()->getType() &&734GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();735if (IndicesTheSame)736for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)737if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {738IndicesTheSame = false;739break;740}741742// If all indices are the same, just compare the base pointers.743Type *BaseType = GEPLHS->getOperand(0)->getType();744if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())745return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));746747// If we're comparing GEPs with two base pointers that only differ in type748// and both GEPs have only constant indices or just one use, then fold749// the compare with the adjusted indices.750// FIXME: Support vector of pointers.751if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&752(GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&753(GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&754PtrBase->stripPointerCasts() ==755GEPRHS->getOperand(0)->stripPointerCasts() &&756!GEPLHS->getType()->isVectorTy()) {757Value *LOffset = EmitGEPOffset(GEPLHS);758Value *ROffset = EmitGEPOffset(GEPRHS);759760// If we looked through an addrspacecast between different sized address761// spaces, the LHS and RHS pointers are different sized762// integers. Truncate to the smaller one.763Type *LHSIndexTy = LOffset->getType();764Type *RHSIndexTy = ROffset->getType();765if (LHSIndexTy != RHSIndexTy) {766if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <767RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {768ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);769} else770LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);771}772773Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),774LOffset, ROffset);775return replaceInstUsesWith(I, Cmp);776}777778// Otherwise, the base pointers are different and the indices are779// different. Try convert this to an indexed compare by looking through780// PHIs/casts.781return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);782}783784bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();785if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&786GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {787// If the GEPs only differ by one index, compare it.788unsigned NumDifferences = 0; // Keep track of # differences.789unsigned DiffOperand = 0; // The operand that differs.790for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)791if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {792Type *LHSType = GEPLHS->getOperand(i)->getType();793Type *RHSType = GEPRHS->getOperand(i)->getType();794// FIXME: Better support for vector of pointers.795if (LHSType->getPrimitiveSizeInBits() !=796RHSType->getPrimitiveSizeInBits() ||797(GEPLHS->getType()->isVectorTy() &&798(!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {799// Irreconcilable differences.800NumDifferences = 2;801break;802}803804if (NumDifferences++) break;805DiffOperand = i;806}807808if (NumDifferences == 0) // SAME GEP?809return replaceInstUsesWith(I, // No comparison is needed here.810ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));811812else if (NumDifferences == 1 && GEPsInBounds) {813Value *LHSV = GEPLHS->getOperand(DiffOperand);814Value *RHSV = GEPRHS->getOperand(DiffOperand);815// Make sure we do a signed comparison here.816return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);817}818}819820if (GEPsInBounds || CmpInst::isEquality(Cond)) {821// ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)822Value *L = EmitGEPOffset(GEPLHS, /*RewriteGEP=*/true);823Value *R = EmitGEPOffset(GEPRHS, /*RewriteGEP=*/true);824return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);825}826}827828// Try convert this to an indexed compare by looking through PHIs/casts as a829// last resort.830return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);831}832833bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {834// It would be tempting to fold away comparisons between allocas and any835// pointer not based on that alloca (e.g. an argument). However, even836// though such pointers cannot alias, they can still compare equal.837//838// But LLVM doesn't specify where allocas get their memory, so if the alloca839// doesn't escape we can argue that it's impossible to guess its value, and we840// can therefore act as if any such guesses are wrong.841//842// However, we need to ensure that this folding is consistent: We can't fold843// one comparison to false, and then leave a different comparison against the844// same value alone (as it might evaluate to true at runtime, leading to a845// contradiction). As such, this code ensures that all comparisons are folded846// at the same time, and there are no other escapes.847848struct CmpCaptureTracker : public CaptureTracker {849AllocaInst *Alloca;850bool Captured = false;851/// The value of the map is a bit mask of which icmp operands the alloca is852/// used in.853SmallMapVector<ICmpInst *, unsigned, 4> ICmps;854855CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}856857void tooManyUses() override { Captured = true; }858859bool captured(const Use *U) override {860auto *ICmp = dyn_cast<ICmpInst>(U->getUser());861// We need to check that U is based *only* on the alloca, and doesn't862// have other contributions from a select/phi operand.863// TODO: We could check whether getUnderlyingObjects() reduces to one864// object, which would allow looking through phi nodes.865if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {866// Collect equality icmps of the alloca, and don't treat them as867// captures.868auto Res = ICmps.insert({ICmp, 0});869Res.first->second |= 1u << U->getOperandNo();870return false;871}872873Captured = true;874return true;875}876};877878CmpCaptureTracker Tracker(Alloca);879PointerMayBeCaptured(Alloca, &Tracker);880if (Tracker.Captured)881return false;882883bool Changed = false;884for (auto [ICmp, Operands] : Tracker.ICmps) {885switch (Operands) {886case 1:887case 2: {888// The alloca is only used in one icmp operand. Assume that the889// equality is false.890auto *Res = ConstantInt::get(891ICmp->getType(), ICmp->getPredicate() == ICmpInst::ICMP_NE);892replaceInstUsesWith(*ICmp, Res);893eraseInstFromFunction(*ICmp);894Changed = true;895break;896}897case 3:898// Both icmp operands are based on the alloca, so this is comparing899// pointer offsets, without leaking any information about the address900// of the alloca. Ignore such comparisons.901break;902default:903llvm_unreachable("Cannot happen");904}905}906907return Changed;908}909910/// Fold "icmp pred (X+C), X".911Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,912ICmpInst::Predicate Pred) {913// From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,914// so the values can never be equal. Similarly for all other "or equals"915// operators.916assert(!!C && "C should not be zero!");917918// (X+1) <u X --> X >u (MAXUINT-1) --> X == 255919// (X+2) <u X --> X >u (MAXUINT-2) --> X > 253920// (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0921if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {922Constant *R = ConstantInt::get(X->getType(),923APInt::getMaxValue(C.getBitWidth()) - C);924return new ICmpInst(ICmpInst::ICMP_UGT, X, R);925}926927// (X+1) >u X --> X <u (0-1) --> X != 255928// (X+2) >u X --> X <u (0-2) --> X <u 254929// (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0930if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)931return new ICmpInst(ICmpInst::ICMP_ULT, X,932ConstantInt::get(X->getType(), -C));933934APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());935936// (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127937// (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125938// (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0939// (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1940// (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126941// (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127942if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)943return new ICmpInst(ICmpInst::ICMP_SGT, X,944ConstantInt::get(X->getType(), SMax - C));945946// (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127947// (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126948// (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1949// (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2950// (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126951// (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128952953assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);954return new ICmpInst(ICmpInst::ICMP_SLT, X,955ConstantInt::get(X->getType(), SMax - (C - 1)));956}957958/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->959/// (icmp eq/ne A, Log2(AP2/AP1)) ->960/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).961Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,962const APInt &AP1,963const APInt &AP2) {964assert(I.isEquality() && "Cannot fold icmp gt/lt");965966auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {967if (I.getPredicate() == I.ICMP_NE)968Pred = CmpInst::getInversePredicate(Pred);969return new ICmpInst(Pred, LHS, RHS);970};971972// Don't bother doing any work for cases which InstSimplify handles.973if (AP2.isZero())974return nullptr;975976bool IsAShr = isa<AShrOperator>(I.getOperand(0));977if (IsAShr) {978if (AP2.isAllOnes())979return nullptr;980if (AP2.isNegative() != AP1.isNegative())981return nullptr;982if (AP2.sgt(AP1))983return nullptr;984}985986if (!AP1)987// 'A' must be large enough to shift out the highest set bit.988return getICmp(I.ICMP_UGT, A,989ConstantInt::get(A->getType(), AP2.logBase2()));990991if (AP1 == AP2)992return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));993994int Shift;995if (IsAShr && AP1.isNegative())996Shift = AP1.countl_one() - AP2.countl_one();997else998Shift = AP1.countl_zero() - AP2.countl_zero();9991000if (Shift > 0) {1001if (IsAShr && AP1 == AP2.ashr(Shift)) {1002// There are multiple solutions if we are comparing against -1 and the LHS1003// of the ashr is not a power of two.1004if (AP1.isAllOnes() && !AP2.isPowerOf2())1005return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));1006return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));1007} else if (AP1 == AP2.lshr(Shift)) {1008return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));1009}1010}10111012// Shifting const2 will never be equal to const1.1013// FIXME: This should always be handled by InstSimplify?1014auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);1015return replaceInstUsesWith(I, TorF);1016}10171018/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->1019/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).1020Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,1021const APInt &AP1,1022const APInt &AP2) {1023assert(I.isEquality() && "Cannot fold icmp gt/lt");10241025auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {1026if (I.getPredicate() == I.ICMP_NE)1027Pred = CmpInst::getInversePredicate(Pred);1028return new ICmpInst(Pred, LHS, RHS);1029};10301031// Don't bother doing any work for cases which InstSimplify handles.1032if (AP2.isZero())1033return nullptr;10341035unsigned AP2TrailingZeros = AP2.countr_zero();10361037if (!AP1 && AP2TrailingZeros != 0)1038return getICmp(1039I.ICMP_UGE, A,1040ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));10411042if (AP1 == AP2)1043return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));10441045// Get the distance between the lowest bits that are set.1046int Shift = AP1.countr_zero() - AP2TrailingZeros;10471048if (Shift > 0 && AP2.shl(Shift) == AP1)1049return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));10501051// Shifting const2 will never be equal to const1.1052// FIXME: This should always be handled by InstSimplify?1053auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);1054return replaceInstUsesWith(I, TorF);1055}10561057/// The caller has matched a pattern of the form:1058/// I = icmp ugt (add (add A, B), CI2), CI11059/// If this is of the form:1060/// sum = a + b1061/// if (sum+128 >u 255)1062/// Then replace it with llvm.sadd.with.overflow.i8.1063///1064static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,1065ConstantInt *CI2, ConstantInt *CI1,1066InstCombinerImpl &IC) {1067// The transformation we're trying to do here is to transform this into an1068// llvm.sadd.with.overflow. To do this, we have to replace the original add1069// with a narrower add, and discard the add-with-constant that is part of the1070// range check (if we can't eliminate it, this isn't profitable).10711072// In order to eliminate the add-with-constant, the compare can be its only1073// use.1074Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));1075if (!AddWithCst->hasOneUse())1076return nullptr;10771078// If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.1079if (!CI2->getValue().isPowerOf2())1080return nullptr;1081unsigned NewWidth = CI2->getValue().countr_zero();1082if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)1083return nullptr;10841085// The width of the new add formed is 1 more than the bias.1086++NewWidth;10871088// Check to see that CI1 is an all-ones value with NewWidth bits.1089if (CI1->getBitWidth() == NewWidth ||1090CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))1091return nullptr;10921093// This is only really a signed overflow check if the inputs have been1094// sign-extended; check for that condition. For example, if CI2 is 2^31 and1095// the operands of the add are 64 bits wide, we need at least 33 sign bits.1096if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||1097IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)1098return nullptr;10991100// In order to replace the original add with a narrower1101// llvm.sadd.with.overflow, the only uses allowed are the add-with-constant1102// and truncates that discard the high bits of the add. Verify that this is1103// the case.1104Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));1105for (User *U : OrigAdd->users()) {1106if (U == AddWithCst)1107continue;11081109// Only accept truncates for now. We would really like a nice recursive1110// predicate like SimplifyDemandedBits, but which goes downwards the use-def1111// chain to see which bits of a value are actually demanded. If the1112// original add had another add which was then immediately truncated, we1113// could still do the transformation.1114TruncInst *TI = dyn_cast<TruncInst>(U);1115if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)1116return nullptr;1117}11181119// If the pattern matches, truncate the inputs to the narrower type and1120// use the sadd_with_overflow intrinsic to efficiently compute both the1121// result and the overflow bit.1122Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);1123Function *F = Intrinsic::getDeclaration(1124I.getModule(), Intrinsic::sadd_with_overflow, NewType);11251126InstCombiner::BuilderTy &Builder = IC.Builder;11271128// Put the new code above the original add, in case there are any uses of the1129// add between the add and the compare.1130Builder.SetInsertPoint(OrigAdd);11311132Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");1133Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");1134CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");1135Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");1136Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());11371138// The inner add was the result of the narrow add, zero extended to the1139// wider type. Replace it with the result computed by the intrinsic.1140IC.replaceInstUsesWith(*OrigAdd, ZExt);1141IC.eraseInstFromFunction(*OrigAdd);11421143// The original icmp gets replaced with the overflow value.1144return ExtractValueInst::Create(Call, 1, "sadd.overflow");1145}11461147/// If we have:1148/// icmp eq/ne (urem/srem %x, %y), 01149/// iff %y is a power-of-two, we can replace this with a bit test:1150/// icmp eq/ne (and %x, (add %y, -1)), 01151Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {1152// This fold is only valid for equality predicates.1153if (!I.isEquality())1154return nullptr;1155ICmpInst::Predicate Pred;1156Value *X, *Y, *Zero;1157if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),1158m_CombineAnd(m_Zero(), m_Value(Zero)))))1159return nullptr;1160if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))1161return nullptr;1162// This may increase instruction count, we don't enforce that Y is a constant.1163Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));1164Value *Masked = Builder.CreateAnd(X, Mask);1165return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);1166}11671168/// Fold equality-comparison between zero and any (maybe truncated) right-shift1169/// by one-less-than-bitwidth into a sign test on the original value.1170Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {1171Instruction *Val;1172ICmpInst::Predicate Pred;1173if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))1174return nullptr;11751176Value *X;1177Type *XTy;11781179Constant *C;1180if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {1181XTy = X->getType();1182unsigned XBitWidth = XTy->getScalarSizeInBits();1183if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,1184APInt(XBitWidth, XBitWidth - 1))))1185return nullptr;1186} else if (isa<BinaryOperator>(Val) &&1187(X = reassociateShiftAmtsOfTwoSameDirectionShifts(1188cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),1189/*AnalyzeForSignBitExtraction=*/true))) {1190XTy = X->getType();1191} else1192return nullptr;11931194return ICmpInst::Create(Instruction::ICmp,1195Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE1196: ICmpInst::ICMP_SLT,1197X, ConstantInt::getNullValue(XTy));1198}11991200// Handle icmp pred X, 01201Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {1202CmpInst::Predicate Pred = Cmp.getPredicate();1203if (!match(Cmp.getOperand(1), m_Zero()))1204return nullptr;12051206// (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)1207if (Pred == ICmpInst::ICMP_SGT) {1208Value *A, *B;1209if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {1210if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))1211return new ICmpInst(Pred, B, Cmp.getOperand(1));1212if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))1213return new ICmpInst(Pred, A, Cmp.getOperand(1));1214}1215}12161217if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))1218return New;12191220// Given:1221// icmp eq/ne (urem %x, %y), 01222// Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':1223// icmp eq/ne %x, 01224Value *X, *Y;1225if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&1226ICmpInst::isEquality(Pred)) {1227KnownBits XKnown = computeKnownBits(X, 0, &Cmp);1228KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);1229if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)1230return new ICmpInst(Pred, X, Cmp.getOperand(1));1231}12321233// (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are1234// odd/non-zero/there is no overflow.1235if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&1236ICmpInst::isEquality(Pred)) {12371238KnownBits XKnown = computeKnownBits(X, 0, &Cmp);1239// if X % 2 != 01240// (icmp eq/ne Y)1241if (XKnown.countMaxTrailingZeros() == 0)1242return new ICmpInst(Pred, Y, Cmp.getOperand(1));12431244KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);1245// if Y % 2 != 01246// (icmp eq/ne X)1247if (YKnown.countMaxTrailingZeros() == 0)1248return new ICmpInst(Pred, X, Cmp.getOperand(1));12491250auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));1251if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {1252const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);1253// `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`1254// but to avoid unnecessary work, first just if this is an obvious case.12551256// if X non-zero and NoOverflow(X * Y)1257// (icmp eq/ne Y)1258if (!XKnown.One.isZero() || isKnownNonZero(X, Q))1259return new ICmpInst(Pred, Y, Cmp.getOperand(1));12601261// if Y non-zero and NoOverflow(X * Y)1262// (icmp eq/ne X)1263if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))1264return new ICmpInst(Pred, X, Cmp.getOperand(1));1265}1266// Note, we are skipping cases:1267// if Y % 2 != 0 AND X % 2 != 01268// (false/true)1269// if X non-zero and Y non-zero and NoOverflow(X * Y)1270// (false/true)1271// Those can be simplified later as we would have already replaced the (icmp1272// eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that1273// will fold to a constant elsewhere.1274}1275return nullptr;1276}12771278/// Fold icmp Pred X, C.1279/// TODO: This code structure does not make sense. The saturating add fold1280/// should be moved to some other helper and extended as noted below (it is also1281/// possible that code has been made unnecessary - do we canonicalize IR to1282/// overflow/saturating intrinsics or not?).1283Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {1284// Match the following pattern, which is a common idiom when writing1285// overflow-safe integer arithmetic functions. The source performs an addition1286// in wider type and explicitly checks for overflow using comparisons against1287// INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.1288//1289// TODO: This could probably be generalized to handle other overflow-safe1290// operations if we worked out the formulas to compute the appropriate magic1291// constants.1292//1293// sum = a + b1294// if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i81295CmpInst::Predicate Pred = Cmp.getPredicate();1296Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);1297Value *A, *B;1298ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI1299if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&1300match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))1301if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))1302return Res;13031304// icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).1305Constant *C = dyn_cast<Constant>(Op1);1306if (!C)1307return nullptr;13081309if (auto *Phi = dyn_cast<PHINode>(Op0))1310if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {1311SmallVector<Constant *> Ops;1312for (Value *V : Phi->incoming_values()) {1313Constant *Res =1314ConstantFoldCompareInstOperands(Pred, cast<Constant>(V), C, DL);1315if (!Res)1316return nullptr;1317Ops.push_back(Res);1318}1319Builder.SetInsertPoint(Phi);1320PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());1321for (auto [V, Pred] : zip(Ops, Phi->blocks()))1322NewPhi->addIncoming(V, Pred);1323return replaceInstUsesWith(Cmp, NewPhi);1324}13251326if (Instruction *R = tryFoldInstWithCtpopWithNot(&Cmp))1327return R;13281329return nullptr;1330}13311332/// Canonicalize icmp instructions based on dominating conditions.1333Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {1334// We already checked simple implication in InstSimplify, only handle complex1335// cases here.1336Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);1337const APInt *C;1338if (!match(Y, m_APInt(C)))1339return nullptr;13401341CmpInst::Predicate Pred = Cmp.getPredicate();1342ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C);13431344auto handleDomCond = [&](ICmpInst::Predicate DomPred,1345const APInt *DomC) -> Instruction * {1346// We have 2 compares of a variable with constants. Calculate the constant1347// ranges of those compares to see if we can transform the 2nd compare:1348// DomBB:1349// DomCond = icmp DomPred X, DomC1350// br DomCond, CmpBB, FalseBB1351// CmpBB:1352// Cmp = icmp Pred X, C1353ConstantRange DominatingCR =1354ConstantRange::makeExactICmpRegion(DomPred, *DomC);1355ConstantRange Intersection = DominatingCR.intersectWith(CR);1356ConstantRange Difference = DominatingCR.difference(CR);1357if (Intersection.isEmptySet())1358return replaceInstUsesWith(Cmp, Builder.getFalse());1359if (Difference.isEmptySet())1360return replaceInstUsesWith(Cmp, Builder.getTrue());13611362// Canonicalizing a sign bit comparison that gets used in a branch,1363// pessimizes codegen by generating branch on zero instruction instead1364// of a test and branch. So we avoid canonicalizing in such situations1365// because test and branch instruction has better branch displacement1366// than compare and branch instruction.1367bool UnusedBit;1368bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);1369if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))1370return nullptr;13711372// Avoid an infinite loop with min/max canonicalization.1373// TODO: This will be unnecessary if we canonicalize to min/max intrinsics.1374if (Cmp.hasOneUse() &&1375match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))1376return nullptr;13771378if (const APInt *EqC = Intersection.getSingleElement())1379return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));1380if (const APInt *NeC = Difference.getSingleElement())1381return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));1382return nullptr;1383};13841385for (BranchInst *BI : DC.conditionsFor(X)) {1386ICmpInst::Predicate DomPred;1387const APInt *DomC;1388if (!match(BI->getCondition(),1389m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))1390continue;13911392BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));1393if (DT.dominates(Edge0, Cmp.getParent())) {1394if (auto *V = handleDomCond(DomPred, DomC))1395return V;1396} else {1397BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));1398if (DT.dominates(Edge1, Cmp.getParent()))1399if (auto *V =1400handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))1401return V;1402}1403}14041405return nullptr;1406}14071408/// Fold icmp (trunc X), C.1409Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,1410TruncInst *Trunc,1411const APInt &C) {1412ICmpInst::Predicate Pred = Cmp.getPredicate();1413Value *X = Trunc->getOperand(0);1414Type *SrcTy = X->getType();1415unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),1416SrcBits = SrcTy->getScalarSizeInBits();14171418// Match (icmp pred (trunc nuw/nsw X), C)1419// Which we can convert to (icmp pred X, (sext/zext C))1420if (shouldChangeType(Trunc->getType(), SrcTy)) {1421if (Trunc->hasNoSignedWrap())1422return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));1423if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())1424return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));1425}14261427if (C.isOne() && C.getBitWidth() > 1) {1428// icmp slt trunc(signum(V)) 1 --> icmp slt V, 11429Value *V = nullptr;1430if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))1431return new ICmpInst(ICmpInst::ICMP_SLT, V,1432ConstantInt::get(V->getType(), 1));1433}14341435// TODO: Handle any shifted constant by subtracting trailing zeros.1436// TODO: Handle non-equality predicates.1437Value *Y;1438if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {1439// (trunc (1 << Y) to iN) == 0 --> Y u>= N1440// (trunc (1 << Y) to iN) != 0 --> Y u< N1441if (C.isZero()) {1442auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;1443return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));1444}1445// (trunc (1 << Y) to iN) == 2**C --> Y == C1446// (trunc (1 << Y) to iN) != 2**C --> Y != C1447if (C.isPowerOf2())1448return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));1449}14501451if (Cmp.isEquality() && Trunc->hasOneUse()) {1452// Canonicalize to a mask and wider compare if the wide type is suitable:1453// (trunc X to i8) == C --> (X & 0xff) == (zext C)1454if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {1455Constant *Mask =1456ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));1457Value *And = Builder.CreateAnd(X, Mask);1458Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));1459return new ICmpInst(Pred, And, WideC);1460}14611462// Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all1463// of the high bits truncated out of x are known.1464KnownBits Known = computeKnownBits(X, 0, &Cmp);14651466// If all the high bits are known, we can do this xform.1467if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {1468// Pull in the high bits from known-ones set.1469APInt NewRHS = C.zext(SrcBits);1470NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);1471return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));1472}1473}14741475// Look through truncated right-shift of the sign-bit for a sign-bit check:1476// trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 01477// trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -11478Value *ShOp;1479const APInt *ShAmtC;1480bool TrueIfSigned;1481if (isSignBitCheck(Pred, C, TrueIfSigned) &&1482match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&1483DstBits == SrcBits - ShAmtC->getZExtValue()) {1484return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,1485ConstantInt::getNullValue(SrcTy))1486: new ICmpInst(ICmpInst::ICMP_SGT, ShOp,1487ConstantInt::getAllOnesValue(SrcTy));1488}14891490return nullptr;1491}14921493/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).1494/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).1495Instruction *1496InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,1497const SimplifyQuery &Q) {1498Value *X, *Y;1499ICmpInst::Predicate Pred;1500bool YIsSExt = false;1501// Try to match icmp (trunc X), (trunc Y)1502if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {1503unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &1504cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();1505if (Cmp.isSigned()) {1506// For signed comparisons, both truncs must be nsw.1507if (!(NoWrapFlags & TruncInst::NoSignedWrap))1508return nullptr;1509} else {1510// For unsigned and equality comparisons, either both must be nuw or1511// both must be nsw, we don't care which.1512if (!NoWrapFlags)1513return nullptr;1514}15151516if (X->getType() != Y->getType() &&1517(!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))1518return nullptr;1519if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&1520isDesirableIntType(Y->getType()->getScalarSizeInBits())) {1521std::swap(X, Y);1522Pred = Cmp.getSwappedPredicate(Pred);1523}1524YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);1525}1526// Try to match icmp (trunc nuw X), (zext Y)1527else if (!Cmp.isSigned() &&1528match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),1529m_OneUse(m_ZExt(m_Value(Y)))))) {1530// Can fold trunc nuw + zext for unsigned and equality predicates.1531}1532// Try to match icmp (trunc nsw X), (sext Y)1533else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),1534m_OneUse(m_ZExtOrSExt(m_Value(Y)))))) {1535// Can fold trunc nsw + zext/sext for all predicates.1536YIsSExt =1537isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));1538} else1539return nullptr;15401541Type *TruncTy = Cmp.getOperand(0)->getType();1542unsigned TruncBits = TruncTy->getScalarSizeInBits();15431544// If this transform will end up changing from desirable types -> undesirable1545// types skip it.1546if (isDesirableIntType(TruncBits) &&1547!isDesirableIntType(X->getType()->getScalarSizeInBits()))1548return nullptr;15491550Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);1551return new ICmpInst(Pred, X, NewY);1552}15531554/// Fold icmp (xor X, Y), C.1555Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,1556BinaryOperator *Xor,1557const APInt &C) {1558if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))1559return I;15601561Value *X = Xor->getOperand(0);1562Value *Y = Xor->getOperand(1);1563const APInt *XorC;1564if (!match(Y, m_APInt(XorC)))1565return nullptr;15661567// If this is a comparison that tests the signbit (X < 0) or (x > -1),1568// fold the xor.1569ICmpInst::Predicate Pred = Cmp.getPredicate();1570bool TrueIfSigned = false;1571if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {15721573// If the sign bit of the XorCst is not set, there is no change to1574// the operation, just stop using the Xor.1575if (!XorC->isNegative())1576return replaceOperand(Cmp, 0, X);15771578// Emit the opposite comparison.1579if (TrueIfSigned)1580return new ICmpInst(ICmpInst::ICMP_SGT, X,1581ConstantInt::getAllOnesValue(X->getType()));1582else1583return new ICmpInst(ICmpInst::ICMP_SLT, X,1584ConstantInt::getNullValue(X->getType()));1585}15861587if (Xor->hasOneUse()) {1588// (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))1589if (!Cmp.isEquality() && XorC->isSignMask()) {1590Pred = Cmp.getFlippedSignednessPredicate();1591return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));1592}15931594// (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))1595if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {1596Pred = Cmp.getFlippedSignednessPredicate();1597Pred = Cmp.getSwappedPredicate(Pred);1598return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));1599}1600}16011602// Mask constant magic can eliminate an 'xor' with unsigned compares.1603if (Pred == ICmpInst::ICMP_UGT) {1604// (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)1605if (*XorC == ~C && (C + 1).isPowerOf2())1606return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);1607// (xor X, C) >u C --> X >u C (when C+1 is a power of 2)1608if (*XorC == C && (C + 1).isPowerOf2())1609return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);1610}1611if (Pred == ICmpInst::ICMP_ULT) {1612// (xor X, -C) <u C --> X >u ~C (when C is a power of 2)1613if (*XorC == -C && C.isPowerOf2())1614return new ICmpInst(ICmpInst::ICMP_UGT, X,1615ConstantInt::get(X->getType(), ~C));1616// (xor X, C) <u C --> X >u ~C (when -C is a power of 2)1617if (*XorC == C && (-C).isPowerOf2())1618return new ICmpInst(ICmpInst::ICMP_UGT, X,1619ConstantInt::get(X->getType(), ~C));1620}1621return nullptr;1622}16231624/// For power-of-2 C:1625/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)1626/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)1627Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,1628BinaryOperator *Xor,1629const APInt &C) {1630CmpInst::Predicate Pred = Cmp.getPredicate();1631APInt PowerOf2;1632if (Pred == ICmpInst::ICMP_ULT)1633PowerOf2 = C;1634else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())1635PowerOf2 = C + 1;1636else1637return nullptr;1638if (!PowerOf2.isPowerOf2())1639return nullptr;1640Value *X;1641const APInt *ShiftC;1642if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),1643m_AShr(m_Deferred(X), m_APInt(ShiftC))))))1644return nullptr;1645uint64_t Shift = ShiftC->getLimitedValue();1646Type *XType = X->getType();1647if (Shift == 0 || PowerOf2.isMinSignedValue())1648return nullptr;1649Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));1650APInt Bound =1651Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);1652return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));1653}16541655/// Fold icmp (and (sh X, Y), C2), C1.1656Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,1657BinaryOperator *And,1658const APInt &C1,1659const APInt &C2) {1660BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));1661if (!Shift || !Shift->isShift())1662return nullptr;16631664// If this is: (X >> C3) & C2 != C1 (where any shift and any compare could1665// exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in1666// code produced by the clang front-end, for bitfield access.1667// This seemingly simple opportunity to fold away a shift turns out to be1668// rather complicated. See PR17827 for details.1669unsigned ShiftOpcode = Shift->getOpcode();1670bool IsShl = ShiftOpcode == Instruction::Shl;1671const APInt *C3;1672if (match(Shift->getOperand(1), m_APInt(C3))) {1673APInt NewAndCst, NewCmpCst;1674bool AnyCmpCstBitsShiftedOut;1675if (ShiftOpcode == Instruction::Shl) {1676// For a left shift, we can fold if the comparison is not signed. We can1677// also fold a signed comparison if the mask value and comparison value1678// are not negative. These constraints may not be obvious, but we can1679// prove that they are correct using an SMT solver.1680if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))1681return nullptr;16821683NewCmpCst = C1.lshr(*C3);1684NewAndCst = C2.lshr(*C3);1685AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;1686} else if (ShiftOpcode == Instruction::LShr) {1687// For a logical right shift, we can fold if the comparison is not signed.1688// We can also fold a signed comparison if the shifted mask value and the1689// shifted comparison value are not negative. These constraints may not be1690// obvious, but we can prove that they are correct using an SMT solver.1691NewCmpCst = C1.shl(*C3);1692NewAndCst = C2.shl(*C3);1693AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;1694if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))1695return nullptr;1696} else {1697// For an arithmetic shift, check that both constants don't use (in a1698// signed sense) the top bits being shifted out.1699assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");1700NewCmpCst = C1.shl(*C3);1701NewAndCst = C2.shl(*C3);1702AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;1703if (NewAndCst.ashr(*C3) != C2)1704return nullptr;1705}17061707if (AnyCmpCstBitsShiftedOut) {1708// If we shifted bits out, the fold is not going to work out. As a1709// special case, check to see if this means that the result is always1710// true or false now.1711if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)1712return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));1713if (Cmp.getPredicate() == ICmpInst::ICMP_NE)1714return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));1715} else {1716Value *NewAnd = Builder.CreateAnd(1717Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));1718return new ICmpInst(Cmp.getPredicate(),1719NewAnd, ConstantInt::get(And->getType(), NewCmpCst));1720}1721}17221723// Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is1724// preferable because it allows the C2 << Y expression to be hoisted out of a1725// loop if Y is invariant and X is not.1726if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&1727!Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {1728// Compute C2 << Y.1729Value *NewShift =1730IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))1731: Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));17321733// Compute X & (C2 << Y).1734Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);1735return replaceOperand(Cmp, 0, NewAnd);1736}17371738return nullptr;1739}17401741/// Fold icmp (and X, C2), C1.1742Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,1743BinaryOperator *And,1744const APInt &C1) {1745bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;17461747// For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i11748// TODO: We canonicalize to the longer form for scalars because we have1749// better analysis/folds for icmp, and codegen may be better with icmp.1750if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&1751match(And->getOperand(1), m_One()))1752return new TruncInst(And->getOperand(0), Cmp.getType());17531754const APInt *C2;1755Value *X;1756if (!match(And, m_And(m_Value(X), m_APInt(C2))))1757return nullptr;17581759// Don't perform the following transforms if the AND has multiple uses1760if (!And->hasOneUse())1761return nullptr;17621763if (Cmp.isEquality() && C1.isZero()) {1764// Restrict this fold to single-use 'and' (PR10267).1765// Replace (and X, (1 << size(X)-1) != 0) with X s< 01766if (C2->isSignMask()) {1767Constant *Zero = Constant::getNullValue(X->getType());1768auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;1769return new ICmpInst(NewPred, X, Zero);1770}17711772APInt NewC2 = *C2;1773KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);1774// Set high zeros of C2 to allow matching negated power-of-2.1775NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),1776Know.countMinLeadingZeros());17771778// Restrict this fold only for single-use 'and' (PR10267).1779// ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.1780if (NewC2.isNegatedPowerOf2()) {1781Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);1782auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;1783return new ICmpInst(NewPred, X, NegBOC);1784}1785}17861787// If the LHS is an 'and' of a truncate and we can widen the and/compare to1788// the input width without changing the value produced, eliminate the cast:1789//1790// icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'1791//1792// We can do this transformation if the constants do not have their sign bits1793// set or if it is an equality comparison. Extending a relational comparison1794// when we're checking the sign bit would not work.1795Value *W;1796if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&1797(Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {1798// TODO: Is this a good transform for vectors? Wider types may reduce1799// throughput. Should this transform be limited (even for scalars) by using1800// shouldChangeType()?1801if (!Cmp.getType()->isVectorTy()) {1802Type *WideType = W->getType();1803unsigned WideScalarBits = WideType->getScalarSizeInBits();1804Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));1805Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));1806Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());1807return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);1808}1809}18101811if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))1812return I;18131814// (icmp pred (and (or (lshr A, B), A), 1), 0) -->1815// (icmp pred (and A, (or (shl 1, B), 1), 0))1816//1817// iff pred isn't signed1818if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&1819match(And->getOperand(1), m_One())) {1820Constant *One = cast<Constant>(And->getOperand(1));1821Value *Or = And->getOperand(0);1822Value *A, *B, *LShr;1823if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&1824match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {1825unsigned UsesRemoved = 0;1826if (And->hasOneUse())1827++UsesRemoved;1828if (Or->hasOneUse())1829++UsesRemoved;1830if (LShr->hasOneUse())1831++UsesRemoved;18321833// Compute A & ((1 << B) | 1)1834unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;1835if (UsesRemoved >= RequireUsesRemoved) {1836Value *NewOr =1837Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),1838/*HasNUW=*/true),1839One, Or->getName());1840Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());1841return replaceOperand(Cmp, 0, NewAnd);1842}1843}1844}18451846// (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->1847// llvm.is.fpclass(X, fcInf|fcNan)1848// (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->1849// llvm.is.fpclass(X, ~(fcInf|fcNan))1850Value *V;1851if (!Cmp.getParent()->getParent()->hasFnAttribute(1852Attribute::NoImplicitFloat) &&1853Cmp.isEquality() &&1854match(X, m_OneUse(m_ElementWiseBitCast(m_Value(V))))) {1855Type *FPType = V->getType()->getScalarType();1856if (FPType->isIEEELikeFPTy() && C1 == *C2) {1857APInt ExponentMask =1858APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();1859if (C1 == ExponentMask) {1860unsigned Mask = FPClassTest::fcNan | FPClassTest::fcInf;1861if (isICMP_NE)1862Mask = ~Mask & fcAllFlags;1863return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));1864}1865}1866}18671868return nullptr;1869}18701871/// Fold icmp (and X, Y), C.1872Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,1873BinaryOperator *And,1874const APInt &C) {1875if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))1876return I;18771878const ICmpInst::Predicate Pred = Cmp.getPredicate();1879bool TrueIfNeg;1880if (isSignBitCheck(Pred, C, TrueIfNeg)) {1881// ((X - 1) & ~X) < 0 --> X == 01882// ((X - 1) & ~X) >= 0 --> X != 01883Value *X;1884if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&1885match(And->getOperand(1), m_Not(m_Specific(X)))) {1886auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;1887return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));1888}1889// (X & -X) < 0 --> X == MinSignedC1890// (X & -X) > -1 --> X != MinSignedC1891if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {1892Constant *MinSignedC = ConstantInt::get(1893X->getType(),1894APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));1895auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;1896return new ICmpInst(NewPred, X, MinSignedC);1897}1898}18991900// TODO: These all require that Y is constant too, so refactor with the above.19011902// Try to optimize things like "A[i] & 42 == 0" to index computations.1903Value *X = And->getOperand(0);1904Value *Y = And->getOperand(1);1905if (auto *C2 = dyn_cast<ConstantInt>(Y))1906if (auto *LI = dyn_cast<LoadInst>(X))1907if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))1908if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))1909if (Instruction *Res =1910foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))1911return Res;19121913if (!Cmp.isEquality())1914return nullptr;19151916// X & -C == -C -> X > u ~C1917// X & -C != -C -> X <= u ~C1918// iff C is a power of 21919if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {1920auto NewPred =1921Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;1922return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));1923}19241925// If we are testing the intersection of 2 select-of-nonzero-constants with no1926// common bits set, it's the same as checking if exactly one select condition1927// is set:1928// ((A ? TC : FC) & (B ? TC : FC)) == 0 --> xor A, B1929// ((A ? TC : FC) & (B ? TC : FC)) != 0 --> not(xor A, B)1930// TODO: Generalize for non-constant values.1931// TODO: Handle signed/unsigned predicates.1932// TODO: Handle other bitwise logic connectors.1933// TODO: Extend to handle a non-zero compare constant.1934if (C.isZero() && (Pred == CmpInst::ICMP_EQ || And->hasOneUse())) {1935assert(Cmp.isEquality() && "Not expecting non-equality predicates");1936Value *A, *B;1937const APInt *TC, *FC;1938if (match(X, m_Select(m_Value(A), m_APInt(TC), m_APInt(FC))) &&1939match(Y,1940m_Select(m_Value(B), m_SpecificInt(*TC), m_SpecificInt(*FC))) &&1941!TC->isZero() && !FC->isZero() && !TC->intersects(*FC)) {1942Value *R = Builder.CreateXor(A, B);1943if (Pred == CmpInst::ICMP_NE)1944R = Builder.CreateNot(R);1945return replaceInstUsesWith(Cmp, R);1946}1947}19481949// ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)1950// ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)1951// ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)1952// ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)1953if (match(And, m_OneUse(m_c_And(m_OneUse(m_ZExt(m_Value(X))), m_Value(Y)))) &&1954X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {1955Value *TruncY = Builder.CreateTrunc(Y, X->getType());1956if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {1957Value *And = Builder.CreateAnd(TruncY, X);1958return BinaryOperator::CreateNot(And);1959}1960return BinaryOperator::CreateAnd(TruncY, X);1961}19621963// (icmp eq/ne (and (shl -1, X), Y), 0)1964// -> (icmp eq/ne (lshr Y, X), 0)1965// We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems1966// highly unlikely the non-zero case will ever show up in code.1967if (C.isZero() &&1968match(And, m_OneUse(m_c_And(m_OneUse(m_Shl(m_AllOnes(), m_Value(X))),1969m_Value(Y))))) {1970Value *LShr = Builder.CreateLShr(Y, X);1971return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));1972}19731974return nullptr;1975}19761977/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.1978static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,1979InstCombiner::BuilderTy &Builder) {1980// Are we using xors or subs to bitwise check for a pair or pairs of1981// (in)equalities? Convert to a shorter form that has more potential to be1982// folded even further.1983// ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)1984// ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)1985// ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->1986// (X1 == X2) && (X3 == X4) && (X5 == X6)1987// ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->1988// (X1 != X2) || (X3 != X4) || (X5 != X6)1989SmallVector<std::pair<Value *, Value *>, 2> CmpValues;1990SmallVector<Value *, 16> WorkList(1, Or);19911992while (!WorkList.empty()) {1993auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {1994Value *Lhs, *Rhs;19951996if (match(OrOperatorArgument,1997m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {1998CmpValues.emplace_back(Lhs, Rhs);1999return;2000}20012002if (match(OrOperatorArgument,2003m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {2004CmpValues.emplace_back(Lhs, Rhs);2005return;2006}20072008WorkList.push_back(OrOperatorArgument);2009};20102011Value *CurrentValue = WorkList.pop_back_val();2012Value *OrOperatorLhs, *OrOperatorRhs;20132014if (!match(CurrentValue,2015m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {2016return nullptr;2017}20182019MatchOrOperatorArgument(OrOperatorRhs);2020MatchOrOperatorArgument(OrOperatorLhs);2021}20222023ICmpInst::Predicate Pred = Cmp.getPredicate();2024auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;2025Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,2026CmpValues.rbegin()->second);20272028for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {2029Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);2030LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);2031}20322033return LhsCmp;2034}20352036/// Fold icmp (or X, Y), C.2037Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,2038BinaryOperator *Or,2039const APInt &C) {2040ICmpInst::Predicate Pred = Cmp.getPredicate();2041if (C.isOne()) {2042// icmp slt signum(V) 1 --> icmp slt V, 12043Value *V = nullptr;2044if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))2045return new ICmpInst(ICmpInst::ICMP_SLT, V,2046ConstantInt::get(V->getType(), 1));2047}20482049Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);20502051// (icmp eq/ne (or disjoint x, C0), C1)2052// -> (icmp eq/ne x, C0^C1)2053if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&2054cast<PossiblyDisjointInst>(Or)->isDisjoint()) {2055Value *NewC =2056Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));2057return new ICmpInst(Pred, OrOp0, NewC);2058}20592060const APInt *MaskC;2061if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {2062if (*MaskC == C && (C + 1).isPowerOf2()) {2063// X | C == C --> X <=u C2064// X | C != C --> X >u C2065// iff C+1 is a power of 2 (C is a bitmask of the low bits)2066Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;2067return new ICmpInst(Pred, OrOp0, OrOp1);2068}20692070// More general: canonicalize 'equality with set bits mask' to2071// 'equality with clear bits mask'.2072// (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC2073// (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC2074if (Or->hasOneUse()) {2075Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));2076Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));2077return new ICmpInst(Pred, And, NewC);2078}2079}20802081// (X | (X-1)) s< 0 --> X s< 12082// (X | (X-1)) s> -1 --> X s> 02083Value *X;2084bool TrueIfSigned;2085if (isSignBitCheck(Pred, C, TrueIfSigned) &&2086match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) {2087auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;2088Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);2089return new ICmpInst(NewPred, X, NewC);2090}20912092const APInt *OrC;2093// icmp(X | OrC, C) --> icmp(X, 0)2094if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {2095switch (Pred) {2096// X | OrC s< C --> X s< 0 iff OrC s>= C s>= 02097case ICmpInst::ICMP_SLT:2098// X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 02099case ICmpInst::ICMP_SGE:2100if (OrC->sge(C))2101return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));2102break;2103// X | OrC s<= C --> X s< 0 iff OrC s> C s>= 02104case ICmpInst::ICMP_SLE:2105// X | OrC s> C --> X s>= 0 iff OrC s> C s>= 02106case ICmpInst::ICMP_SGT:2107if (OrC->sgt(C))2108return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(Pred), X,2109ConstantInt::getNullValue(X->getType()));2110break;2111default:2112break;2113}2114}21152116if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())2117return nullptr;21182119Value *P, *Q;2120if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {2121// Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 02122// -> and (icmp eq P, null), (icmp eq Q, null).2123Value *CmpP =2124Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));2125Value *CmpQ =2126Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));2127auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;2128return BinaryOperator::Create(BOpc, CmpP, CmpQ);2129}21302131if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))2132return replaceInstUsesWith(Cmp, V);21332134return nullptr;2135}21362137/// Fold icmp (mul X, Y), C.2138Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,2139BinaryOperator *Mul,2140const APInt &C) {2141ICmpInst::Predicate Pred = Cmp.getPredicate();2142Type *MulTy = Mul->getType();2143Value *X = Mul->getOperand(0);21442145// If there's no overflow:2146// X * X == 0 --> X == 02147// X * X != 0 --> X != 02148if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&2149(Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))2150return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));21512152const APInt *MulC;2153if (!match(Mul->getOperand(1), m_APInt(MulC)))2154return nullptr;21552156// If this is a test of the sign bit and the multiply is sign-preserving with2157// a constant operand, use the multiply LHS operand instead:2158// (X * +MulC) < 0 --> X < 02159// (X * -MulC) < 0 --> X > 02160if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {2161if (MulC->isNegative())2162Pred = ICmpInst::getSwappedPredicate(Pred);2163return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));2164}21652166if (MulC->isZero())2167return nullptr;21682169// If the multiply does not wrap or the constant is odd, try to divide the2170// compare constant by the multiplication factor.2171if (Cmp.isEquality()) {2172// (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC2173if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {2174Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));2175return new ICmpInst(Pred, X, NewC);2176}21772178// C % MulC == 0 is weaker than we could use if MulC is odd because it2179// correct to transform if MulC * N == C including overflow. I.e with i82180// (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we2181// miss that case.2182if (C.urem(*MulC).isZero()) {2183// (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC2184// (mul X, OddC) eq/ne N * C --> X eq/ne N2185if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {2186Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));2187return new ICmpInst(Pred, X, NewC);2188}2189}2190}21912192// With a matching no-overflow guarantee, fold the constants:2193// (X * MulC) < C --> X < (C / MulC)2194// (X * MulC) > C --> X > (C / MulC)2195// TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?2196Constant *NewC = nullptr;2197if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {2198// MININT / -1 --> overflow.2199if (C.isMinSignedValue() && MulC->isAllOnes())2200return nullptr;2201if (MulC->isNegative())2202Pred = ICmpInst::getSwappedPredicate(Pred);22032204if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {2205NewC = ConstantInt::get(2206MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));2207} else {2208assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&2209"Unexpected predicate");2210NewC = ConstantInt::get(2211MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::DOWN));2212}2213} else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {2214if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {2215NewC = ConstantInt::get(2216MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));2217} else {2218assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&2219"Unexpected predicate");2220NewC = ConstantInt::get(2221MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::DOWN));2222}2223}22242225return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;2226}22272228/// Fold icmp (shl 1, Y), C.2229static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,2230const APInt &C) {2231Value *Y;2232if (!match(Shl, m_Shl(m_One(), m_Value(Y))))2233return nullptr;22342235Type *ShiftType = Shl->getType();2236unsigned TypeBits = C.getBitWidth();2237bool CIsPowerOf2 = C.isPowerOf2();2238ICmpInst::Predicate Pred = Cmp.getPredicate();2239if (Cmp.isUnsigned()) {2240// (1 << Y) pred C -> Y pred Log2(C)2241if (!CIsPowerOf2) {2242// (1 << Y) < 30 -> Y <= 42243// (1 << Y) <= 30 -> Y <= 42244// (1 << Y) >= 30 -> Y > 42245// (1 << Y) > 30 -> Y > 42246if (Pred == ICmpInst::ICMP_ULT)2247Pred = ICmpInst::ICMP_ULE;2248else if (Pred == ICmpInst::ICMP_UGE)2249Pred = ICmpInst::ICMP_UGT;2250}22512252unsigned CLog2 = C.logBase2();2253return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));2254} else if (Cmp.isSigned()) {2255Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);2256// (1 << Y) > 0 -> Y != 312257// (1 << Y) > C -> Y != 31 if C is negative.2258if (Pred == ICmpInst::ICMP_SGT && C.sle(0))2259return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);22602261// (1 << Y) < 0 -> Y == 312262// (1 << Y) < 1 -> Y == 312263// (1 << Y) < C -> Y == 31 if C is negative and not signed min.2264// Exclude signed min by subtracting 1 and lower the upper bound to 0.2265if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))2266return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);2267}22682269return nullptr;2270}22712272/// Fold icmp (shl X, Y), C.2273Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,2274BinaryOperator *Shl,2275const APInt &C) {2276const APInt *ShiftVal;2277if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))2278return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);22792280ICmpInst::Predicate Pred = Cmp.getPredicate();2281// (icmp pred (shl nuw&nsw X, Y), Csle0)2282// -> (icmp pred X, Csle0)2283//2284// The idea is the nuw/nsw essentially freeze the sign bit for the shift op2285// so X's must be what is used.2286if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())2287return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));22882289// (icmp eq/ne (shl nuw|nsw X, Y), 0)2290// -> (icmp eq/ne X, 0)2291if (ICmpInst::isEquality(Pred) && C.isZero() &&2292(Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))2293return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));22942295// (icmp slt (shl nsw X, Y), 0/1)2296// -> (icmp slt X, 0/1)2297// (icmp sgt (shl nsw X, Y), 0/-1)2298// -> (icmp sgt X, 0/-1)2299//2300// NB: sge/sle with a constant will canonicalize to sgt/slt.2301if (Shl->hasNoSignedWrap() &&2302(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))2303if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))2304return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));23052306const APInt *ShiftAmt;2307if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))2308return foldICmpShlOne(Cmp, Shl, C);23092310// Check that the shift amount is in range. If not, don't perform undefined2311// shifts. When the shift is visited, it will be simplified.2312unsigned TypeBits = C.getBitWidth();2313if (ShiftAmt->uge(TypeBits))2314return nullptr;23152316Value *X = Shl->getOperand(0);2317Type *ShType = Shl->getType();23182319// NSW guarantees that we are only shifting out sign bits from the high bits,2320// so we can ASHR the compare constant without needing a mask and eliminate2321// the shift.2322if (Shl->hasNoSignedWrap()) {2323if (Pred == ICmpInst::ICMP_SGT) {2324// icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)2325APInt ShiftedC = C.ashr(*ShiftAmt);2326return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));2327}2328if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&2329C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {2330APInt ShiftedC = C.ashr(*ShiftAmt);2331return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));2332}2333if (Pred == ICmpInst::ICMP_SLT) {2334// SLE is the same as above, but SLE is canonicalized to SLT, so convert:2335// (X << S) <=s C is equiv to X <=s (C >> S) for all C2336// (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX2337// (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN2338assert(!C.isMinSignedValue() && "Unexpected icmp slt");2339APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;2340return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));2341}2342}23432344// NUW guarantees that we are only shifting out zero bits from the high bits,2345// so we can LSHR the compare constant without needing a mask and eliminate2346// the shift.2347if (Shl->hasNoUnsignedWrap()) {2348if (Pred == ICmpInst::ICMP_UGT) {2349// icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)2350APInt ShiftedC = C.lshr(*ShiftAmt);2351return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));2352}2353if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&2354C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {2355APInt ShiftedC = C.lshr(*ShiftAmt);2356return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));2357}2358if (Pred == ICmpInst::ICMP_ULT) {2359// ULE is the same as above, but ULE is canonicalized to ULT, so convert:2360// (X << S) <=u C is equiv to X <=u (C >> S) for all C2361// (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u2362// (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 02363assert(C.ugt(0) && "ult 0 should have been eliminated");2364APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;2365return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));2366}2367}23682369if (Cmp.isEquality() && Shl->hasOneUse()) {2370// Strength-reduce the shift into an 'and'.2371Constant *Mask = ConstantInt::get(2372ShType,2373APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));2374Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");2375Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));2376return new ICmpInst(Pred, And, LShrC);2377}23782379// Otherwise, if this is a comparison of the sign bit, simplify to and/test.2380bool TrueIfSigned = false;2381if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {2382// (X << 31) <s 0 --> (X & 1) != 02383Constant *Mask = ConstantInt::get(2384ShType,2385APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));2386Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");2387return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,2388And, Constant::getNullValue(ShType));2389}23902391// Simplify 'shl' inequality test into 'and' equality test.2392if (Cmp.isUnsigned() && Shl->hasOneUse()) {2393// (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 02394if ((C + 1).isPowerOf2() &&2395(Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {2396Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));2397return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ2398: ICmpInst::ICMP_NE,2399And, Constant::getNullValue(ShType));2400}2401// (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 02402if (C.isPowerOf2() &&2403(Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {2404Value *And =2405Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));2406return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ2407: ICmpInst::ICMP_NE,2408And, Constant::getNullValue(ShType));2409}2410}24112412// Transform (icmp pred iM (shl iM %v, N), C)2413// -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))2414// Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.2415// This enables us to get rid of the shift in favor of a trunc that may be2416// free on the target. It has the additional benefit of comparing to a2417// smaller constant that may be more target-friendly.2418unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);2419if (Shl->hasOneUse() && Amt != 0 &&2420shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {2421ICmpInst::Predicate CmpPred = Pred;2422APInt RHSC = C;24232424if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {2425// Try the flipped strictness predicate.2426// e.g.:2427// icmp ult i64 (shl X, 32), 8589934593 ->2428// icmp ule i64 (shl X, 32), 8589934592 ->2429// icmp ule i32 (trunc X, i32), 2 ->2430// icmp ult i32 (trunc X, i32), 32431if (auto FlippedStrictness =2432InstCombiner::getFlippedStrictnessPredicateAndConstant(2433Pred, ConstantInt::get(ShType->getContext(), C))) {2434CmpPred = FlippedStrictness->first;2435RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();2436}2437}24382439if (RHSC.countr_zero() >= Amt) {2440Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);2441Constant *NewC =2442ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));2443return new ICmpInst(CmpPred,2444Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,2445Shl->hasNoSignedWrap()),2446NewC);2447}2448}24492450return nullptr;2451}24522453/// Fold icmp ({al}shr X, Y), C.2454Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,2455BinaryOperator *Shr,2456const APInt &C) {2457// An exact shr only shifts out zero bits, so:2458// icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 02459Value *X = Shr->getOperand(0);2460CmpInst::Predicate Pred = Cmp.getPredicate();2461if (Cmp.isEquality() && Shr->isExact() && C.isZero())2462return new ICmpInst(Pred, X, Cmp.getOperand(1));24632464bool IsAShr = Shr->getOpcode() == Instruction::AShr;2465const APInt *ShiftValC;2466if (match(X, m_APInt(ShiftValC))) {2467if (Cmp.isEquality())2468return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);24692470// (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 02471// (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 02472bool TrueIfSigned;2473if (!IsAShr && ShiftValC->isNegative() &&2474isSignBitCheck(Pred, C, TrueIfSigned))2475return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,2476Shr->getOperand(1),2477ConstantInt::getNullValue(X->getType()));24782479// If the shifted constant is a power-of-2, test the shift amount directly:2480// (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))2481// (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))2482if (!IsAShr && ShiftValC->isPowerOf2() &&2483(Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {2484bool IsUGT = Pred == CmpInst::ICMP_UGT;2485assert(ShiftValC->uge(C) && "Expected simplify of compare");2486assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");24872488unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();2489unsigned ShiftLZ = ShiftValC->countl_zero();2490Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);2491auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;2492return new ICmpInst(NewPred, Shr->getOperand(1), NewC);2493}2494}24952496const APInt *ShiftAmtC;2497if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))2498return nullptr;24992500// Check that the shift amount is in range. If not, don't perform undefined2501// shifts. When the shift is visited it will be simplified.2502unsigned TypeBits = C.getBitWidth();2503unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);2504if (ShAmtVal >= TypeBits || ShAmtVal == 0)2505return nullptr;25062507bool IsExact = Shr->isExact();2508Type *ShrTy = Shr->getType();2509// TODO: If we could guarantee that InstSimplify would handle all of the2510// constant-value-based preconditions in the folds below, then we could assert2511// those conditions rather than checking them. This is difficult because of2512// undef/poison (PR34838).2513if (IsAShr && Shr->hasOneUse()) {2514if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&2515(C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {2516// When C - 1 is a power of two and the transform can be legally2517// performed, prefer this form so the produced constant is close to a2518// power of two.2519// icmp slt/ult (ashr exact X, ShAmtC), C2520// --> icmp slt/ult X, (C - 1) << ShAmtC) + 12521APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;2522return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));2523}2524if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {2525// When ShAmtC can be shifted losslessly:2526// icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)2527// icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)2528APInt ShiftedC = C.shl(ShAmtVal);2529if (ShiftedC.ashr(ShAmtVal) == C)2530return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));2531}2532if (Pred == CmpInst::ICMP_SGT) {2533// icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 12534APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;2535if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&2536(ShiftedC + 1).ashr(ShAmtVal) == (C + 1))2537return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));2538}2539if (Pred == CmpInst::ICMP_UGT) {2540// icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 12541// 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd2542// clause accounts for that pattern.2543APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;2544if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||2545(C + 1).shl(ShAmtVal).isMinSignedValue())2546return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));2547}25482549// If the compare constant has significant bits above the lowest sign-bit,2550// then convert an unsigned cmp to a test of the sign-bit:2551// (ashr X, ShiftC) u> C --> X s< 02552// (ashr X, ShiftC) u< C --> X s> -12553if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {2554if (Pred == CmpInst::ICMP_UGT) {2555return new ICmpInst(CmpInst::ICMP_SLT, X,2556ConstantInt::getNullValue(ShrTy));2557}2558if (Pred == CmpInst::ICMP_ULT) {2559return new ICmpInst(CmpInst::ICMP_SGT, X,2560ConstantInt::getAllOnesValue(ShrTy));2561}2562}2563} else if (!IsAShr) {2564if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {2565// icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)2566// icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)2567APInt ShiftedC = C.shl(ShAmtVal);2568if (ShiftedC.lshr(ShAmtVal) == C)2569return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));2570}2571if (Pred == CmpInst::ICMP_UGT) {2572// icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 12573APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;2574if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))2575return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));2576}2577}25782579if (!Cmp.isEquality())2580return nullptr;25812582// Handle equality comparisons of shift-by-constant.25832584// If the comparison constant changes with the shift, the comparison cannot2585// succeed (bits of the comparison constant cannot match the shifted value).2586// This should be known by InstSimplify and already be folded to true/false.2587assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||2588(!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&2589"Expected icmp+shr simplify did not occur.");25902591// If the bits shifted out are known zero, compare the unshifted value:2592// (X & 4) >> 1 == 2 --> (X & 4) == 4.2593if (Shr->isExact())2594return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));25952596if (C.isZero()) {2597// == 0 is u< 1.2598if (Pred == CmpInst::ICMP_EQ)2599return new ICmpInst(CmpInst::ICMP_ULT, X,2600ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));2601else2602return new ICmpInst(CmpInst::ICMP_UGT, X,2603ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));2604}26052606if (Shr->hasOneUse()) {2607// Canonicalize the shift into an 'and':2608// icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)2609APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));2610Constant *Mask = ConstantInt::get(ShrTy, Val);2611Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");2612return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));2613}26142615return nullptr;2616}26172618Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,2619BinaryOperator *SRem,2620const APInt &C) {2621// Match an 'is positive' or 'is negative' comparison of remainder by a2622// constant power-of-2 value:2623// (X % pow2C) sgt/slt 02624const ICmpInst::Predicate Pred = Cmp.getPredicate();2625if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&2626Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)2627return nullptr;26282629// TODO: The one-use check is standard because we do not typically want to2630// create longer instruction sequences, but this might be a special-case2631// because srem is not good for analysis or codegen.2632if (!SRem->hasOneUse())2633return nullptr;26342635const APInt *DivisorC;2636if (!match(SRem->getOperand(1), m_Power2(DivisorC)))2637return nullptr;26382639// For cmp_sgt/cmp_slt only zero valued C is handled.2640// For cmp_eq/cmp_ne only positive valued C is handled.2641if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&2642!C.isZero()) ||2643((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&2644!C.isStrictlyPositive()))2645return nullptr;26462647// Mask off the sign bit and the modulo bits (low-bits).2648Type *Ty = SRem->getType();2649APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());2650Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));2651Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);26522653if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)2654return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));26552656// For 'is positive?' check that the sign-bit is clear and at least 1 masked2657// bit is set. Example:2658// (i8 X % 32) s> 0 --> (X & 159) s> 02659if (Pred == ICmpInst::ICMP_SGT)2660return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));26612662// For 'is negative?' check that the sign-bit is set and at least 1 masked2663// bit is set. Example:2664// (i16 X % 4) s< 0 --> (X & 32771) u> 327682665return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));2666}26672668/// Fold icmp (udiv X, Y), C.2669Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,2670BinaryOperator *UDiv,2671const APInt &C) {2672ICmpInst::Predicate Pred = Cmp.getPredicate();2673Value *X = UDiv->getOperand(0);2674Value *Y = UDiv->getOperand(1);2675Type *Ty = UDiv->getType();26762677const APInt *C2;2678if (!match(X, m_APInt(C2)))2679return nullptr;26802681assert(*C2 != 0 && "udiv 0, X should have been simplified already.");26822683// (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))2684if (Pred == ICmpInst::ICMP_UGT) {2685assert(!C.isMaxValue() &&2686"icmp ugt X, UINT_MAX should have been simplified already.");2687return new ICmpInst(ICmpInst::ICMP_ULE, Y,2688ConstantInt::get(Ty, C2->udiv(C + 1)));2689}26902691// (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)2692if (Pred == ICmpInst::ICMP_ULT) {2693assert(C != 0 && "icmp ult X, 0 should have been simplified already.");2694return new ICmpInst(ICmpInst::ICMP_UGT, Y,2695ConstantInt::get(Ty, C2->udiv(C)));2696}26972698return nullptr;2699}27002701/// Fold icmp ({su}div X, Y), C.2702Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,2703BinaryOperator *Div,2704const APInt &C) {2705ICmpInst::Predicate Pred = Cmp.getPredicate();2706Value *X = Div->getOperand(0);2707Value *Y = Div->getOperand(1);2708Type *Ty = Div->getType();2709bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;27102711// If unsigned division and the compare constant is bigger than2712// UMAX/2 (negative), there's only one pair of values that satisfies an2713// equality check, so eliminate the division:2714// (X u/ Y) == C --> (X == C) && (Y == 1)2715// (X u/ Y) != C --> (X != C) || (Y != 1)2716// Similarly, if signed division and the compare constant is exactly SMIN:2717// (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)2718// (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)2719if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&2720(!DivIsSigned || C.isMinSignedValue())) {2721Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));2722Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));2723auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;2724return BinaryOperator::Create(Logic, XBig, YOne);2725}27262727// Fold: icmp pred ([us]div X, C2), C -> range test2728// Fold this div into the comparison, producing a range check.2729// Determine, based on the divide type, what the range is being2730// checked. If there is an overflow on the low or high side, remember2731// it, otherwise compute the range [low, hi) bounding the new value.2732// See: InsertRangeTest above for the kinds of replacements possible.2733const APInt *C2;2734if (!match(Y, m_APInt(C2)))2735return nullptr;27362737// FIXME: If the operand types don't match the type of the divide2738// then don't attempt this transform. The code below doesn't have the2739// logic to deal with a signed divide and an unsigned compare (and2740// vice versa). This is because (x /s C2) <s C produces different2741// results than (x /s C2) <u C or (x /u C2) <s C or even2742// (x /u C2) <u C. Simply casting the operands and result won't2743// work. :( The if statement below tests that condition and bails2744// if it finds it.2745if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())2746return nullptr;27472748// The ProdOV computation fails on divide by 0 and divide by -1. Cases with2749// INT_MIN will also fail if the divisor is 1. Although folds of all these2750// division-by-constant cases should be present, we can not assert that they2751// have happened before we reach this icmp instruction.2752if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))2753return nullptr;27542755// Compute Prod = C * C2. We are essentially solving an equation of2756// form X / C2 = C. We solve for X by multiplying C2 and C.2757// By solving for X, we can turn this into a range check instead of computing2758// a divide.2759APInt Prod = C * *C2;27602761// Determine if the product overflows by seeing if the product is not equal to2762// the divide. Make sure we do the same kind of divide as in the LHS2763// instruction that we're folding.2764bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;27652766// If the division is known to be exact, then there is no remainder from the2767// divide, so the covered range size is unit, otherwise it is the divisor.2768APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;27692770// Figure out the interval that is being checked. For example, a comparison2771// like "X /u 5 == 0" is really checking that X is in the interval [0, 5).2772// Compute this interval based on the constants involved and the signedness of2773// the compare/divide. This computes a half-open interval, keeping track of2774// whether either value in the interval overflows. After analysis each2775// overflow variable is set to 0 if it's corresponding bound variable is valid2776// -1 if overflowed off the bottom end, or +1 if overflowed off the top end.2777int LoOverflow = 0, HiOverflow = 0;2778APInt LoBound, HiBound;27792780if (!DivIsSigned) { // udiv2781// e.g. X/5 op 3 --> [15, 20)2782LoBound = Prod;2783HiOverflow = LoOverflow = ProdOV;2784if (!HiOverflow) {2785// If this is not an exact divide, then many values in the range collapse2786// to the same result value.2787HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);2788}2789} else if (C2->isStrictlyPositive()) { // Divisor is > 0.2790if (C.isZero()) { // (X / pos) op 02791// Can't overflow. e.g. X/2 op 0 --> [-1, 2)2792LoBound = -(RangeSize - 1);2793HiBound = RangeSize;2794} else if (C.isStrictlyPositive()) { // (X / pos) op pos2795LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)2796HiOverflow = LoOverflow = ProdOV;2797if (!HiOverflow)2798HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);2799} else { // (X / pos) op neg2800// e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)2801HiBound = Prod + 1;2802LoOverflow = HiOverflow = ProdOV ? -1 : 0;2803if (!LoOverflow) {2804APInt DivNeg = -RangeSize;2805LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;2806}2807}2808} else if (C2->isNegative()) { // Divisor is < 0.2809if (Div->isExact())2810RangeSize.negate();2811if (C.isZero()) { // (X / neg) op 02812// e.g. X/-5 op 0 --> [-4, 5)2813LoBound = RangeSize + 1;2814HiBound = -RangeSize;2815if (HiBound == *C2) { // -INTMIN = INTMIN2816HiOverflow = 1; // [INTMIN+1, overflow)2817HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN2818}2819} else if (C.isStrictlyPositive()) { // (X / neg) op pos2820// e.g. X/-5 op 3 --> [-19, -14)2821HiBound = Prod + 1;2822HiOverflow = LoOverflow = ProdOV ? -1 : 0;2823if (!LoOverflow)2824LoOverflow =2825addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;2826} else { // (X / neg) op neg2827LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)2828LoOverflow = HiOverflow = ProdOV;2829if (!HiOverflow)2830HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);2831}28322833// Dividing by a negative swaps the condition. LT <-> GT2834Pred = ICmpInst::getSwappedPredicate(Pred);2835}28362837switch (Pred) {2838default:2839llvm_unreachable("Unhandled icmp predicate!");2840case ICmpInst::ICMP_EQ:2841if (LoOverflow && HiOverflow)2842return replaceInstUsesWith(Cmp, Builder.getFalse());2843if (HiOverflow)2844return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,2845X, ConstantInt::get(Ty, LoBound));2846if (LoOverflow)2847return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,2848X, ConstantInt::get(Ty, HiBound));2849return replaceInstUsesWith(2850Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));2851case ICmpInst::ICMP_NE:2852if (LoOverflow && HiOverflow)2853return replaceInstUsesWith(Cmp, Builder.getTrue());2854if (HiOverflow)2855return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,2856X, ConstantInt::get(Ty, LoBound));2857if (LoOverflow)2858return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,2859X, ConstantInt::get(Ty, HiBound));2860return replaceInstUsesWith(2861Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));2862case ICmpInst::ICMP_ULT:2863case ICmpInst::ICMP_SLT:2864if (LoOverflow == +1) // Low bound is greater than input range.2865return replaceInstUsesWith(Cmp, Builder.getTrue());2866if (LoOverflow == -1) // Low bound is less than input range.2867return replaceInstUsesWith(Cmp, Builder.getFalse());2868return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));2869case ICmpInst::ICMP_UGT:2870case ICmpInst::ICMP_SGT:2871if (HiOverflow == +1) // High bound greater than input range.2872return replaceInstUsesWith(Cmp, Builder.getFalse());2873if (HiOverflow == -1) // High bound less than input range.2874return replaceInstUsesWith(Cmp, Builder.getTrue());2875if (Pred == ICmpInst::ICMP_UGT)2876return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));2877return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));2878}28792880return nullptr;2881}28822883/// Fold icmp (sub X, Y), C.2884Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,2885BinaryOperator *Sub,2886const APInt &C) {2887Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);2888ICmpInst::Predicate Pred = Cmp.getPredicate();2889Type *Ty = Sub->getType();28902891// (SubC - Y) == C) --> Y == (SubC - C)2892// (SubC - Y) != C) --> Y != (SubC - C)2893Constant *SubC;2894if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {2895return new ICmpInst(Pred, Y,2896ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));2897}28982899// (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)2900const APInt *C2;2901APInt SubResult;2902ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();2903bool HasNSW = Sub->hasNoSignedWrap();2904bool HasNUW = Sub->hasNoUnsignedWrap();2905if (match(X, m_APInt(C2)) &&2906((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&2907!subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))2908return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));29092910// X - Y == 0 --> X == Y.2911// X - Y != 0 --> X != Y.2912// TODO: We allow this with multiple uses as long as the other uses are not2913// in phis. The phi use check is guarding against a codegen regression2914// for a loop test. If the backend could undo this (and possibly2915// subsequent transforms), we would not need this hack.2916if (Cmp.isEquality() && C.isZero() &&2917none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))2918return new ICmpInst(Pred, X, Y);29192920// The following transforms are only worth it if the only user of the subtract2921// is the icmp.2922// TODO: This is an artificial restriction for all of the transforms below2923// that only need a single replacement icmp. Can these use the phi test2924// like the transform above here?2925if (!Sub->hasOneUse())2926return nullptr;29272928if (Sub->hasNoSignedWrap()) {2929// (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)2930if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())2931return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);29322933// (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)2934if (Pred == ICmpInst::ICMP_SGT && C.isZero())2935return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);29362937// (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)2938if (Pred == ICmpInst::ICMP_SLT && C.isZero())2939return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);29402941// (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)2942if (Pred == ICmpInst::ICMP_SLT && C.isOne())2943return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);2944}29452946if (!match(X, m_APInt(C2)))2947return nullptr;29482949// C2 - Y <u C -> (Y | (C - 1)) == C22950// iff (C2 & (C - 1)) == C - 1 and C is a power of 22951if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&2952(*C2 & (C - 1)) == (C - 1))2953return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);29542955// C2 - Y >u C -> (Y | C) != C22956// iff C2 & C == C and C + 1 is a power of 22957if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)2958return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);29592960// We have handled special cases that reduce.2961// Canonicalize any remaining sub to add as:2962// (C2 - Y) > C --> (Y + ~C2) < ~C2963Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",2964HasNUW, HasNSW);2965return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));2966}29672968static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,2969Value *Op1, IRBuilderBase &Builder,2970bool HasOneUse) {2971auto FoldConstant = [&](bool Val) {2972Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();2973if (Op0->getType()->isVectorTy())2974Res = ConstantVector::getSplat(2975cast<VectorType>(Op0->getType())->getElementCount(), Res);2976return Res;2977};29782979switch (Table.to_ulong()) {2980case 0: // 0 0 0 02981return FoldConstant(false);2982case 1: // 0 0 0 12983return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;2984case 2: // 0 0 1 02985return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;2986case 3: // 0 0 1 12987return Builder.CreateNot(Op0);2988case 4: // 0 1 0 02989return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;2990case 5: // 0 1 0 12991return Builder.CreateNot(Op1);2992case 6: // 0 1 1 02993return Builder.CreateXor(Op0, Op1);2994case 7: // 0 1 1 12995return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;2996case 8: // 1 0 0 02997return Builder.CreateAnd(Op0, Op1);2998case 9: // 1 0 0 12999return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;3000case 10: // 1 0 1 03001return Op1;3002case 11: // 1 0 1 13003return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;3004case 12: // 1 1 0 03005return Op0;3006case 13: // 1 1 0 13007return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;3008case 14: // 1 1 1 03009return Builder.CreateOr(Op0, Op1);3010case 15: // 1 1 1 13011return FoldConstant(true);3012default:3013llvm_unreachable("Invalid Operation");3014}3015return nullptr;3016}30173018/// Fold icmp (add X, Y), C.3019Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,3020BinaryOperator *Add,3021const APInt &C) {3022Value *Y = Add->getOperand(1);3023Value *X = Add->getOperand(0);30243025Value *Op0, *Op1;3026Instruction *Ext0, *Ext1;3027const CmpInst::Predicate Pred = Cmp.getPredicate();3028if (match(Add,3029m_Add(m_CombineAnd(m_Instruction(Ext0), m_ZExtOrSExt(m_Value(Op0))),3030m_CombineAnd(m_Instruction(Ext1),3031m_ZExtOrSExt(m_Value(Op1))))) &&3032Op0->getType()->isIntOrIntVectorTy(1) &&3033Op1->getType()->isIntOrIntVectorTy(1)) {3034unsigned BW = C.getBitWidth();3035std::bitset<4> Table;3036auto ComputeTable = [&](bool Op0Val, bool Op1Val) {3037int Res = 0;3038if (Op0Val)3039Res += isa<ZExtInst>(Ext0) ? 1 : -1;3040if (Op1Val)3041Res += isa<ZExtInst>(Ext1) ? 1 : -1;3042return ICmpInst::compare(APInt(BW, Res, true), C, Pred);3043};30443045Table[0] = ComputeTable(false, false);3046Table[1] = ComputeTable(false, true);3047Table[2] = ComputeTable(true, false);3048Table[3] = ComputeTable(true, true);3049if (auto *Cond =3050createLogicFromTable(Table, Op0, Op1, Builder, Add->hasOneUse()))3051return replaceInstUsesWith(Cmp, Cond);3052}3053const APInt *C2;3054if (Cmp.isEquality() || !match(Y, m_APInt(C2)))3055return nullptr;30563057// Fold icmp pred (add X, C2), C.3058Type *Ty = Add->getType();30593060// If the add does not wrap, we can always adjust the compare by subtracting3061// the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE3062// are canonicalized to SGT/SLT/UGT/ULT.3063if ((Add->hasNoSignedWrap() &&3064(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||3065(Add->hasNoUnsignedWrap() &&3066(Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {3067bool Overflow;3068APInt NewC =3069Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);3070// If there is overflow, the result must be true or false.3071// TODO: Can we assert there is no overflow because InstSimplify always3072// handles those cases?3073if (!Overflow)3074// icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)3075return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));3076}30773078auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);3079const APInt &Upper = CR.getUpper();3080const APInt &Lower = CR.getLower();3081if (Cmp.isSigned()) {3082if (Lower.isSignMask())3083return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));3084if (Upper.isSignMask())3085return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));3086} else {3087if (Lower.isMinValue())3088return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));3089if (Upper.isMinValue())3090return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));3091}30923093// This set of folds is intentionally placed after folds that use no-wrapping3094// flags because those folds are likely better for later analysis/codegen.3095const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());3096const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());30973098// Fold compare with offset to opposite sign compare if it eliminates offset:3099// (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)3100if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)3101return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));31023103// (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)3104if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)3105return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));31063107// (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)3108if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)3109return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));31103111// (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)3112if (Pred == CmpInst::ICMP_SLT && C == *C2)3113return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));31143115// (X + -1) <u C --> X <=u C (if X is never null)3116if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {3117const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);3118if (llvm::isKnownNonZero(X, Q))3119return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));3120}31213122if (!Add->hasOneUse())3123return nullptr;31243125// X+C <u C2 -> (X & -C2) == C3126// iff C & (C2-1) == 03127// C2 is a power of 23128if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)3129return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),3130ConstantExpr::getNeg(cast<Constant>(Y)));31313132// X+C2 <u C -> (X & C) == 2C3133// iff C == -(C2)3134// C2 is a power of 23135if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)3136return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),3137ConstantInt::get(Ty, C * 2));31383139// X+C >u C2 -> (X & ~C2) != C3140// iff C & C2 == 03141// C2+1 is a power of 23142if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)3143return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),3144ConstantExpr::getNeg(cast<Constant>(Y)));31453146// The range test idiom can use either ult or ugt. Arbitrarily canonicalize3147// to the ult form.3148// X+C2 >u C -> X+(C2-C-1) <u ~C3149if (Pred == ICmpInst::ICMP_UGT)3150return new ICmpInst(ICmpInst::ICMP_ULT,3151Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),3152ConstantInt::get(Ty, ~C));31533154return nullptr;3155}31563157bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,3158Value *&RHS, ConstantInt *&Less,3159ConstantInt *&Equal,3160ConstantInt *&Greater) {3161// TODO: Generalize this to work with other comparison idioms or ensure3162// they get canonicalized into this form.31633164// select i1 (a == b),3165// i32 Equal,3166// i32 (select i1 (a < b), i32 Less, i32 Greater)3167// where Equal, Less and Greater are placeholders for any three constants.3168ICmpInst::Predicate PredA;3169if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||3170!ICmpInst::isEquality(PredA))3171return false;3172Value *EqualVal = SI->getTrueValue();3173Value *UnequalVal = SI->getFalseValue();3174// We still can get non-canonical predicate here, so canonicalize.3175if (PredA == ICmpInst::ICMP_NE)3176std::swap(EqualVal, UnequalVal);3177if (!match(EqualVal, m_ConstantInt(Equal)))3178return false;3179ICmpInst::Predicate PredB;3180Value *LHS2, *RHS2;3181if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),3182m_ConstantInt(Less), m_ConstantInt(Greater))))3183return false;3184// We can get predicate mismatch here, so canonicalize if possible:3185// First, ensure that 'LHS' match.3186if (LHS2 != LHS) {3187// x sgt y <--> y slt x3188std::swap(LHS2, RHS2);3189PredB = ICmpInst::getSwappedPredicate(PredB);3190}3191if (LHS2 != LHS)3192return false;3193// We also need to canonicalize 'RHS'.3194if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {3195// x sgt C-1 <--> x sge C <--> not(x slt C)3196auto FlippedStrictness =3197InstCombiner::getFlippedStrictnessPredicateAndConstant(3198PredB, cast<Constant>(RHS2));3199if (!FlippedStrictness)3200return false;3201assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&3202"basic correctness failure");3203RHS2 = FlippedStrictness->second;3204// And kind-of perform the result swap.3205std::swap(Less, Greater);3206PredB = ICmpInst::ICMP_SLT;3207}3208return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;3209}32103211Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,3212SelectInst *Select,3213ConstantInt *C) {32143215assert(C && "Cmp RHS should be a constant int!");3216// If we're testing a constant value against the result of a three way3217// comparison, the result can be expressed directly in terms of the3218// original values being compared. Note: We could possibly be more3219// aggressive here and remove the hasOneUse test. The original select is3220// really likely to simplify or sink when we remove a test of the result.3221Value *OrigLHS, *OrigRHS;3222ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;3223if (Cmp.hasOneUse() &&3224matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,3225C3GreaterThan)) {3226assert(C1LessThan && C2Equal && C3GreaterThan);32273228bool TrueWhenLessThan = ICmpInst::compare(3229C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());3230bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),3231Cmp.getPredicate());3232bool TrueWhenGreaterThan = ICmpInst::compare(3233C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());32343235// This generates the new instruction that will replace the original Cmp3236// Instruction. Instead of enumerating the various combinations when3237// TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus3238// false, we rely on chaining of ORs and future passes of InstCombine to3239// simplify the OR further (i.e. a s< b || a == b becomes a s<= b).32403241// When none of the three constants satisfy the predicate for the RHS (C),3242// the entire original Cmp can be simplified to a false.3243Value *Cond = Builder.getFalse();3244if (TrueWhenLessThan)3245Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,3246OrigLHS, OrigRHS));3247if (TrueWhenEqual)3248Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,3249OrigLHS, OrigRHS));3250if (TrueWhenGreaterThan)3251Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,3252OrigLHS, OrigRHS));32533254return replaceInstUsesWith(Cmp, Cond);3255}3256return nullptr;3257}32583259Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {3260auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));3261if (!Bitcast)3262return nullptr;32633264ICmpInst::Predicate Pred = Cmp.getPredicate();3265Value *Op1 = Cmp.getOperand(1);3266Value *BCSrcOp = Bitcast->getOperand(0);3267Type *SrcType = Bitcast->getSrcTy();3268Type *DstType = Bitcast->getType();32693270// Make sure the bitcast doesn't change between scalar and vector and3271// doesn't change the number of vector elements.3272if (SrcType->isVectorTy() == DstType->isVectorTy() &&3273SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {3274// Zero-equality and sign-bit checks are preserved through sitofp + bitcast.3275Value *X;3276if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {3277// icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 03278// icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 03279// icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 03280// icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 03281if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||3282Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&3283match(Op1, m_Zero()))3284return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));32853286// icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 13287if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))3288return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));32893290// icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -13291if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))3292return new ICmpInst(Pred, X,3293ConstantInt::getAllOnesValue(X->getType()));3294}32953296// Zero-equality checks are preserved through unsigned floating-point casts:3297// icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 03298// icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 03299if (match(BCSrcOp, m_UIToFP(m_Value(X))))3300if (Cmp.isEquality() && match(Op1, m_Zero()))3301return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));33023303const APInt *C;3304bool TrueIfSigned;3305if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {3306// If this is a sign-bit test of a bitcast of a casted FP value, eliminate3307// the FP extend/truncate because that cast does not change the sign-bit.3308// This is true for all standard IEEE-754 types and the X86 80-bit type.3309// The sign-bit is always the most significant bit in those types.3310if (isSignBitCheck(Pred, *C, TrueIfSigned) &&3311(match(BCSrcOp, m_FPExt(m_Value(X))) ||3312match(BCSrcOp, m_FPTrunc(m_Value(X))))) {3313// (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 03314// (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -13315Type *XType = X->getType();33163317// We can't currently handle Power style floating point operations here.3318if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {3319Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());3320if (auto *XVTy = dyn_cast<VectorType>(XType))3321NewType = VectorType::get(NewType, XVTy->getElementCount());3322Value *NewBitcast = Builder.CreateBitCast(X, NewType);3323if (TrueIfSigned)3324return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,3325ConstantInt::getNullValue(NewType));3326else3327return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,3328ConstantInt::getAllOnesValue(NewType));3329}3330}33313332// icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)3333Type *FPType = SrcType->getScalarType();3334if (!Cmp.getParent()->getParent()->hasFnAttribute(3335Attribute::NoImplicitFloat) &&3336Cmp.isEquality() && FPType->isIEEELikeFPTy()) {3337FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();3338if (Mask & (fcInf | fcZero)) {3339if (Pred == ICmpInst::ICMP_NE)3340Mask = ~Mask;3341return replaceInstUsesWith(Cmp,3342Builder.createIsFPClass(BCSrcOp, Mask));3343}3344}3345}3346}33473348const APInt *C;3349if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||3350!SrcType->isIntOrIntVectorTy())3351return nullptr;33523353// If this is checking if all elements of a vector compare are set or not,3354// invert the casted vector equality compare and test if all compare3355// elements are clear or not. Compare against zero is generally easier for3356// analysis and codegen.3357// icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 03358// Example: are all elements equal? --> are zero elements not equal?3359// TODO: Try harder to reduce compare of 2 freely invertible operands?3360if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {3361if (Value *NotBCSrcOp =3362getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {3363Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);3364return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));3365}3366}33673368// If this is checking if all elements of an extended vector are clear or not,3369// compare in a narrow type to eliminate the extend:3370// icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 03371Value *X;3372if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&3373match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {3374if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {3375Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());3376Value *NewCast = Builder.CreateBitCast(X, NewType);3377return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));3378}3379}33803381// Folding: icmp <pred> iN X, C3382// where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN3383// and C is a splat of a K-bit pattern3384// and SC is a constant vector = <C', C', C', ..., C'>3385// Into:3386// %E = extractelement <M x iK> %vec, i32 C'3387// icmp <pred> iK %E, trunc(C)3388Value *Vec;3389ArrayRef<int> Mask;3390if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {3391// Check whether every element of Mask is the same constant3392if (all_equal(Mask)) {3393auto *VecTy = cast<VectorType>(SrcType);3394auto *EltTy = cast<IntegerType>(VecTy->getElementType());3395if (C->isSplat(EltTy->getBitWidth())) {3396// Fold the icmp based on the value of C3397// If C is M copies of an iK sized bit pattern,3398// then:3399// => %E = extractelement <N x iK> %vec, i32 Elem3400// icmp <pred> iK %SplatVal, <pattern>3401Value *Elem = Builder.getInt32(Mask[0]);3402Value *Extract = Builder.CreateExtractElement(Vec, Elem);3403Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));3404return new ICmpInst(Pred, Extract, NewC);3405}3406}3407}3408return nullptr;3409}34103411/// Try to fold integer comparisons with a constant operand: icmp Pred X, C3412/// where X is some kind of instruction.3413Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {3414const APInt *C;34153416if (match(Cmp.getOperand(1), m_APInt(C))) {3417if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))3418if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))3419return I;34203421if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))3422// For now, we only support constant integers while folding the3423// ICMP(SELECT)) pattern. We can extend this to support vector of integers3424// similar to the cases handled by binary ops above.3425if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))3426if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))3427return I;34283429if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))3430if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))3431return I;34323433if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))3434if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))3435return I;34363437// (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y3438// (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y3439// TODO: This checks one-use, but that is not strictly necessary.3440Value *Cmp0 = Cmp.getOperand(0);3441Value *X, *Y;3442if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&3443(match(Cmp0,3444m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(3445m_Value(X), m_Value(Y)))) ||3446match(Cmp0,3447m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(3448m_Value(X), m_Value(Y))))))3449return new ICmpInst(Cmp.getPredicate(), X, Y);3450}34513452if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))3453return foldICmpInstWithConstantAllowPoison(Cmp, *C);34543455return nullptr;3456}34573458/// Fold an icmp equality instruction with binary operator LHS and constant RHS:3459/// icmp eq/ne BO, C.3460Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(3461ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {3462// TODO: Some of these folds could work with arbitrary constants, but this3463// function is limited to scalar and vector splat constants.3464if (!Cmp.isEquality())3465return nullptr;34663467ICmpInst::Predicate Pred = Cmp.getPredicate();3468bool isICMP_NE = Pred == ICmpInst::ICMP_NE;3469Constant *RHS = cast<Constant>(Cmp.getOperand(1));3470Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);34713472switch (BO->getOpcode()) {3473case Instruction::SRem:3474// If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.3475if (C.isZero() && BO->hasOneUse()) {3476const APInt *BOC;3477if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {3478Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());3479return new ICmpInst(Pred, NewRem,3480Constant::getNullValue(BO->getType()));3481}3482}3483break;3484case Instruction::Add: {3485// (A + C2) == C --> A == (C - C2)3486// (A + C2) != C --> A != (C - C2)3487// TODO: Remove the one-use limitation? See discussion in D58633.3488if (Constant *C2 = dyn_cast<Constant>(BOp1)) {3489if (BO->hasOneUse())3490return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));3491} else if (C.isZero()) {3492// Replace ((add A, B) != 0) with (A != -B) if A or B is3493// efficiently invertible, or if the add has just this one use.3494if (Value *NegVal = dyn_castNegVal(BOp1))3495return new ICmpInst(Pred, BOp0, NegVal);3496if (Value *NegVal = dyn_castNegVal(BOp0))3497return new ICmpInst(Pred, NegVal, BOp1);3498if (BO->hasOneUse()) {3499// (add nuw A, B) != 0 -> (or A, B) != 03500if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {3501Value *Or = Builder.CreateOr(BOp0, BOp1);3502return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));3503}3504Value *Neg = Builder.CreateNeg(BOp1);3505Neg->takeName(BO);3506return new ICmpInst(Pred, BOp0, Neg);3507}3508}3509break;3510}3511case Instruction::Xor:3512if (Constant *BOC = dyn_cast<Constant>(BOp1)) {3513// For the xor case, we can xor two constants together, eliminating3514// the explicit xor.3515return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));3516} else if (C.isZero()) {3517// Replace ((xor A, B) != 0) with (A != B)3518return new ICmpInst(Pred, BOp0, BOp1);3519}3520break;3521case Instruction::Or: {3522const APInt *BOC;3523if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {3524// Comparing if all bits outside of a constant mask are set?3525// Replace (X | C) == -1 with (X & ~C) == ~C.3526// This removes the -1 constant.3527Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));3528Value *And = Builder.CreateAnd(BOp0, NotBOC);3529return new ICmpInst(Pred, And, NotBOC);3530}3531break;3532}3533case Instruction::UDiv:3534case Instruction::SDiv:3535if (BO->isExact()) {3536// div exact X, Y eq/ne 0 -> X eq/ne 03537// div exact X, Y eq/ne 1 -> X eq/ne Y3538// div exact X, Y eq/ne C ->3539// if Y * C never-overflow && OneUse:3540// -> Y * C eq/ne X3541if (C.isZero())3542return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));3543else if (C.isOne())3544return new ICmpInst(Pred, BOp0, BOp1);3545else if (BO->hasOneUse()) {3546OverflowResult OR = computeOverflow(3547Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,3548Cmp.getOperand(1), BO);3549if (OR == OverflowResult::NeverOverflows) {3550Value *YC =3551Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));3552return new ICmpInst(Pred, YC, BOp0);3553}3554}3555}3556if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {3557// (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)3558auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;3559return new ICmpInst(NewPred, BOp1, BOp0);3560}3561break;3562default:3563break;3564}3565return nullptr;3566}35673568static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,3569const APInt &CRhs,3570InstCombiner::BuilderTy &Builder,3571const SimplifyQuery &Q) {3572assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&3573"Non-ctpop intrin in ctpop fold");3574if (!CtpopLhs->hasOneUse())3575return nullptr;35763577// Power of 2 test:3578// isPow2OrZero : ctpop(X) u< 23579// isPow2 : ctpop(X) == 13580// NotPow2OrZero: ctpop(X) u> 13581// NotPow2 : ctpop(X) != 13582// If we know any bit of X can be folded to:3583// IsPow2 : X & (~Bit) == 03584// NotPow2 : X & (~Bit) != 03585const ICmpInst::Predicate Pred = I.getPredicate();3586if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||3587(Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {3588Value *Op = CtpopLhs->getArgOperand(0);3589KnownBits OpKnown = computeKnownBits(Op, Q.DL,3590/*Depth*/ 0, Q.AC, Q.CxtI, Q.DT);3591// No need to check for count > 1, that should be already constant folded.3592if (OpKnown.countMinPopulation() == 1) {3593Value *And = Builder.CreateAnd(3594Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));3595return new ICmpInst(3596(Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)3597? ICmpInst::ICMP_EQ3598: ICmpInst::ICMP_NE,3599And, Constant::getNullValue(Op->getType()));3600}3601}36023603return nullptr;3604}36053606/// Fold an equality icmp with LLVM intrinsic and constant operand.3607Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(3608ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {3609Type *Ty = II->getType();3610unsigned BitWidth = C.getBitWidth();3611const ICmpInst::Predicate Pred = Cmp.getPredicate();36123613switch (II->getIntrinsicID()) {3614case Intrinsic::abs:3615// abs(A) == 0 -> A == 03616// abs(A) == INT_MIN -> A == INT_MIN3617if (C.isZero() || C.isMinSignedValue())3618return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));3619break;36203621case Intrinsic::bswap:3622// bswap(A) == C -> A == bswap(C)3623return new ICmpInst(Pred, II->getArgOperand(0),3624ConstantInt::get(Ty, C.byteSwap()));36253626case Intrinsic::bitreverse:3627// bitreverse(A) == C -> A == bitreverse(C)3628return new ICmpInst(Pred, II->getArgOperand(0),3629ConstantInt::get(Ty, C.reverseBits()));36303631case Intrinsic::ctlz:3632case Intrinsic::cttz: {3633// ctz(A) == bitwidth(A) -> A == 0 and likewise for !=3634if (C == BitWidth)3635return new ICmpInst(Pred, II->getArgOperand(0),3636ConstantInt::getNullValue(Ty));36373638// ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set3639// and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.3640// Limit to one use to ensure we don't increase instruction count.3641unsigned Num = C.getLimitedValue(BitWidth);3642if (Num != BitWidth && II->hasOneUse()) {3643bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;3644APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)3645: APInt::getHighBitsSet(BitWidth, Num + 1);3646APInt Mask2 = IsTrailing3647? APInt::getOneBitSet(BitWidth, Num)3648: APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);3649return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),3650ConstantInt::get(Ty, Mask2));3651}3652break;3653}36543655case Intrinsic::ctpop: {3656// popcount(A) == 0 -> A == 0 and likewise for !=3657// popcount(A) == bitwidth(A) -> A == -1 and likewise for !=3658bool IsZero = C.isZero();3659if (IsZero || C == BitWidth)3660return new ICmpInst(Pred, II->getArgOperand(0),3661IsZero ? Constant::getNullValue(Ty)3662: Constant::getAllOnesValue(Ty));36633664break;3665}36663667case Intrinsic::fshl:3668case Intrinsic::fshr:3669if (II->getArgOperand(0) == II->getArgOperand(1)) {3670const APInt *RotAmtC;3671// ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)3672// rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)3673if (match(II->getArgOperand(2), m_APInt(RotAmtC)))3674return new ICmpInst(Pred, II->getArgOperand(0),3675II->getIntrinsicID() == Intrinsic::fshl3676? ConstantInt::get(Ty, C.rotr(*RotAmtC))3677: ConstantInt::get(Ty, C.rotl(*RotAmtC)));3678}3679break;36803681case Intrinsic::umax:3682case Intrinsic::uadd_sat: {3683// uadd.sat(a, b) == 0 -> (a | b) == 03684// umax(a, b) == 0 -> (a | b) == 03685if (C.isZero() && II->hasOneUse()) {3686Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));3687return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));3688}3689break;3690}36913692case Intrinsic::ssub_sat:3693// ssub.sat(a, b) == 0 -> a == b3694if (C.isZero())3695return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));3696break;3697case Intrinsic::usub_sat: {3698// usub.sat(a, b) == 0 -> a <= b3699if (C.isZero()) {3700ICmpInst::Predicate NewPred =3701Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;3702return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));3703}3704break;3705}3706default:3707break;3708}37093710return nullptr;3711}37123713/// Fold an icmp with LLVM intrinsics3714static Instruction *3715foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,3716InstCombiner::BuilderTy &Builder) {3717assert(Cmp.isEquality());37183719ICmpInst::Predicate Pred = Cmp.getPredicate();3720Value *Op0 = Cmp.getOperand(0);3721Value *Op1 = Cmp.getOperand(1);3722const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);3723const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);3724if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())3725return nullptr;37263727switch (IIOp0->getIntrinsicID()) {3728case Intrinsic::bswap:3729case Intrinsic::bitreverse:3730// If both operands are byte-swapped or bit-reversed, just compare the3731// original values.3732return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));3733case Intrinsic::fshl:3734case Intrinsic::fshr: {3735// If both operands are rotated by same amount, just compare the3736// original values.3737if (IIOp0->getOperand(0) != IIOp0->getOperand(1))3738break;3739if (IIOp1->getOperand(0) != IIOp1->getOperand(1))3740break;3741if (IIOp0->getOperand(2) == IIOp1->getOperand(2))3742return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));37433744// rotate(X, AmtX) == rotate(Y, AmtY)3745// -> rotate(X, AmtX - AmtY) == Y3746// Do this if either both rotates have one use or if only one has one use3747// and AmtX/AmtY are constants.3748unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();3749if (OneUses == 2 ||3750(OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&3751match(IIOp1->getOperand(2), m_ImmConstant()))) {3752Value *SubAmt =3753Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));3754Value *CombinedRotate = Builder.CreateIntrinsic(3755Op0->getType(), IIOp0->getIntrinsicID(),3756{IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});3757return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);3758}3759} break;3760default:3761break;3762}37633764return nullptr;3765}37663767/// Try to fold integer comparisons with a constant operand: icmp Pred X, C3768/// where X is some kind of instruction and C is AllowPoison.3769/// TODO: Move more folds which allow poison to this function.3770Instruction *3771InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,3772const APInt &C) {3773const ICmpInst::Predicate Pred = Cmp.getPredicate();3774if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {3775switch (II->getIntrinsicID()) {3776default:3777break;3778case Intrinsic::fshl:3779case Intrinsic::fshr:3780if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {3781// (rot X, ?) == 0/-1 --> X == 0/-13782if (C.isZero() || C.isAllOnes())3783return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));3784}3785break;3786}3787}37883789return nullptr;3790}37913792/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.3793Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,3794BinaryOperator *BO,3795const APInt &C) {3796switch (BO->getOpcode()) {3797case Instruction::Xor:3798if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))3799return I;3800break;3801case Instruction::And:3802if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))3803return I;3804break;3805case Instruction::Or:3806if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))3807return I;3808break;3809case Instruction::Mul:3810if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))3811return I;3812break;3813case Instruction::Shl:3814if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))3815return I;3816break;3817case Instruction::LShr:3818case Instruction::AShr:3819if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))3820return I;3821break;3822case Instruction::SRem:3823if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))3824return I;3825break;3826case Instruction::UDiv:3827if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))3828return I;3829[[fallthrough]];3830case Instruction::SDiv:3831if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))3832return I;3833break;3834case Instruction::Sub:3835if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))3836return I;3837break;3838case Instruction::Add:3839if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))3840return I;3841break;3842default:3843break;3844}38453846// TODO: These folds could be refactored to be part of the above calls.3847return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);3848}38493850static Instruction *3851foldICmpUSubSatOrUAddSatWithConstant(ICmpInst::Predicate Pred,3852SaturatingInst *II, const APInt &C,3853InstCombiner::BuilderTy &Builder) {3854// This transform may end up producing more than one instruction for the3855// intrinsic, so limit it to one user of the intrinsic.3856if (!II->hasOneUse())3857return nullptr;38583859// Let Y = [add/sub]_sat(X, C) pred C23860// SatVal = The saturating value for the operation3861// WillWrap = Whether or not the operation will underflow / overflow3862// => Y = (WillWrap ? SatVal : (X binop C)) pred C23863// => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)3864//3865// When (SatVal pred C2) is true, then3866// Y = WillWrap ? true : ((X binop C) pred C2)3867// => Y = WillWrap || ((X binop C) pred C2)3868// else3869// Y = WillWrap ? false : ((X binop C) pred C2)3870// => Y = !WillWrap ? ((X binop C) pred C2) : false3871// => Y = !WillWrap && ((X binop C) pred C2)3872Value *Op0 = II->getOperand(0);3873Value *Op1 = II->getOperand(1);38743875const APInt *COp1;3876// This transform only works when the intrinsic has an integral constant or3877// splat vector as the second operand.3878if (!match(Op1, m_APInt(COp1)))3879return nullptr;38803881APInt SatVal;3882switch (II->getIntrinsicID()) {3883default:3884llvm_unreachable(3885"This function only works with usub_sat and uadd_sat for now!");3886case Intrinsic::uadd_sat:3887SatVal = APInt::getAllOnes(C.getBitWidth());3888break;3889case Intrinsic::usub_sat:3890SatVal = APInt::getZero(C.getBitWidth());3891break;3892}38933894// Check (SatVal pred C2)3895bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);38963897// !WillWrap.3898ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(3899II->getBinaryOp(), *COp1, II->getNoWrapKind());39003901// WillWrap.3902if (SatValCheck)3903C1 = C1.inverse();39043905ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, C);3906if (II->getBinaryOp() == Instruction::Add)3907C2 = C2.sub(*COp1);3908else3909C2 = C2.add(*COp1);39103911Instruction::BinaryOps CombiningOp =3912SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;39133914std::optional<ConstantRange> Combination;3915if (CombiningOp == Instruction::BinaryOps::Or)3916Combination = C1.exactUnionWith(C2);3917else /* CombiningOp == Instruction::BinaryOps::And */3918Combination = C1.exactIntersectWith(C2);39193920if (!Combination)3921return nullptr;39223923CmpInst::Predicate EquivPred;3924APInt EquivInt;3925APInt EquivOffset;39263927Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);39283929return new ICmpInst(3930EquivPred,3931Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),3932ConstantInt::get(Op1->getType(), EquivInt));3933}39343935static Instruction *3936foldICmpOfCmpIntrinsicWithConstant(ICmpInst::Predicate Pred, IntrinsicInst *I,3937const APInt &C,3938InstCombiner::BuilderTy &Builder) {3939std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;3940switch (Pred) {3941case ICmpInst::ICMP_EQ:3942case ICmpInst::ICMP_NE:3943if (C.isZero())3944NewPredicate = Pred;3945else if (C.isOne())3946NewPredicate =3947Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;3948else if (C.isAllOnes())3949NewPredicate =3950Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;3951break;39523953case ICmpInst::ICMP_SGT:3954if (C.isAllOnes())3955NewPredicate = ICmpInst::ICMP_UGE;3956else if (C.isZero())3957NewPredicate = ICmpInst::ICMP_UGT;3958break;39593960case ICmpInst::ICMP_SLT:3961if (C.isZero())3962NewPredicate = ICmpInst::ICMP_ULT;3963else if (C.isOne())3964NewPredicate = ICmpInst::ICMP_ULE;3965break;39663967default:3968break;3969}39703971if (!NewPredicate)3972return nullptr;39733974if (I->getIntrinsicID() == Intrinsic::scmp)3975NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);3976Value *LHS = I->getOperand(0);3977Value *RHS = I->getOperand(1);3978return new ICmpInst(*NewPredicate, LHS, RHS);3979}39803981/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.3982Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,3983IntrinsicInst *II,3984const APInt &C) {3985ICmpInst::Predicate Pred = Cmp.getPredicate();39863987// Handle folds that apply for any kind of icmp.3988switch (II->getIntrinsicID()) {3989default:3990break;3991case Intrinsic::uadd_sat:3992case Intrinsic::usub_sat:3993if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(3994Pred, cast<SaturatingInst>(II), C, Builder))3995return Folded;3996break;3997case Intrinsic::ctpop: {3998const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);3999if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))4000return R;4001} break;4002case Intrinsic::scmp:4003case Intrinsic::ucmp:4004if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))4005return Folded;4006break;4007}40084009if (Cmp.isEquality())4010return foldICmpEqIntrinsicWithConstant(Cmp, II, C);40114012Type *Ty = II->getType();4013unsigned BitWidth = C.getBitWidth();4014switch (II->getIntrinsicID()) {4015case Intrinsic::ctpop: {4016// (ctpop X > BitWidth - 1) --> X == -14017Value *X = II->getArgOperand(0);4018if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)4019return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,4020ConstantInt::getAllOnesValue(Ty));4021// (ctpop X < BitWidth) --> X != -14022if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)4023return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,4024ConstantInt::getAllOnesValue(Ty));4025break;4026}4027case Intrinsic::ctlz: {4028// ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b000100004029if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {4030unsigned Num = C.getLimitedValue();4031APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);4032return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,4033II->getArgOperand(0), ConstantInt::get(Ty, Limit));4034}40354036// ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b000111114037if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {4038unsigned Num = C.getLimitedValue();4039APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);4040return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,4041II->getArgOperand(0), ConstantInt::get(Ty, Limit));4042}4043break;4044}4045case Intrinsic::cttz: {4046// Limit to one use to ensure we don't increase instruction count.4047if (!II->hasOneUse())4048return nullptr;40494050// cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 04051if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {4052APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);4053return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,4054Builder.CreateAnd(II->getArgOperand(0), Mask),4055ConstantInt::getNullValue(Ty));4056}40574058// cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 04059if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {4060APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());4061return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,4062Builder.CreateAnd(II->getArgOperand(0), Mask),4063ConstantInt::getNullValue(Ty));4064}4065break;4066}4067case Intrinsic::ssub_sat:4068// ssub.sat(a, b) spred 0 -> a spred b4069if (ICmpInst::isSigned(Pred)) {4070if (C.isZero())4071return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));4072// X s<= 0 is cannonicalized to X s< 14073if (Pred == ICmpInst::ICMP_SLT && C.isOne())4074return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),4075II->getArgOperand(1));4076// X s>= 0 is cannonicalized to X s> -14077if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())4078return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),4079II->getArgOperand(1));4080}4081break;4082default:4083break;4084}40854086return nullptr;4087}40884089/// Handle icmp with constant (but not simple integer constant) RHS.4090Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {4091Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);4092Constant *RHSC = dyn_cast<Constant>(Op1);4093Instruction *LHSI = dyn_cast<Instruction>(Op0);4094if (!RHSC || !LHSI)4095return nullptr;40964097switch (LHSI->getOpcode()) {4098case Instruction::PHI:4099if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))4100return NV;4101break;4102case Instruction::IntToPtr:4103// icmp pred inttoptr(X), null -> icmp pred X, 04104if (RHSC->isNullValue() &&4105DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())4106return new ICmpInst(4107I.getPredicate(), LHSI->getOperand(0),4108Constant::getNullValue(LHSI->getOperand(0)->getType()));4109break;41104111case Instruction::Load:4112// Try to optimize things like "A[i] > 4" to index computations.4113if (GetElementPtrInst *GEP =4114dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))4115if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))4116if (Instruction *Res =4117foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))4118return Res;4119break;4120}41214122return nullptr;4123}41244125Instruction *InstCombinerImpl::foldSelectICmp(ICmpInst::Predicate Pred,4126SelectInst *SI, Value *RHS,4127const ICmpInst &I) {4128// Try to fold the comparison into the select arms, which will cause the4129// select to be converted into a logical and/or.4130auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {4131if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))4132return Res;4133if (std::optional<bool> Impl = isImpliedCondition(4134SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))4135return ConstantInt::get(I.getType(), *Impl);4136return nullptr;4137};41384139ConstantInt *CI = nullptr;4140Value *Op1 = SimplifyOp(SI->getOperand(1), true);4141if (Op1)4142CI = dyn_cast<ConstantInt>(Op1);41434144Value *Op2 = SimplifyOp(SI->getOperand(2), false);4145if (Op2)4146CI = dyn_cast<ConstantInt>(Op2);41474148// We only want to perform this transformation if it will not lead to4149// additional code. This is true if either both sides of the select4150// fold to a constant (in which case the icmp is replaced with a select4151// which will usually simplify) or this is the only user of the4152// select (in which case we are trading a select+icmp for a simpler4153// select+icmp) or all uses of the select can be replaced based on4154// dominance information ("Global cases").4155bool Transform = false;4156if (Op1 && Op2)4157Transform = true;4158else if (Op1 || Op2) {4159// Local case4160if (SI->hasOneUse())4161Transform = true;4162// Global cases4163else if (CI && !CI->isZero())4164// When Op1 is constant try replacing select with second operand.4165// Otherwise Op2 is constant and try replacing select with first4166// operand.4167Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);4168}4169if (Transform) {4170if (!Op1)4171Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());4172if (!Op2)4173Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());4174return SelectInst::Create(SI->getOperand(0), Op1, Op2);4175}41764177return nullptr;4178}41794180// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)4181static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,4182unsigned Depth = 0) {4183if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))4184return true;4185if (V->getType()->getScalarSizeInBits() == 1)4186return true;4187if (Depth++ >= MaxAnalysisRecursionDepth)4188return false;4189Value *X;4190const Instruction *I = dyn_cast<Instruction>(V);4191if (!I)4192return false;4193switch (I->getOpcode()) {4194case Instruction::ZExt:4195// ZExt(Mask) is a Mask.4196return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);4197case Instruction::SExt:4198// SExt(Mask) is a Mask.4199// SExt(~Mask) is a ~Mask.4200return isMaskOrZero(I->getOperand(0), Not, Q, Depth);4201case Instruction::And:4202case Instruction::Or:4203// Mask0 | Mask1 is a Mask.4204// Mask0 & Mask1 is a Mask.4205// ~Mask0 | ~Mask1 is a ~Mask.4206// ~Mask0 & ~Mask1 is a ~Mask.4207return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&4208isMaskOrZero(I->getOperand(0), Not, Q, Depth);4209case Instruction::Xor:4210if (match(V, m_Not(m_Value(X))))4211return isMaskOrZero(X, !Not, Q, Depth);42124213// (X ^ -X) is a ~Mask4214if (Not)4215return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));4216// (X ^ (X - 1)) is a Mask4217else4218return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));4219case Instruction::Select:4220// c ? Mask0 : Mask1 is a Mask.4221return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&4222isMaskOrZero(I->getOperand(2), Not, Q, Depth);4223case Instruction::Shl:4224// (~Mask) << X is a ~Mask.4225return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);4226case Instruction::LShr:4227// Mask >> X is a Mask.4228return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);4229case Instruction::AShr:4230// Mask s>> X is a Mask.4231// ~Mask s>> X is a ~Mask.4232return isMaskOrZero(I->getOperand(0), Not, Q, Depth);4233case Instruction::Add:4234// Pow2 - 1 is a Mask.4235if (!Not && match(I->getOperand(1), m_AllOnes()))4236return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,4237Depth, Q.AC, Q.CxtI, Q.DT);4238break;4239case Instruction::Sub:4240// -Pow2 is a ~Mask.4241if (Not && match(I->getOperand(0), m_Zero()))4242return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,4243Depth, Q.AC, Q.CxtI, Q.DT);4244break;4245case Instruction::Call: {4246if (auto *II = dyn_cast<IntrinsicInst>(I)) {4247switch (II->getIntrinsicID()) {4248// min/max(Mask0, Mask1) is a Mask.4249// min/max(~Mask0, ~Mask1) is a ~Mask.4250case Intrinsic::umax:4251case Intrinsic::smax:4252case Intrinsic::umin:4253case Intrinsic::smin:4254return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&4255isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);42564257// In the context of masks, bitreverse(Mask) == ~Mask4258case Intrinsic::bitreverse:4259return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);4260default:4261break;4262}4263}4264break;4265}4266default:4267break;4268}4269return false;4270}42714272/// Some comparisons can be simplified.4273/// In this case, we are looking for comparisons that look like4274/// a check for a lossy truncation.4275/// Folds:4276/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask4277/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask4278/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask4279/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask4280/// Where Mask is some pattern that produces all-ones in low bits:4281/// (-1 >> y)4282/// ((-1 << y) >> y) <- non-canonical, has extra uses4283/// ~(-1 << y)4284/// ((1 << y) + (-1)) <- non-canonical, has extra uses4285/// The Mask can be a constant, too.4286/// For some predicates, the operands are commutative.4287/// For others, x can only be on a specific side.4288static Value *foldICmpWithLowBitMaskedVal(ICmpInst::Predicate Pred, Value *Op0,4289Value *Op1, const SimplifyQuery &Q,4290InstCombiner &IC) {42914292ICmpInst::Predicate DstPred;4293switch (Pred) {4294case ICmpInst::Predicate::ICMP_EQ:4295// x & Mask == x4296// x & ~Mask == 04297// ~x | Mask == -14298// -> x u<= Mask4299// x & ~Mask == ~Mask4300// -> ~Mask u<= x4301DstPred = ICmpInst::Predicate::ICMP_ULE;4302break;4303case ICmpInst::Predicate::ICMP_NE:4304// x & Mask != x4305// x & ~Mask != 04306// ~x | Mask != -14307// -> x u> Mask4308// x & ~Mask != ~Mask4309// -> ~Mask u> x4310DstPred = ICmpInst::Predicate::ICMP_UGT;4311break;4312case ICmpInst::Predicate::ICMP_ULT:4313// x & Mask u< x4314// -> x u> Mask4315// x & ~Mask u< ~Mask4316// -> ~Mask u> x4317DstPred = ICmpInst::Predicate::ICMP_UGT;4318break;4319case ICmpInst::Predicate::ICMP_UGE:4320// x & Mask u>= x4321// -> x u<= Mask4322// x & ~Mask u>= ~Mask4323// -> ~Mask u<= x4324DstPred = ICmpInst::Predicate::ICMP_ULE;4325break;4326case ICmpInst::Predicate::ICMP_SLT:4327// x & Mask s< x [iff Mask s>= 0]4328// -> x s> Mask4329// x & ~Mask s< ~Mask [iff ~Mask != 0]4330// -> ~Mask s> x4331DstPred = ICmpInst::Predicate::ICMP_SGT;4332break;4333case ICmpInst::Predicate::ICMP_SGE:4334// x & Mask s>= x [iff Mask s>= 0]4335// -> x s<= Mask4336// x & ~Mask s>= ~Mask [iff ~Mask != 0]4337// -> ~Mask s<= x4338DstPred = ICmpInst::Predicate::ICMP_SLE;4339break;4340default:4341// We don't support sgt,sle4342// ult/ugt are simplified to true/false respectively.4343return nullptr;4344}43454346Value *X, *M;4347// Put search code in lambda for early positive returns.4348auto IsLowBitMask = [&]() {4349if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {4350X = Op1;4351// Look for: x & Mask pred x4352if (isMaskOrZero(M, /*Not=*/false, Q)) {4353return !ICmpInst::isSigned(Pred) ||4354(match(M, m_NonNegative()) || isKnownNonNegative(M, Q));4355}43564357// Look for: x & ~Mask pred ~Mask4358if (isMaskOrZero(X, /*Not=*/true, Q)) {4359return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);4360}4361return false;4362}4363if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&4364match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {43654366auto Check = [&]() {4367// Look for: ~x | Mask == -14368if (isMaskOrZero(M, /*Not=*/false, Q)) {4369if (Value *NotX =4370IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {4371X = NotX;4372return true;4373}4374}4375return false;4376};4377if (Check())4378return true;4379std::swap(X, M);4380return Check();4381}4382if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&4383match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {4384auto Check = [&]() {4385// Look for: x & ~Mask == 04386if (isMaskOrZero(M, /*Not=*/true, Q)) {4387if (Value *NotM =4388IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {4389M = NotM;4390return true;4391}4392}4393return false;4394};4395if (Check())4396return true;4397std::swap(X, M);4398return Check();4399}4400return false;4401};44024403if (!IsLowBitMask())4404return nullptr;44054406return IC.Builder.CreateICmp(DstPred, X, M);4407}44084409/// Some comparisons can be simplified.4410/// In this case, we are looking for comparisons that look like4411/// a check for a lossy signed truncation.4412/// Folds: (MaskedBits is a constant.)4413/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x4414/// Into:4415/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)4416/// Where KeptBits = bitwidth(%x) - MaskedBits4417static Value *4418foldICmpWithTruncSignExtendedVal(ICmpInst &I,4419InstCombiner::BuilderTy &Builder) {4420ICmpInst::Predicate SrcPred;4421Value *X;4422const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.4423// We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.4424if (!match(&I, m_c_ICmp(SrcPred,4425m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),4426m_APInt(C1))),4427m_Deferred(X))))4428return nullptr;44294430// Potential handling of non-splats: for each element:4431// * if both are undef, replace with constant 0.4432// Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.4433// * if both are not undef, and are different, bailout.4434// * else, only one is undef, then pick the non-undef one.44354436// The shift amount must be equal.4437if (*C0 != *C1)4438return nullptr;4439const APInt &MaskedBits = *C0;4440assert(MaskedBits != 0 && "shift by zero should be folded away already.");44414442ICmpInst::Predicate DstPred;4443switch (SrcPred) {4444case ICmpInst::Predicate::ICMP_EQ:4445// ((%x << MaskedBits) a>> MaskedBits) == %x4446// =>4447// (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)4448DstPred = ICmpInst::Predicate::ICMP_ULT;4449break;4450case ICmpInst::Predicate::ICMP_NE:4451// ((%x << MaskedBits) a>> MaskedBits) != %x4452// =>4453// (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)4454DstPred = ICmpInst::Predicate::ICMP_UGE;4455break;4456// FIXME: are more folds possible?4457default:4458return nullptr;4459}44604461auto *XType = X->getType();4462const unsigned XBitWidth = XType->getScalarSizeInBits();4463const APInt BitWidth = APInt(XBitWidth, XBitWidth);4464assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");44654466// KeptBits = bitwidth(%x) - MaskedBits4467const APInt KeptBits = BitWidth - MaskedBits;4468assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");4469// ICmpCst = (1 << KeptBits)4470const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);4471assert(ICmpCst.isPowerOf2());4472// AddCst = (1 << (KeptBits-1))4473const APInt AddCst = ICmpCst.lshr(1);4474assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());44754476// T0 = add %x, AddCst4477Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));4478// T1 = T0 DstPred ICmpCst4479Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));44804481return T1;4482}44834484// Given pattern:4485// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 04486// we should move shifts to the same hand of 'and', i.e. rewrite as4487// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)4488// We are only interested in opposite logical shifts here.4489// One of the shifts can be truncated.4490// If we can, we want to end up creating 'lshr' shift.4491static Value *4492foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,4493InstCombiner::BuilderTy &Builder) {4494if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||4495!I.getOperand(0)->hasOneUse())4496return nullptr;44974498auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());44994500// Look for an 'and' of two logical shifts, one of which may be truncated.4501// We use m_TruncOrSelf() on the RHS to correctly handle commutative case.4502Instruction *XShift, *MaybeTruncation, *YShift;4503if (!match(4504I.getOperand(0),4505m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),4506m_CombineAnd(m_TruncOrSelf(m_CombineAnd(4507m_AnyLogicalShift, m_Instruction(YShift))),4508m_Instruction(MaybeTruncation)))))4509return nullptr;45104511// We potentially looked past 'trunc', but only when matching YShift,4512// therefore YShift must have the widest type.4513Instruction *WidestShift = YShift;4514// Therefore XShift must have the shallowest type.4515// Or they both have identical types if there was no truncation.4516Instruction *NarrowestShift = XShift;45174518Type *WidestTy = WidestShift->getType();4519Type *NarrowestTy = NarrowestShift->getType();4520assert(NarrowestTy == I.getOperand(0)->getType() &&4521"We did not look past any shifts while matching XShift though.");4522bool HadTrunc = WidestTy != I.getOperand(0)->getType();45234524// If YShift is a 'lshr', swap the shifts around.4525if (match(YShift, m_LShr(m_Value(), m_Value())))4526std::swap(XShift, YShift);45274528// The shifts must be in opposite directions.4529auto XShiftOpcode = XShift->getOpcode();4530if (XShiftOpcode == YShift->getOpcode())4531return nullptr; // Do not care about same-direction shifts here.45324533Value *X, *XShAmt, *Y, *YShAmt;4534match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));4535match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));45364537// If one of the values being shifted is a constant, then we will end with4538// and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,4539// however, we will need to ensure that we won't increase instruction count.4540if (!isa<Constant>(X) && !isa<Constant>(Y)) {4541// At least one of the hands of the 'and' should be one-use shift.4542if (!match(I.getOperand(0),4543m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))4544return nullptr;4545if (HadTrunc) {4546// Due to the 'trunc', we will need to widen X. For that either the old4547// 'trunc' or the shift amt in the non-truncated shift should be one-use.4548if (!MaybeTruncation->hasOneUse() &&4549!NarrowestShift->getOperand(1)->hasOneUse())4550return nullptr;4551}4552}45534554// We have two shift amounts from two different shifts. The types of those4555// shift amounts may not match. If that's the case let's bailout now.4556if (XShAmt->getType() != YShAmt->getType())4557return nullptr;45584559// As input, we have the following pattern:4560// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 04561// We want to rewrite that as:4562// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)4563// While we know that originally (Q+K) would not overflow4564// (because 2 * (N-1) u<= iN -1), we have looked past extensions of4565// shift amounts. so it may now overflow in smaller bitwidth.4566// To ensure that does not happen, we need to ensure that the total maximal4567// shift amount is still representable in that smaller bit width.4568unsigned MaximalPossibleTotalShiftAmount =4569(WidestTy->getScalarSizeInBits() - 1) +4570(NarrowestTy->getScalarSizeInBits() - 1);4571APInt MaximalRepresentableShiftAmount =4572APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits());4573if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))4574return nullptr;45754576// Can we fold (XShAmt+YShAmt) ?4577auto *NewShAmt = dyn_cast_or_null<Constant>(4578simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,4579/*isNUW=*/false, SQ.getWithInstruction(&I)));4580if (!NewShAmt)4581return nullptr;4582if (NewShAmt->getType() != WidestTy) {4583NewShAmt =4584ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);4585if (!NewShAmt)4586return nullptr;4587}4588unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();45894590// Is the new shift amount smaller than the bit width?4591// FIXME: could also rely on ConstantRange.4592if (!match(NewShAmt,4593m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,4594APInt(WidestBitWidth, WidestBitWidth))))4595return nullptr;45964597// An extra legality check is needed if we had trunc-of-lshr.4598if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {4599auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,4600WidestShift]() {4601// It isn't obvious whether it's worth it to analyze non-constants here.4602// Also, let's basically give up on non-splat cases, pessimizing vectors.4603// If *any* of these preconditions matches we can perform the fold.4604Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()4605? NewShAmt->getSplatValue()4606: NewShAmt;4607// If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.4608if (NewShAmtSplat &&4609(NewShAmtSplat->isNullValue() ||4610NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))4611return true;4612// We consider *min* leading zeros so a single outlier4613// blocks the transform as opposed to allowing it.4614if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {4615KnownBits Known = computeKnownBits(C, SQ.DL);4616unsigned MinLeadZero = Known.countMinLeadingZeros();4617// If the value being shifted has at most lowest bit set we can fold.4618unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;4619if (MaxActiveBits <= 1)4620return true;4621// Precondition: NewShAmt u<= countLeadingZeros(C)4622if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))4623return true;4624}4625if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {4626KnownBits Known = computeKnownBits(C, SQ.DL);4627unsigned MinLeadZero = Known.countMinLeadingZeros();4628// If the value being shifted has at most lowest bit set we can fold.4629unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;4630if (MaxActiveBits <= 1)4631return true;4632// Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)4633if (NewShAmtSplat) {4634APInt AdjNewShAmt =4635(WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();4636if (AdjNewShAmt.ule(MinLeadZero))4637return true;4638}4639}4640return false; // Can't tell if it's ok.4641};4642if (!CanFold())4643return nullptr;4644}46454646// All good, we can do this fold.4647X = Builder.CreateZExt(X, WidestTy);4648Y = Builder.CreateZExt(Y, WidestTy);4649// The shift is the same that was for X.4650Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr4651? Builder.CreateLShr(X, NewShAmt)4652: Builder.CreateShl(X, NewShAmt);4653Value *T1 = Builder.CreateAnd(T0, Y);4654return Builder.CreateICmp(I.getPredicate(), T1,4655Constant::getNullValue(WidestTy));4656}46574658/// Fold4659/// (-1 u/ x) u< y4660/// ((x * y) ?/ x) != y4661/// to4662/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit4663/// Note that the comparison is commutative, while inverted (u>=, ==) predicate4664/// will mean that we are looking for the opposite answer.4665Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {4666ICmpInst::Predicate Pred;4667Value *X, *Y;4668Instruction *Mul;4669Instruction *Div;4670bool NeedNegation;4671// Look for: (-1 u/ x) u</u>= y4672if (!I.isEquality() &&4673match(&I, m_c_ICmp(Pred,4674m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),4675m_Instruction(Div)),4676m_Value(Y)))) {4677Mul = nullptr;46784679// Are we checking that overflow does not happen, or does happen?4680switch (Pred) {4681case ICmpInst::Predicate::ICMP_ULT:4682NeedNegation = false;4683break; // OK4684case ICmpInst::Predicate::ICMP_UGE:4685NeedNegation = true;4686break; // OK4687default:4688return nullptr; // Wrong predicate.4689}4690} else // Look for: ((x * y) / x) !=/== y4691if (I.isEquality() &&4692match(&I,4693m_c_ICmp(Pred, m_Value(Y),4694m_CombineAnd(4695m_OneUse(m_IDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y),4696m_Value(X)),4697m_Instruction(Mul)),4698m_Deferred(X))),4699m_Instruction(Div))))) {4700NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;4701} else4702return nullptr;47034704BuilderTy::InsertPointGuard Guard(Builder);4705// If the pattern included (x * y), we'll want to insert new instructions4706// right before that original multiplication so that we can replace it.4707bool MulHadOtherUses = Mul && !Mul->hasOneUse();4708if (MulHadOtherUses)4709Builder.SetInsertPoint(Mul);47104711Function *F = Intrinsic::getDeclaration(I.getModule(),4712Div->getOpcode() == Instruction::UDiv4713? Intrinsic::umul_with_overflow4714: Intrinsic::smul_with_overflow,4715X->getType());4716CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");47174718// If the multiplication was used elsewhere, to ensure that we don't leave4719// "duplicate" instructions, replace uses of that original multiplication4720// with the multiplication result from the with.overflow intrinsic.4721if (MulHadOtherUses)4722replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));47234724Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");4725if (NeedNegation) // This technically increases instruction count.4726Res = Builder.CreateNot(Res, "mul.not.ov");47274728// If we replaced the mul, erase it. Do this after all uses of Builder,4729// as the mul is used as insertion point.4730if (MulHadOtherUses)4731eraseInstFromFunction(*Mul);47324733return Res;4734}47354736static Instruction *foldICmpXNegX(ICmpInst &I,4737InstCombiner::BuilderTy &Builder) {4738CmpInst::Predicate Pred;4739Value *X;4740if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {47414742if (ICmpInst::isSigned(Pred))4743Pred = ICmpInst::getSwappedPredicate(Pred);4744else if (ICmpInst::isUnsigned(Pred))4745Pred = ICmpInst::getSignedPredicate(Pred);4746// else for equality-comparisons just keep the predicate.47474748return ICmpInst::Create(Instruction::ICmp, Pred, X,4749Constant::getNullValue(X->getType()), I.getName());4750}47514752// A value is not equal to its negation unless that value is 0 or4753// MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 04754if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&4755ICmpInst::isEquality(Pred)) {4756Type *Ty = X->getType();4757uint32_t BitWidth = Ty->getScalarSizeInBits();4758Constant *MaxSignedVal =4759ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));4760Value *And = Builder.CreateAnd(X, MaxSignedVal);4761Constant *Zero = Constant::getNullValue(Ty);4762return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);4763}47644765return nullptr;4766}47674768static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,4769InstCombinerImpl &IC) {4770Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;4771// Normalize and operand as operand 0.4772CmpInst::Predicate Pred = I.getPredicate();4773if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {4774std::swap(Op0, Op1);4775Pred = ICmpInst::getSwappedPredicate(Pred);4776}47774778if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))4779return nullptr;47804781// (icmp (X & Y) u< X --> (X & Y) != X4782if (Pred == ICmpInst::ICMP_ULT)4783return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);47844785// (icmp (X & Y) u>= X --> (X & Y) == X4786if (Pred == ICmpInst::ICMP_UGE)4787return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);47884789if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {4790// icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and4791// Y is non-constant. If Y is constant the `X & C == C` form is preferable4792// so don't do this fold.4793if (!match(Op1, m_ImmConstant()))4794if (auto *NotOp1 =4795IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))4796return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),4797Constant::getAllOnesValue(Op1->getType()));4798// icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.4799if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))4800return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),4801Constant::getNullValue(Op1->getType()));4802}48034804if (!ICmpInst::isSigned(Pred))4805return nullptr;48064807KnownBits KnownY = IC.computeKnownBits(A, /*Depth=*/0, &I);4808// (X & NegY) spred X --> (X & NegY) upred X4809if (KnownY.isNegative())4810return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);48114812if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)4813return nullptr;48144815if (KnownY.isNonNegative())4816// (X & PosY) s<= X --> X s>= 04817// (X & PosY) s> X --> X s< 04818return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,4819Constant::getNullValue(Op1->getType()));48204821if (isKnownNegative(Op1, IC.getSimplifyQuery().getWithInstruction(&I)))4822// (NegX & Y) s<= NegX --> Y s< 04823// (NegX & Y) s> NegX --> Y s>= 04824return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(Pred), A,4825Constant::getNullValue(A->getType()));48264827return nullptr;4828}48294830static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,4831InstCombinerImpl &IC) {4832Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;48334834// Normalize or operand as operand 0.4835CmpInst::Predicate Pred = I.getPredicate();4836if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {4837std::swap(Op0, Op1);4838Pred = ICmpInst::getSwappedPredicate(Pred);4839} else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {4840return nullptr;4841}48424843// icmp (X | Y) u<= X --> (X | Y) == X4844if (Pred == ICmpInst::ICMP_ULE)4845return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);48464847// icmp (X | Y) u> X --> (X | Y) != X4848if (Pred == ICmpInst::ICMP_UGT)4849return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);48504851if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {4852// icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible4853if (Value *NotOp1 =4854IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))4855return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),4856Constant::getNullValue(Op1->getType()));4857// icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.4858if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))4859return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),4860Constant::getAllOnesValue(Op1->getType()));4861}4862return nullptr;4863}48644865static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,4866InstCombinerImpl &IC) {4867Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;4868// Normalize xor operand as operand 0.4869CmpInst::Predicate Pred = I.getPredicate();4870if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {4871std::swap(Op0, Op1);4872Pred = ICmpInst::getSwappedPredicate(Pred);4873}4874if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))4875return nullptr;48764877// icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X4878// icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X4879// icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X4880// icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X4881CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(Pred);4882if (PredOut != Pred && isKnownNonZero(A, Q))4883return new ICmpInst(PredOut, Op0, Op1);48844885return nullptr;4886}48874888/// Try to fold icmp (binop), X or icmp X, (binop).4889/// TODO: A large part of this logic is duplicated in InstSimplify's4890/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code4891/// duplication.4892Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,4893const SimplifyQuery &SQ) {4894const SimplifyQuery Q = SQ.getWithInstruction(&I);4895Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);48964897// Special logic for binary operators.4898BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);4899BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);4900if (!BO0 && !BO1)4901return nullptr;49024903if (Instruction *NewICmp = foldICmpXNegX(I, Builder))4904return NewICmp;49054906const CmpInst::Predicate Pred = I.getPredicate();4907Value *X;49084909// Convert add-with-unsigned-overflow comparisons into a 'not' with compare.4910// (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X4911if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&4912(Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))4913return new ICmpInst(Pred, Builder.CreateNot(Op1), X);4914// Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op04915if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&4916(Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))4917return new ICmpInst(Pred, X, Builder.CreateNot(Op0));49184919{4920// (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op14921Constant *C;4922if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),4923m_ImmConstant(C)))) &&4924(Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {4925Constant *C2 = ConstantExpr::getNot(C);4926return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);4927}4928// Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X4929if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),4930m_ImmConstant(C)))) &&4931(Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {4932Constant *C2 = ConstantExpr::getNot(C);4933return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));4934}4935}49364937{4938// Similar to above: an unsigned overflow comparison may use offset + mask:4939// ((Op1 + C) & C) u< Op1 --> Op1 != 04940// ((Op1 + C) & C) u>= Op1 --> Op1 == 04941// Op0 u> ((Op0 + C) & C) --> Op0 != 04942// Op0 u<= ((Op0 + C) & C) --> Op0 == 04943BinaryOperator *BO;4944const APInt *C;4945if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&4946match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&4947match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowPoison(*C)))) {4948CmpInst::Predicate NewPred =4949Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;4950Constant *Zero = ConstantInt::getNullValue(Op1->getType());4951return new ICmpInst(NewPred, Op1, Zero);4952}49534954if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&4955match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&4956match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowPoison(*C)))) {4957CmpInst::Predicate NewPred =4958Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;4959Constant *Zero = ConstantInt::getNullValue(Op1->getType());4960return new ICmpInst(NewPred, Op0, Zero);4961}4962}49634964bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;4965bool Op0HasNUW = false, Op1HasNUW = false;4966bool Op0HasNSW = false, Op1HasNSW = false;4967// Analyze the case when either Op0 or Op1 is an add instruction.4968// Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).4969auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,4970bool &HasNSW, bool &HasNUW) -> bool {4971if (isa<OverflowingBinaryOperator>(BO)) {4972HasNUW = BO.hasNoUnsignedWrap();4973HasNSW = BO.hasNoSignedWrap();4974return ICmpInst::isEquality(Pred) ||4975(CmpInst::isUnsigned(Pred) && HasNUW) ||4976(CmpInst::isSigned(Pred) && HasNSW);4977} else if (BO.getOpcode() == Instruction::Or) {4978HasNUW = true;4979HasNSW = true;4980return true;4981} else {4982return false;4983}4984};4985Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;49864987if (BO0) {4988match(BO0, m_AddLike(m_Value(A), m_Value(B)));4989NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);4990}4991if (BO1) {4992match(BO1, m_AddLike(m_Value(C), m_Value(D)));4993NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);4994}49954996// icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.4997// icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.4998if ((A == Op1 || B == Op1) && NoOp0WrapProblem)4999return new ICmpInst(Pred, A == Op1 ? B : A,5000Constant::getNullValue(Op1->getType()));50015002// icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.5003// icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.5004if ((C == Op0 || D == Op0) && NoOp1WrapProblem)5005return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),5006C == Op0 ? D : C);50075008// icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.5009if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&5010NoOp1WrapProblem) {5011// Determine Y and Z in the form icmp (X+Y), (X+Z).5012Value *Y, *Z;5013if (A == C) {5014// C + B == C + D -> B == D5015Y = B;5016Z = D;5017} else if (A == D) {5018// D + B == C + D -> B == C5019Y = B;5020Z = C;5021} else if (B == C) {5022// A + C == C + D -> A == D5023Y = A;5024Z = D;5025} else {5026assert(B == D);5027// A + D == C + D -> A == C5028Y = A;5029Z = C;5030}5031return new ICmpInst(Pred, Y, Z);5032}50335034// icmp slt (A + -1), Op1 -> icmp sle A, Op15035if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&5036match(B, m_AllOnes()))5037return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);50385039// icmp sge (A + -1), Op1 -> icmp sgt A, Op15040if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&5041match(B, m_AllOnes()))5042return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);50435044// icmp sle (A + 1), Op1 -> icmp slt A, Op15045if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))5046return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);50475048// icmp sgt (A + 1), Op1 -> icmp sge A, Op15049if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))5050return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);50515052// icmp sgt Op0, (C + -1) -> icmp sge Op0, C5053if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&5054match(D, m_AllOnes()))5055return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);50565057// icmp sle Op0, (C + -1) -> icmp slt Op0, C5058if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&5059match(D, m_AllOnes()))5060return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);50615062// icmp sge Op0, (C + 1) -> icmp sgt Op0, C5063if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))5064return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);50655066// icmp slt Op0, (C + 1) -> icmp sle Op0, C5067if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))5068return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);50695070// TODO: The subtraction-related identities shown below also hold, but5071// canonicalization from (X -nuw 1) to (X + -1) means that the combinations5072// wouldn't happen even if they were implemented.5073//5074// icmp ult (A - 1), Op1 -> icmp ule A, Op15075// icmp uge (A - 1), Op1 -> icmp ugt A, Op15076// icmp ugt Op0, (C - 1) -> icmp uge Op0, C5077// icmp ule Op0, (C - 1) -> icmp ult Op0, C50785079// icmp ule (A + 1), Op0 -> icmp ult A, Op15080if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))5081return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);50825083// icmp ugt (A + 1), Op0 -> icmp uge A, Op15084if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))5085return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);50865087// icmp uge Op0, (C + 1) -> icmp ugt Op0, C5088if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))5089return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);50905091// icmp ult Op0, (C + 1) -> icmp ule Op0, C5092if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))5093return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);50945095// if C1 has greater magnitude than C2:5096// icmp (A + C1), (C + C2) -> icmp (A + C3), C5097// s.t. C3 = C1 - C25098//5099// if C2 has greater magnitude than C1:5100// icmp (A + C1), (C + C2) -> icmp A, (C + C3)5101// s.t. C3 = C2 - C15102if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&5103(BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {5104const APInt *AP1, *AP2;5105// TODO: Support non-uniform vectors.5106// TODO: Allow poison passthrough if B or D's element is poison.5107if (match(B, m_APIntAllowPoison(AP1)) &&5108match(D, m_APIntAllowPoison(AP2)) &&5109AP1->isNegative() == AP2->isNegative()) {5110APInt AP1Abs = AP1->abs();5111APInt AP2Abs = AP2->abs();5112if (AP1Abs.uge(AP2Abs)) {5113APInt Diff = *AP1 - *AP2;5114Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);5115Value *NewAdd = Builder.CreateAdd(5116A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);5117return new ICmpInst(Pred, NewAdd, C);5118} else {5119APInt Diff = *AP2 - *AP1;5120Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);5121Value *NewAdd = Builder.CreateAdd(5122C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);5123return new ICmpInst(Pred, A, NewAdd);5124}5125}5126Constant *Cst1, *Cst2;5127if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&5128ICmpInst::isEquality(Pred)) {5129Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);5130Value *NewAdd = Builder.CreateAdd(C, Diff);5131return new ICmpInst(Pred, A, NewAdd);5132}5133}51345135// Analyze the case when either Op0 or Op1 is a sub instruction.5136// Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).5137A = nullptr;5138B = nullptr;5139C = nullptr;5140D = nullptr;5141if (BO0 && BO0->getOpcode() == Instruction::Sub) {5142A = BO0->getOperand(0);5143B = BO0->getOperand(1);5144}5145if (BO1 && BO1->getOpcode() == Instruction::Sub) {5146C = BO1->getOperand(0);5147D = BO1->getOperand(1);5148}51495150// icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.5151if (A == Op1 && NoOp0WrapProblem)5152return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);5153// icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.5154if (C == Op0 && NoOp1WrapProblem)5155return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));51565157// Convert sub-with-unsigned-overflow comparisons into a comparison of args.5158// (A - B) u>/u<= A --> B u>/u<= A5159if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))5160return new ICmpInst(Pred, B, A);5161// C u</u>= (C - D) --> C u</u>= D5162if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))5163return new ICmpInst(Pred, C, D);5164// (A - B) u>=/u< A --> B u>/u<= A iff B != 05165if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&5166isKnownNonZero(B, Q))5167return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);5168// C u<=/u> (C - D) --> C u</u>= D iff B != 05169if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&5170isKnownNonZero(D, Q))5171return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);51725173// icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.5174if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)5175return new ICmpInst(Pred, A, C);51765177// icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.5178if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)5179return new ICmpInst(Pred, D, B);51805181// icmp (0-X) < cst --> x > -cst5182if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {5183Value *X;5184if (match(BO0, m_Neg(m_Value(X))))5185if (Constant *RHSC = dyn_cast<Constant>(Op1))5186if (RHSC->isNotMinSignedValue())5187return new ICmpInst(I.getSwappedPredicate(), X,5188ConstantExpr::getNeg(RHSC));5189}51905191if (Instruction * R = foldICmpXorXX(I, Q, *this))5192return R;5193if (Instruction *R = foldICmpOrXX(I, Q, *this))5194return R;51955196{5197// Try to remove shared multiplier from comparison:5198// X * Z u{lt/le/gt/ge}/eq/ne Y * Z5199Value *X, *Y, *Z;5200if (Pred == ICmpInst::getUnsignedPredicate(Pred) &&5201((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&5202match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||5203(match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&5204match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))))) {5205bool NonZero;5206if (ICmpInst::isEquality(Pred)) {5207KnownBits ZKnown = computeKnownBits(Z, 0, &I);5208// if Z % 2 != 05209// X * Z eq/ne Y * Z -> X eq/ne Y5210if (ZKnown.countMaxTrailingZeros() == 0)5211return new ICmpInst(Pred, X, Y);5212NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);5213// if Z != 0 and nsw(X * Z) and nsw(Y * Z)5214// X * Z eq/ne Y * Z -> X eq/ne Y5215if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)5216return new ICmpInst(Pred, X, Y);5217} else5218NonZero = isKnownNonZero(Z, Q);52195220// If Z != 0 and nuw(X * Z) and nuw(Y * Z)5221// X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y5222if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)5223return new ICmpInst(Pred, X, Y);5224}5225}52265227BinaryOperator *SRem = nullptr;5228// icmp (srem X, Y), Y5229if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))5230SRem = BO0;5231// icmp Y, (srem X, Y)5232else if (BO1 && BO1->getOpcode() == Instruction::SRem &&5233Op0 == BO1->getOperand(1))5234SRem = BO1;5235if (SRem) {5236// We don't check hasOneUse to avoid increasing register pressure because5237// the value we use is the same value this instruction was already using.5238switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {5239default:5240break;5241case ICmpInst::ICMP_EQ:5242return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));5243case ICmpInst::ICMP_NE:5244return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));5245case ICmpInst::ICMP_SGT:5246case ICmpInst::ICMP_SGE:5247return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),5248Constant::getAllOnesValue(SRem->getType()));5249case ICmpInst::ICMP_SLT:5250case ICmpInst::ICMP_SLE:5251return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),5252Constant::getNullValue(SRem->getType()));5253}5254}52555256if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&5257(BO0->hasOneUse() || BO1->hasOneUse()) &&5258BO0->getOperand(1) == BO1->getOperand(1)) {5259switch (BO0->getOpcode()) {5260default:5261break;5262case Instruction::Add:5263case Instruction::Sub:5264case Instruction::Xor: {5265if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b5266return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));52675268const APInt *C;5269if (match(BO0->getOperand(1), m_APInt(C))) {5270// icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b5271if (C->isSignMask()) {5272ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();5273return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));5274}52755276// icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b5277if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {5278ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();5279NewPred = I.getSwappedPredicate(NewPred);5280return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));5281}5282}5283break;5284}5285case Instruction::Mul: {5286if (!I.isEquality())5287break;52885289const APInt *C;5290if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&5291!C->isOne()) {5292// icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)5293// Mask = -1 >> count-trailing-zeros(C).5294if (unsigned TZs = C->countr_zero()) {5295Constant *Mask = ConstantInt::get(5296BO0->getType(),5297APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));5298Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);5299Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);5300return new ICmpInst(Pred, And1, And2);5301}5302}5303break;5304}5305case Instruction::UDiv:5306case Instruction::LShr:5307if (I.isSigned() || !BO0->isExact() || !BO1->isExact())5308break;5309return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));53105311case Instruction::SDiv:5312if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||5313!BO0->isExact() || !BO1->isExact())5314break;5315return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));53165317case Instruction::AShr:5318if (!BO0->isExact() || !BO1->isExact())5319break;5320return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));53215322case Instruction::Shl: {5323bool NUW = Op0HasNUW && Op1HasNUW;5324bool NSW = Op0HasNSW && Op1HasNSW;5325if (!NUW && !NSW)5326break;5327if (!NSW && I.isSigned())5328break;5329return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));5330}5331}5332}53335334if (BO0) {5335// Transform A & (L - 1) `ult` L --> L != 05336auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());5337auto BitwiseAnd = m_c_And(m_Value(), LSubOne);53385339if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {5340auto *Zero = Constant::getNullValue(BO0->getType());5341return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);5342}5343}53445345// For unsigned predicates / eq / ne:5346// icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 05347// icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x5348if (!ICmpInst::isSigned(Pred)) {5349if (match(Op0, m_Shl(m_Specific(Op1), m_One())))5350return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,5351Constant::getNullValue(Op1->getType()));5352else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))5353return new ICmpInst(ICmpInst::getSignedPredicate(Pred),5354Constant::getNullValue(Op0->getType()), Op0);5355}53565357if (Value *V = foldMultiplicationOverflowCheck(I))5358return replaceInstUsesWith(I, V);53595360if (Instruction *R = foldICmpAndXX(I, Q, *this))5361return R;53625363if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))5364return replaceInstUsesWith(I, V);53655366if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))5367return replaceInstUsesWith(I, V);53685369return nullptr;5370}53715372/// Fold icmp Pred min|max(X, Y), Z.5373Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,5374MinMaxIntrinsic *MinMax,5375Value *Z,5376ICmpInst::Predicate Pred) {5377Value *X = MinMax->getLHS();5378Value *Y = MinMax->getRHS();5379if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())5380return nullptr;5381if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {5382// Revert the transform signed pred -> unsigned pred5383// TODO: We can flip the signedness of predicate if both operands of icmp5384// are negative.5385if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&5386isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {5387Pred = ICmpInst::getFlippedSignednessPredicate(Pred);5388} else5389return nullptr;5390}5391SimplifyQuery Q = SQ.getWithInstruction(&I);5392auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {5393if (!Val)5394return std::nullopt;5395if (match(Val, m_One()))5396return true;5397if (match(Val, m_Zero()))5398return false;5399return std::nullopt;5400};5401auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));5402auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));5403if (!CmpXZ.has_value() && !CmpYZ.has_value())5404return nullptr;5405if (!CmpXZ.has_value()) {5406std::swap(X, Y);5407std::swap(CmpXZ, CmpYZ);5408}54095410auto FoldIntoCmpYZ = [&]() -> Instruction * {5411if (CmpYZ.has_value())5412return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));5413return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);5414};54155416switch (Pred) {5417case ICmpInst::ICMP_EQ:5418case ICmpInst::ICMP_NE: {5419// If X == Z:5420// Expr Result5421// min(X, Y) == Z X <= Y5422// max(X, Y) == Z X >= Y5423// min(X, Y) != Z X > Y5424// max(X, Y) != Z X < Y5425if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {5426ICmpInst::Predicate NewPred =5427ICmpInst::getNonStrictPredicate(MinMax->getPredicate());5428if (Pred == ICmpInst::ICMP_NE)5429NewPred = ICmpInst::getInversePredicate(NewPred);5430return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);5431}5432// Otherwise (X != Z):5433ICmpInst::Predicate NewPred = MinMax->getPredicate();5434auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));5435if (!MinMaxCmpXZ.has_value()) {5436std::swap(X, Y);5437std::swap(CmpXZ, CmpYZ);5438// Re-check pre-condition X != Z5439if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)5440break;5441MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));5442}5443if (!MinMaxCmpXZ.has_value())5444break;5445if (*MinMaxCmpXZ) {5446// Expr Fact Result5447// min(X, Y) == Z X < Z false5448// max(X, Y) == Z X > Z false5449// min(X, Y) != Z X < Z true5450// max(X, Y) != Z X > Z true5451return replaceInstUsesWith(5452I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));5453} else {5454// Expr Fact Result5455// min(X, Y) == Z X > Z Y == Z5456// max(X, Y) == Z X < Z Y == Z5457// min(X, Y) != Z X > Z Y != Z5458// max(X, Y) != Z X < Z Y != Z5459return FoldIntoCmpYZ();5460}5461break;5462}5463case ICmpInst::ICMP_SLT:5464case ICmpInst::ICMP_ULT:5465case ICmpInst::ICMP_SLE:5466case ICmpInst::ICMP_ULE:5467case ICmpInst::ICMP_SGT:5468case ICmpInst::ICMP_UGT:5469case ICmpInst::ICMP_SGE:5470case ICmpInst::ICMP_UGE: {5471bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);5472if (*CmpXZ) {5473if (IsSame) {5474// Expr Fact Result5475// min(X, Y) < Z X < Z true5476// min(X, Y) <= Z X <= Z true5477// max(X, Y) > Z X > Z true5478// max(X, Y) >= Z X >= Z true5479return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));5480} else {5481// Expr Fact Result5482// max(X, Y) < Z X < Z Y < Z5483// max(X, Y) <= Z X <= Z Y <= Z5484// min(X, Y) > Z X > Z Y > Z5485// min(X, Y) >= Z X >= Z Y >= Z5486return FoldIntoCmpYZ();5487}5488} else {5489if (IsSame) {5490// Expr Fact Result5491// min(X, Y) < Z X >= Z Y < Z5492// min(X, Y) <= Z X > Z Y <= Z5493// max(X, Y) > Z X <= Z Y > Z5494// max(X, Y) >= Z X < Z Y >= Z5495return FoldIntoCmpYZ();5496} else {5497// Expr Fact Result5498// max(X, Y) < Z X >= Z false5499// max(X, Y) <= Z X > Z false5500// min(X, Y) > Z X <= Z false5501// min(X, Y) >= Z X < Z false5502return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));5503}5504}5505break;5506}5507default:5508break;5509}55105511return nullptr;5512}55135514// Canonicalize checking for a power-of-2-or-zero value:5515static Instruction *foldICmpPow2Test(ICmpInst &I,5516InstCombiner::BuilderTy &Builder) {5517Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);5518const CmpInst::Predicate Pred = I.getPredicate();5519Value *A = nullptr;5520bool CheckIs;5521if (I.isEquality()) {5522// (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)5523// ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)5524if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),5525m_Deferred(A)))) ||5526!match(Op1, m_ZeroInt()))5527A = nullptr;55285529// (A & -A) == A --> ctpop(A) < 2 (four commuted variants)5530// (-A & A) != A --> ctpop(A) > 1 (four commuted variants)5531if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))5532A = Op1;5533else if (match(Op1,5534m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))5535A = Op0;55365537CheckIs = Pred == ICmpInst::ICMP_EQ;5538} else if (ICmpInst::isUnsigned(Pred)) {5539// (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)5540// ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)55415542if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&5543match(Op0, m_OneUse(m_c_Xor(m_Add(m_Specific(Op1), m_AllOnes()),5544m_Specific(Op1))))) {5545A = Op1;5546CheckIs = Pred == ICmpInst::ICMP_UGE;5547} else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&5548match(Op1, m_OneUse(m_c_Xor(m_Add(m_Specific(Op0), m_AllOnes()),5549m_Specific(Op0))))) {5550A = Op0;5551CheckIs = Pred == ICmpInst::ICMP_ULE;5552}5553}55545555if (A) {5556Type *Ty = A->getType();5557CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);5558return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,5559ConstantInt::get(Ty, 2))5560: new ICmpInst(ICmpInst::ICMP_UGT, CtPop,5561ConstantInt::get(Ty, 1));5562}55635564return nullptr;5565}55665567Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {5568if (!I.isEquality())5569return nullptr;55705571Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);5572const CmpInst::Predicate Pred = I.getPredicate();5573Value *A, *B, *C, *D;5574if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {5575if (A == Op1 || B == Op1) { // (A^B) == A -> B == 05576Value *OtherVal = A == Op1 ? B : A;5577return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));5578}55795580if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {5581// A^c1 == C^c2 --> A == C^(c1^c2)5582ConstantInt *C1, *C2;5583if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&5584Op1->hasOneUse()) {5585Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());5586Value *Xor = Builder.CreateXor(C, NC);5587return new ICmpInst(Pred, A, Xor);5588}55895590// A^B == A^D -> B == D5591if (A == C)5592return new ICmpInst(Pred, B, D);5593if (A == D)5594return new ICmpInst(Pred, B, C);5595if (B == C)5596return new ICmpInst(Pred, A, D);5597if (B == D)5598return new ICmpInst(Pred, A, C);5599}5600}56015602if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {5603// A == (A^B) -> B == 05604Value *OtherVal = A == Op0 ? B : A;5605return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));5606}56075608// (X&Z) == (Y&Z) -> (X^Y) & Z == 05609if (match(Op0, m_And(m_Value(A), m_Value(B))) &&5610match(Op1, m_And(m_Value(C), m_Value(D)))) {5611Value *X = nullptr, *Y = nullptr, *Z = nullptr;56125613if (A == C) {5614X = B;5615Y = D;5616Z = A;5617} else if (A == D) {5618X = B;5619Y = C;5620Z = A;5621} else if (B == C) {5622X = A;5623Y = D;5624Z = B;5625} else if (B == D) {5626X = A;5627Y = C;5628Z = B;5629}56305631if (X) {5632// If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`5633// will fold to `icmp ult/uge Z, -NegP2` incurringb no additional5634// instructions.5635const APInt *C0, *C1;5636bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&5637(*C0 ^ *C1).isNegatedPowerOf2();56385639// If either Op0/Op1 are both one use or X^Y will constant fold and one of5640// Op0/Op1 are one use, proceed. In those cases we are instruction neutral5641// but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.5642int UseCnt =5643int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +5644(int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));5645if (XorIsNegP2 || UseCnt >= 2) {5646// Build (X^Y) & Z5647Op1 = Builder.CreateXor(X, Y);5648Op1 = Builder.CreateAnd(Op1, Z);5649return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));5650}5651}5652}56535654{5655// Similar to above, but specialized for constant because invert is needed:5656// (X | C) == (Y | C) --> (X ^ Y) & ~C == 05657Value *X, *Y;5658Constant *C;5659if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&5660match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {5661Value *Xor = Builder.CreateXor(X, Y);5662Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));5663return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));5664}5665}56665667if (match(Op1, m_ZExt(m_Value(A))) &&5668(Op0->hasOneUse() || Op1->hasOneUse())) {5669// (B & (Pow2C-1)) == zext A --> A == trunc B5670// (B & (Pow2C-1)) != zext A --> A != trunc B5671const APInt *MaskC;5672if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&5673MaskC->countr_one() == A->getType()->getScalarSizeInBits())5674return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));5675}56765677// (A >> C) == (B >> C) --> (A^B) u< (1 << C)5678// For lshr and ashr pairs.5679const APInt *AP1, *AP2;5680if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&5681match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||5682(match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&5683match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {5684if (AP1 != AP2)5685return nullptr;5686unsigned TypeBits = AP1->getBitWidth();5687unsigned ShAmt = AP1->getLimitedValue(TypeBits);5688if (ShAmt < TypeBits && ShAmt != 0) {5689ICmpInst::Predicate NewPred =5690Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;5691Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");5692APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);5693return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));5694}5695}56965697// (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 05698ConstantInt *Cst1;5699if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&5700match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {5701unsigned TypeBits = Cst1->getBitWidth();5702unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);5703if (ShAmt < TypeBits && ShAmt != 0) {5704Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");5705APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);5706Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),5707I.getName() + ".mask");5708return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));5709}5710}57115712// Transform "icmp eq (trunc (lshr(X, cst1)), cst" to5713// "icmp (and X, mask), cst"5714uint64_t ShAmt = 0;5715if (Op0->hasOneUse() &&5716match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&5717match(Op1, m_ConstantInt(Cst1)) &&5718// Only do this when A has multiple uses. This is most important to do5719// when it exposes other optimizations.5720!A->hasOneUse()) {5721unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();57225723if (ShAmt < ASize) {5724APInt MaskV =5725APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());5726MaskV <<= ShAmt;57275728APInt CmpV = Cst1->getValue().zext(ASize);5729CmpV <<= ShAmt;57305731Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));5732return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));5733}5734}57355736if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I, Builder))5737return ICmp;57385739// Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the5740// top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX",5741// which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps5742// of instcombine.5743unsigned BitWidth = Op0->getType()->getScalarSizeInBits();5744if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&5745match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&5746A->getType()->getScalarSizeInBits() == BitWidth * 2 &&5747(I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {5748APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);5749Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));5750return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT5751: ICmpInst::ICMP_UGE,5752Add, ConstantInt::get(A->getType(), C.shl(1)));5753}57545755// Canonicalize:5756// Assume B_Pow2 != 05757// 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 05758// 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 05759if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&5760isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))5761return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,5762ConstantInt::getNullValue(Op0->getType()));57635764if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&5765isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))5766return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,5767ConstantInt::getNullValue(Op1->getType()));57685769// Canonicalize:5770// icmp eq/ne X, OneUse(rotate-right(X))5771// -> icmp eq/ne X, rotate-left(X)5772// We generally try to convert rotate-right -> rotate-left, this just5773// canonicalizes another case.5774CmpInst::Predicate PredUnused = Pred;5775if (match(&I, m_c_ICmp(PredUnused, m_Value(A),5776m_OneUse(m_Intrinsic<Intrinsic::fshr>(5777m_Deferred(A), m_Deferred(A), m_Value(B))))))5778return new ICmpInst(5779Pred, A,5780Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));57815782// Canonicalize:5783// icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst5784Constant *Cst;5785if (match(&I, m_c_ICmp(PredUnused,5786m_OneUse(m_Xor(m_Value(A), m_ImmConstant(Cst))),5787m_CombineAnd(m_Value(B), m_Unless(m_ImmConstant())))))5788return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);57895790{5791// (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)5792auto m_Matcher =5793m_CombineOr(m_CombineOr(m_c_Add(m_Value(B), m_Deferred(A)),5794m_c_Xor(m_Value(B), m_Deferred(A))),5795m_Sub(m_Value(B), m_Deferred(A)));5796std::optional<bool> IsZero = std::nullopt;5797if (match(&I, m_c_ICmp(PredUnused, m_OneUse(m_c_And(m_Value(A), m_Matcher)),5798m_Deferred(A))))5799IsZero = false;5800// (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)5801else if (match(&I,5802m_ICmp(PredUnused, m_OneUse(m_c_And(m_Value(A), m_Matcher)),5803m_Zero())))5804IsZero = true;58055806if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, /*Depth*/ 0, &I))5807// (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)5808// -> (icmp eq/ne (and X, P2), 0)5809// (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)5810// -> (icmp eq/ne (and X, P2), P2)5811return new ICmpInst(Pred, Builder.CreateAnd(B, A),5812*IsZero ? A5813: ConstantInt::getNullValue(A->getType()));5814}58155816return nullptr;5817}58185819Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {5820ICmpInst::Predicate Pred = ICmp.getPredicate();5821Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);58225823// Try to canonicalize trunc + compare-to-constant into a mask + cmp.5824// The trunc masks high bits while the compare may effectively mask low bits.5825Value *X;5826const APInt *C;5827if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))5828return nullptr;58295830// This matches patterns corresponding to tests of the signbit as well as:5831// (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?)5832// (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?)5833APInt Mask;5834if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) {5835Value *And = Builder.CreateAnd(X, Mask);5836Constant *Zero = ConstantInt::getNullValue(X->getType());5837return new ICmpInst(Pred, And, Zero);5838}58395840unsigned SrcBits = X->getType()->getScalarSizeInBits();5841if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) {5842// If C is a negative power-of-2 (high-bit mask):5843// (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?)5844Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits));5845Value *And = Builder.CreateAnd(X, MaskC);5846return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC);5847}58485849if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) {5850// If C is not-of-power-of-2 (one clear bit):5851// (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?)5852Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits));5853Value *And = Builder.CreateAnd(X, MaskC);5854return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC);5855}58565857if (auto *II = dyn_cast<IntrinsicInst>(X)) {5858if (II->getIntrinsicID() == Intrinsic::cttz ||5859II->getIntrinsicID() == Intrinsic::ctlz) {5860unsigned MaxRet = SrcBits;5861// If the "is_zero_poison" argument is set, then we know at least5862// one bit is set in the input, so the result is always at least one5863// less than the full bitwidth of that input.5864if (match(II->getArgOperand(1), m_One()))5865MaxRet--;58665867// Make sure the destination is wide enough to hold the largest output of5868// the intrinsic.5869if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())5870if (Instruction *I =5871foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))5872return I;5873}5874}58755876return nullptr;5877}58785879Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {5880assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");5881auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));5882Value *X;5883if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))5884return nullptr;58855886bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;5887bool IsSignedCmp = ICmp.isSigned();58885889// icmp Pred (ext X), (ext Y)5890Value *Y;5891if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {5892bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));5893bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));58945895if (IsZext0 != IsZext1) {5896// If X and Y and both i15897// (icmp eq/ne (zext X) (sext Y))5898// eq -> (icmp eq (or X, Y), 0)5899// ne -> (icmp ne (or X, Y), 0)5900if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&5901Y->getType()->isIntOrIntVectorTy(1))5902return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),5903Constant::getNullValue(X->getType()));59045905// If we have mismatched casts and zext has the nneg flag, we can5906// treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.59075908auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));5909auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));59105911bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();5912bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();59135914if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))5915IsSignedExt = true;5916else5917return nullptr;5918}59195920// Not an extension from the same type?5921Type *XTy = X->getType(), *YTy = Y->getType();5922if (XTy != YTy) {5923// One of the casts must have one use because we are creating a new cast.5924if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())5925return nullptr;5926// Extend the narrower operand to the type of the wider operand.5927CastInst::CastOps CastOpcode =5928IsSignedExt ? Instruction::SExt : Instruction::ZExt;5929if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())5930X = Builder.CreateCast(CastOpcode, X, YTy);5931else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())5932Y = Builder.CreateCast(CastOpcode, Y, XTy);5933else5934return nullptr;5935}59365937// (zext X) == (zext Y) --> X == Y5938// (sext X) == (sext Y) --> X == Y5939if (ICmp.isEquality())5940return new ICmpInst(ICmp.getPredicate(), X, Y);59415942// A signed comparison of sign extended values simplifies into a5943// signed comparison.5944if (IsSignedCmp && IsSignedExt)5945return new ICmpInst(ICmp.getPredicate(), X, Y);59465947// The other three cases all fold into an unsigned comparison.5948return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);5949}59505951// Below here, we are only folding a compare with constant.5952auto *C = dyn_cast<Constant>(ICmp.getOperand(1));5953if (!C)5954return nullptr;59555956// If a lossless truncate is possible...5957Type *SrcTy = CastOp0->getSrcTy();5958Constant *Res = getLosslessTrunc(C, SrcTy, CastOp0->getOpcode());5959if (Res) {5960if (ICmp.isEquality())5961return new ICmpInst(ICmp.getPredicate(), X, Res);59625963// A signed comparison of sign extended values simplifies into a5964// signed comparison.5965if (IsSignedExt && IsSignedCmp)5966return new ICmpInst(ICmp.getPredicate(), X, Res);59675968// The other three cases all fold into an unsigned comparison.5969return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);5970}59715972// The re-extended constant changed, partly changed (in the case of a vector),5973// or could not be determined to be equal (in the case of a constant5974// expression), so the constant cannot be represented in the shorter type.5975// All the cases that fold to true or false will have already been handled5976// by simplifyICmpInst, so only deal with the tricky case.5977if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))5978return nullptr;59795980// Is source op positive?5981// icmp ult (sext X), C --> icmp sgt X, -15982if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)5983return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));59845985// Is source op negative?5986// icmp ugt (sext X), C --> icmp slt X, 05987assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");5988return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));5989}59905991/// Handle icmp (cast x), (cast or constant).5992Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {5993// If any operand of ICmp is a inttoptr roundtrip cast then remove it as5994// icmp compares only pointer's value.5995// icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.5996Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));5997Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));5998if (SimplifiedOp0 || SimplifiedOp1)5999return new ICmpInst(ICmp.getPredicate(),6000SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),6001SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));60026003auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));6004if (!CastOp0)6005return nullptr;6006if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))6007return nullptr;60086009Value *Op0Src = CastOp0->getOperand(0);6010Type *SrcTy = CastOp0->getSrcTy();6011Type *DestTy = CastOp0->getDestTy();60126013// Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the6014// integer type is the same size as the pointer type.6015auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {6016if (isa<VectorType>(SrcTy)) {6017SrcTy = cast<VectorType>(SrcTy)->getElementType();6018DestTy = cast<VectorType>(DestTy)->getElementType();6019}6020return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();6021};6022if (CastOp0->getOpcode() == Instruction::PtrToInt &&6023CompatibleSizes(SrcTy, DestTy)) {6024Value *NewOp1 = nullptr;6025if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {6026Value *PtrSrc = PtrToIntOp1->getOperand(0);6027if (PtrSrc->getType() == Op0Src->getType())6028NewOp1 = PtrToIntOp1->getOperand(0);6029} else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {6030NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);6031}60326033if (NewOp1)6034return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);6035}60366037if (Instruction *R = foldICmpWithTrunc(ICmp))6038return R;60396040return foldICmpWithZextOrSext(ICmp);6041}60426043static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned) {6044switch (BinaryOp) {6045default:6046llvm_unreachable("Unsupported binary op");6047case Instruction::Add:6048case Instruction::Sub:6049return match(RHS, m_Zero());6050case Instruction::Mul:6051return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&6052match(RHS, m_One());6053}6054}60556056OverflowResult6057InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,6058bool IsSigned, Value *LHS, Value *RHS,6059Instruction *CxtI) const {6060switch (BinaryOp) {6061default:6062llvm_unreachable("Unsupported binary op");6063case Instruction::Add:6064if (IsSigned)6065return computeOverflowForSignedAdd(LHS, RHS, CxtI);6066else6067return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);6068case Instruction::Sub:6069if (IsSigned)6070return computeOverflowForSignedSub(LHS, RHS, CxtI);6071else6072return computeOverflowForUnsignedSub(LHS, RHS, CxtI);6073case Instruction::Mul:6074if (IsSigned)6075return computeOverflowForSignedMul(LHS, RHS, CxtI);6076else6077return computeOverflowForUnsignedMul(LHS, RHS, CxtI);6078}6079}60806081bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,6082bool IsSigned, Value *LHS,6083Value *RHS, Instruction &OrigI,6084Value *&Result,6085Constant *&Overflow) {6086if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))6087std::swap(LHS, RHS);60886089// If the overflow check was an add followed by a compare, the insertion point6090// may be pointing to the compare. We want to insert the new instructions6091// before the add in case there are uses of the add between the add and the6092// compare.6093Builder.SetInsertPoint(&OrigI);60946095Type *OverflowTy = Type::getInt1Ty(LHS->getContext());6096if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))6097OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());60986099if (isNeutralValue(BinaryOp, RHS, IsSigned)) {6100Result = LHS;6101Overflow = ConstantInt::getFalse(OverflowTy);6102return true;6103}61046105switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {6106case OverflowResult::MayOverflow:6107return false;6108case OverflowResult::AlwaysOverflowsLow:6109case OverflowResult::AlwaysOverflowsHigh:6110Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);6111Result->takeName(&OrigI);6112Overflow = ConstantInt::getTrue(OverflowTy);6113return true;6114case OverflowResult::NeverOverflows:6115Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);6116Result->takeName(&OrigI);6117Overflow = ConstantInt::getFalse(OverflowTy);6118if (auto *Inst = dyn_cast<Instruction>(Result)) {6119if (IsSigned)6120Inst->setHasNoSignedWrap();6121else6122Inst->setHasNoUnsignedWrap();6123}6124return true;6125}61266127llvm_unreachable("Unexpected overflow result");6128}61296130/// Recognize and process idiom involving test for multiplication6131/// overflow.6132///6133/// The caller has matched a pattern of the form:6134/// I = cmp u (mul(zext A, zext B), V6135/// The function checks if this is a test for overflow and if so replaces6136/// multiplication with call to 'mul.with.overflow' intrinsic.6137///6138/// \param I Compare instruction.6139/// \param MulVal Result of 'mult' instruction. It is one of the arguments of6140/// the compare instruction. Must be of integer type.6141/// \param OtherVal The other argument of compare instruction.6142/// \returns Instruction which must replace the compare instruction, NULL if no6143/// replacement required.6144static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,6145const APInt *OtherVal,6146InstCombinerImpl &IC) {6147// Don't bother doing this transformation for pointers, don't do it for6148// vectors.6149if (!isa<IntegerType>(MulVal->getType()))6150return nullptr;61516152auto *MulInstr = dyn_cast<Instruction>(MulVal);6153if (!MulInstr)6154return nullptr;6155assert(MulInstr->getOpcode() == Instruction::Mul);61566157auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),6158*RHS = cast<ZExtInst>(MulInstr->getOperand(1));6159assert(LHS->getOpcode() == Instruction::ZExt);6160assert(RHS->getOpcode() == Instruction::ZExt);6161Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);61626163// Calculate type and width of the result produced by mul.with.overflow.6164Type *TyA = A->getType(), *TyB = B->getType();6165unsigned WidthA = TyA->getPrimitiveSizeInBits(),6166WidthB = TyB->getPrimitiveSizeInBits();6167unsigned MulWidth;6168Type *MulType;6169if (WidthB > WidthA) {6170MulWidth = WidthB;6171MulType = TyB;6172} else {6173MulWidth = WidthA;6174MulType = TyA;6175}61766177// In order to replace the original mul with a narrower mul.with.overflow,6178// all uses must ignore upper bits of the product. The number of used low6179// bits must be not greater than the width of mul.with.overflow.6180if (MulVal->hasNUsesOrMore(2))6181for (User *U : MulVal->users()) {6182if (U == &I)6183continue;6184if (TruncInst *TI = dyn_cast<TruncInst>(U)) {6185// Check if truncation ignores bits above MulWidth.6186unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();6187if (TruncWidth > MulWidth)6188return nullptr;6189} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {6190// Check if AND ignores bits above MulWidth.6191if (BO->getOpcode() != Instruction::And)6192return nullptr;6193if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {6194const APInt &CVal = CI->getValue();6195if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)6196return nullptr;6197} else {6198// In this case we could have the operand of the binary operation6199// being defined in another block, and performing the replacement6200// could break the dominance relation.6201return nullptr;6202}6203} else {6204// Other uses prohibit this transformation.6205return nullptr;6206}6207}62086209// Recognize patterns6210switch (I.getPredicate()) {6211case ICmpInst::ICMP_UGT: {6212// Recognize pattern:6213// mulval = mul(zext A, zext B)6214// cmp ugt mulval, max6215APInt MaxVal = APInt::getMaxValue(MulWidth);6216MaxVal = MaxVal.zext(OtherVal->getBitWidth());6217if (MaxVal.eq(*OtherVal))6218break; // Recognized6219return nullptr;6220}62216222case ICmpInst::ICMP_ULT: {6223// Recognize pattern:6224// mulval = mul(zext A, zext B)6225// cmp ule mulval, max + 16226APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);6227if (MaxVal.eq(*OtherVal))6228break; // Recognized6229return nullptr;6230}62316232default:6233return nullptr;6234}62356236InstCombiner::BuilderTy &Builder = IC.Builder;6237Builder.SetInsertPoint(MulInstr);62386239// Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)6240Value *MulA = A, *MulB = B;6241if (WidthA < MulWidth)6242MulA = Builder.CreateZExt(A, MulType);6243if (WidthB < MulWidth)6244MulB = Builder.CreateZExt(B, MulType);6245Function *F = Intrinsic::getDeclaration(6246I.getModule(), Intrinsic::umul_with_overflow, MulType);6247CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");6248IC.addToWorklist(MulInstr);62496250// If there are uses of mul result other than the comparison, we know that6251// they are truncation or binary AND. Change them to use result of6252// mul.with.overflow and adjust properly mask/size.6253if (MulVal->hasNUsesOrMore(2)) {6254Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");6255for (User *U : make_early_inc_range(MulVal->users())) {6256if (U == &I)6257continue;6258if (TruncInst *TI = dyn_cast<TruncInst>(U)) {6259if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)6260IC.replaceInstUsesWith(*TI, Mul);6261else6262TI->setOperand(0, Mul);6263} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {6264assert(BO->getOpcode() == Instruction::And);6265// Replace (mul & mask) --> zext (mul.with.overflow & short_mask)6266ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));6267APInt ShortMask = CI->getValue().trunc(MulWidth);6268Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);6269Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());6270IC.replaceInstUsesWith(*BO, Zext);6271} else {6272llvm_unreachable("Unexpected Binary operation");6273}6274IC.addToWorklist(cast<Instruction>(U));6275}6276}62776278// The original icmp gets replaced with the overflow value, maybe inverted6279// depending on predicate.6280if (I.getPredicate() == ICmpInst::ICMP_ULT) {6281Value *Res = Builder.CreateExtractValue(Call, 1);6282return BinaryOperator::CreateNot(Res);6283}62846285return ExtractValueInst::Create(Call, 1);6286}62876288/// When performing a comparison against a constant, it is possible that not all6289/// the bits in the LHS are demanded. This helper method computes the mask that6290/// IS demanded.6291static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {6292const APInt *RHS;6293if (!match(I.getOperand(1), m_APInt(RHS)))6294return APInt::getAllOnes(BitWidth);62956296// If this is a normal comparison, it demands all bits. If it is a sign bit6297// comparison, it only demands the sign bit.6298bool UnusedBit;6299if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))6300return APInt::getSignMask(BitWidth);63016302switch (I.getPredicate()) {6303// For a UGT comparison, we don't care about any bits that6304// correspond to the trailing ones of the comparand. The value of these6305// bits doesn't impact the outcome of the comparison, because any value6306// greater than the RHS must differ in a bit higher than these due to carry.6307case ICmpInst::ICMP_UGT:6308return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());63096310// Similarly, for a ULT comparison, we don't care about the trailing zeros.6311// Any value less than the RHS must differ in a higher bit because of carries.6312case ICmpInst::ICMP_ULT:6313return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());63146315default:6316return APInt::getAllOnes(BitWidth);6317}6318}63196320/// Check that one use is in the same block as the definition and all6321/// other uses are in blocks dominated by a given block.6322///6323/// \param DI Definition6324/// \param UI Use6325/// \param DB Block that must dominate all uses of \p DI outside6326/// the parent block6327/// \return true when \p UI is the only use of \p DI in the parent block6328/// and all other uses of \p DI are in blocks dominated by \p DB.6329///6330bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,6331const Instruction *UI,6332const BasicBlock *DB) const {6333assert(DI && UI && "Instruction not defined\n");6334// Ignore incomplete definitions.6335if (!DI->getParent())6336return false;6337// DI and UI must be in the same block.6338if (DI->getParent() != UI->getParent())6339return false;6340// Protect from self-referencing blocks.6341if (DI->getParent() == DB)6342return false;6343for (const User *U : DI->users()) {6344auto *Usr = cast<Instruction>(U);6345if (Usr != UI && !DT.dominates(DB, Usr->getParent()))6346return false;6347}6348return true;6349}63506351/// Return true when the instruction sequence within a block is select-cmp-br.6352static bool isChainSelectCmpBranch(const SelectInst *SI) {6353const BasicBlock *BB = SI->getParent();6354if (!BB)6355return false;6356auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());6357if (!BI || BI->getNumSuccessors() != 2)6358return false;6359auto *IC = dyn_cast<ICmpInst>(BI->getCondition());6360if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))6361return false;6362return true;6363}63646365/// True when a select result is replaced by one of its operands6366/// in select-icmp sequence. This will eventually result in the elimination6367/// of the select.6368///6369/// \param SI Select instruction6370/// \param Icmp Compare instruction6371/// \param SIOpd Operand that replaces the select6372///6373/// Notes:6374/// - The replacement is global and requires dominator information6375/// - The caller is responsible for the actual replacement6376///6377/// Example:6378///6379/// entry:6380/// %4 = select i1 %3, %C* %0, %C* null6381/// %5 = icmp eq %C* %4, null6382/// br i1 %5, label %9, label %76383/// ...6384/// ; <label>:7 ; preds = %entry6385/// %8 = getelementptr inbounds %C* %4, i64 0, i32 06386/// ...6387///6388/// can be transformed to6389///6390/// %5 = icmp eq %C* %0, null6391/// %6 = select i1 %3, i1 %5, i1 true6392/// br i1 %6, label %9, label %76393/// ...6394/// ; <label>:7 ; preds = %entry6395/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!6396///6397/// Similar when the first operand of the select is a constant or/and6398/// the compare is for not equal rather than equal.6399///6400/// NOTE: The function is only called when the select and compare constants6401/// are equal, the optimization can work only for EQ predicates. This is not a6402/// major restriction since a NE compare should be 'normalized' to an equal6403/// compare, which usually happens in the combiner and test case6404/// select-cmp-br.ll checks for it.6405bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,6406const ICmpInst *Icmp,6407const unsigned SIOpd) {6408assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");6409if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {6410BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);6411// The check for the single predecessor is not the best that can be6412// done. But it protects efficiently against cases like when SI's6413// home block has two successors, Succ and Succ1, and Succ1 predecessor6414// of Succ. Then SI can't be replaced by SIOpd because the use that gets6415// replaced can be reached on either path. So the uniqueness check6416// guarantees that the path all uses of SI (outside SI's parent) are on6417// is disjoint from all other paths out of SI. But that information6418// is more expensive to compute, and the trade-off here is in favor6419// of compile-time. It should also be noticed that we check for a single6420// predecessor and not only uniqueness. This to handle the situation when6421// Succ and Succ1 points to the same basic block.6422if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {6423NumSel++;6424SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());6425return true;6426}6427}6428return false;6429}64306431/// Try to fold the comparison based on range information we can get by checking6432/// whether bits are known to be zero or one in the inputs.6433Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {6434Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);6435Type *Ty = Op0->getType();6436ICmpInst::Predicate Pred = I.getPredicate();64376438// Get scalar or pointer size.6439unsigned BitWidth = Ty->isIntOrIntVectorTy()6440? Ty->getScalarSizeInBits()6441: DL.getPointerTypeSizeInBits(Ty->getScalarType());64426443if (!BitWidth)6444return nullptr;64456446KnownBits Op0Known(BitWidth);6447KnownBits Op1Known(BitWidth);64486449{6450// Don't use dominating conditions when folding icmp using known bits. This6451// may convert signed into unsigned predicates in ways that other passes6452// (especially IndVarSimplify) may not be able to reliably undo.6453SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);6454if (SimplifyDemandedBits(&I, 0, getDemandedBitsLHSMask(I, BitWidth),6455Op0Known, /*Depth=*/0, Q))6456return &I;64576458if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known,6459/*Depth=*/0, Q))6460return &I;6461}64626463// Given the known and unknown bits, compute a range that the LHS could be6464// in. Compute the Min, Max and RHS values based on the known bits. For the6465// EQ and NE we use unsigned values.6466APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);6467APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);6468if (I.isSigned()) {6469Op0Min = Op0Known.getSignedMinValue();6470Op0Max = Op0Known.getSignedMaxValue();6471Op1Min = Op1Known.getSignedMinValue();6472Op1Max = Op1Known.getSignedMaxValue();6473} else {6474Op0Min = Op0Known.getMinValue();6475Op0Max = Op0Known.getMaxValue();6476Op1Min = Op1Known.getMinValue();6477Op1Max = Op1Known.getMaxValue();6478}64796480// If Min and Max are known to be the same, then SimplifyDemandedBits figured6481// out that the LHS or RHS is a constant. Constant fold this now, so that6482// code below can assume that Min != Max.6483if (!isa<Constant>(Op0) && Op0Min == Op0Max)6484return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);6485if (!isa<Constant>(Op1) && Op1Min == Op1Max)6486return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));64876488// Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a6489// min/max canonical compare with some other compare. That could lead to6490// conflict with select canonicalization and infinite looping.6491// FIXME: This constraint may go away if min/max intrinsics are canonical.6492auto isMinMaxCmp = [&](Instruction &Cmp) {6493if (!Cmp.hasOneUse())6494return false;6495Value *A, *B;6496SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;6497if (!SelectPatternResult::isMinOrMax(SPF))6498return false;6499return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||6500match(Op1, m_MaxOrMin(m_Value(), m_Value()));6501};6502if (!isMinMaxCmp(I)) {6503switch (Pred) {6504default:6505break;6506case ICmpInst::ICMP_ULT: {6507if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)6508return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);6509const APInt *CmpC;6510if (match(Op1, m_APInt(CmpC))) {6511// A <u C -> A == C-1 if min(A)+1 == C6512if (*CmpC == Op0Min + 1)6513return new ICmpInst(ICmpInst::ICMP_EQ, Op0,6514ConstantInt::get(Op1->getType(), *CmpC - 1));6515// X <u C --> X == 0, if the number of zero bits in the bottom of X6516// exceeds the log2 of C.6517if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())6518return new ICmpInst(ICmpInst::ICMP_EQ, Op0,6519Constant::getNullValue(Op1->getType()));6520}6521break;6522}6523case ICmpInst::ICMP_UGT: {6524if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)6525return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);6526const APInt *CmpC;6527if (match(Op1, m_APInt(CmpC))) {6528// A >u C -> A == C+1 if max(a)-1 == C6529if (*CmpC == Op0Max - 1)6530return new ICmpInst(ICmpInst::ICMP_EQ, Op0,6531ConstantInt::get(Op1->getType(), *CmpC + 1));6532// X >u C --> X != 0, if the number of zero bits in the bottom of X6533// exceeds the log2 of C.6534if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())6535return new ICmpInst(ICmpInst::ICMP_NE, Op0,6536Constant::getNullValue(Op1->getType()));6537}6538break;6539}6540case ICmpInst::ICMP_SLT: {6541if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)6542return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);6543const APInt *CmpC;6544if (match(Op1, m_APInt(CmpC))) {6545if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C6546return new ICmpInst(ICmpInst::ICMP_EQ, Op0,6547ConstantInt::get(Op1->getType(), *CmpC - 1));6548}6549break;6550}6551case ICmpInst::ICMP_SGT: {6552if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)6553return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);6554const APInt *CmpC;6555if (match(Op1, m_APInt(CmpC))) {6556if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C6557return new ICmpInst(ICmpInst::ICMP_EQ, Op0,6558ConstantInt::get(Op1->getType(), *CmpC + 1));6559}6560break;6561}6562}6563}65646565// Based on the range information we know about the LHS, see if we can6566// simplify this comparison. For example, (x&4) < 8 is always true.6567switch (Pred) {6568default:6569llvm_unreachable("Unknown icmp opcode!");6570case ICmpInst::ICMP_EQ:6571case ICmpInst::ICMP_NE: {6572if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))6573return replaceInstUsesWith(6574I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE));65756576// If all bits are known zero except for one, then we know at most one bit6577// is set. If the comparison is against zero, then this is a check to see if6578// *that* bit is set.6579APInt Op0KnownZeroInverted = ~Op0Known.Zero;6580if (Op1Known.isZero()) {6581// If the LHS is an AND with the same constant, look through it.6582Value *LHS = nullptr;6583const APInt *LHSC;6584if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||6585*LHSC != Op0KnownZeroInverted)6586LHS = Op0;65876588Value *X;6589const APInt *C1;6590if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {6591Type *XTy = X->getType();6592unsigned Log2C1 = C1->countr_zero();6593APInt C2 = Op0KnownZeroInverted;6594APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;6595if (C2Pow2.isPowerOf2()) {6596// iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):6597// ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))6598// ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))6599unsigned Log2C2 = C2Pow2.countr_zero();6600auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);6601auto NewPred =6602Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;6603return new ICmpInst(NewPred, X, CmpC);6604}6605}6606}66076608// Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.6609if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&6610(Op0Known & Op1Known) == Op0Known)6611return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,6612ConstantInt::getNullValue(Op1->getType()));6613break;6614}6615case ICmpInst::ICMP_ULT: {6616if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)6617return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6618if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)6619return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6620break;6621}6622case ICmpInst::ICMP_UGT: {6623if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)6624return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6625if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)6626return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6627break;6628}6629case ICmpInst::ICMP_SLT: {6630if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)6631return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6632if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)6633return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6634break;6635}6636case ICmpInst::ICMP_SGT: {6637if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)6638return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6639if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)6640return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6641break;6642}6643case ICmpInst::ICMP_SGE:6644assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");6645if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)6646return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6647if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)6648return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6649if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)6650return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);6651break;6652case ICmpInst::ICMP_SLE:6653assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");6654if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)6655return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6656if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)6657return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6658if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)6659return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);6660break;6661case ICmpInst::ICMP_UGE:6662assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");6663if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)6664return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6665if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)6666return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6667if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)6668return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);6669break;6670case ICmpInst::ICMP_ULE:6671assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");6672if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)6673return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));6674if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)6675return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));6676if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)6677return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);6678break;6679}66806681// Turn a signed comparison into an unsigned one if both operands are known to6682// have the same sign.6683if (I.isSigned() &&6684((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||6685(Op0Known.One.isNegative() && Op1Known.One.isNegative())))6686return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);66876688return nullptr;6689}66906691/// If one operand of an icmp is effectively a bool (value range of {0,1}),6692/// then try to reduce patterns based on that limit.6693Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {6694Value *X, *Y;6695ICmpInst::Predicate Pred;66966697// X must be 0 and bool must be true for "ULT":6698// X <u (zext i1 Y) --> (X == 0) & Y6699if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&6700Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)6701return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);67026703// X must be 0 or bool must be true for "ULE":6704// X <=u (sext i1 Y) --> (X == 0) | Y6705if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&6706Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)6707return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);67086709// icmp eq/ne X, (zext/sext (icmp eq/ne X, C))6710ICmpInst::Predicate Pred1, Pred2;6711const APInt *C;6712Instruction *ExtI;6713if (match(&I, m_c_ICmp(Pred1, m_Value(X),6714m_CombineAnd(m_Instruction(ExtI),6715m_ZExtOrSExt(m_ICmp(Pred2, m_Deferred(X),6716m_APInt(C)))))) &&6717ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {6718bool IsSExt = ExtI->getOpcode() == Instruction::SExt;6719bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();6720auto CreateRangeCheck = [&] {6721Value *CmpV1 =6722Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));6723Value *CmpV2 = Builder.CreateICmp(6724Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));6725return BinaryOperator::Create(6726Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,6727CmpV1, CmpV2);6728};6729if (C->isZero()) {6730if (Pred2 == ICmpInst::ICMP_EQ) {6731// icmp eq X, (zext/sext (icmp eq X, 0)) --> false6732// icmp ne X, (zext/sext (icmp eq X, 0)) --> true6733return replaceInstUsesWith(6734I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));6735} else if (!IsSExt || HasOneUse) {6736// icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 16737// icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 16738// icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -16739// icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X == -16740return CreateRangeCheck();6741}6742} else if (IsSExt ? C->isAllOnes() : C->isOne()) {6743if (Pred2 == ICmpInst::ICMP_NE) {6744// icmp eq X, (zext (icmp ne X, 1)) --> false6745// icmp ne X, (zext (icmp ne X, 1)) --> true6746// icmp eq X, (sext (icmp ne X, -1)) --> false6747// icmp ne X, (sext (icmp ne X, -1)) --> true6748return replaceInstUsesWith(6749I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));6750} else if (!IsSExt || HasOneUse) {6751// icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 16752// icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 16753// icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -16754// icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -16755return CreateRangeCheck();6756}6757} else {6758// when C != 0 && C != 1:6759// icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 06760// icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 16761// icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 06762// icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 16763// when C != 0 && C != -1:6764// icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 06765// icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -16766// icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 06767// icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -16768return ICmpInst::Create(6769Instruction::ICmp, Pred1, X,6770ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE6771? (IsSExt ? -1 : 1)6772: 0));6773}6774}67756776return nullptr;6777}67786779std::optional<std::pair<CmpInst::Predicate, Constant *>>6780InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,6781Constant *C) {6782assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&6783"Only for relational integer predicates.");67846785Type *Type = C->getType();6786bool IsSigned = ICmpInst::isSigned(Pred);67876788CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);6789bool WillIncrement =6790UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;67916792// Check if the constant operand can be safely incremented/decremented6793// without overflowing/underflowing.6794auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {6795return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);6796};67976798Constant *SafeReplacementConstant = nullptr;6799if (auto *CI = dyn_cast<ConstantInt>(C)) {6800// Bail out if the constant can't be safely incremented/decremented.6801if (!ConstantIsOk(CI))6802return std::nullopt;6803} else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {6804unsigned NumElts = FVTy->getNumElements();6805for (unsigned i = 0; i != NumElts; ++i) {6806Constant *Elt = C->getAggregateElement(i);6807if (!Elt)6808return std::nullopt;68096810if (isa<UndefValue>(Elt))6811continue;68126813// Bail out if we can't determine if this constant is min/max or if we6814// know that this constant is min/max.6815auto *CI = dyn_cast<ConstantInt>(Elt);6816if (!CI || !ConstantIsOk(CI))6817return std::nullopt;68186819if (!SafeReplacementConstant)6820SafeReplacementConstant = CI;6821}6822} else if (isa<VectorType>(C->getType())) {6823// Handle scalable splat6824Value *SplatC = C->getSplatValue();6825auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);6826// Bail out if the constant can't be safely incremented/decremented.6827if (!CI || !ConstantIsOk(CI))6828return std::nullopt;6829} else {6830// ConstantExpr?6831return std::nullopt;6832}68336834// It may not be safe to change a compare predicate in the presence of6835// undefined elements, so replace those elements with the first safe constant6836// that we found.6837// TODO: in case of poison, it is safe; let's replace undefs only.6838if (C->containsUndefOrPoisonElement()) {6839assert(SafeReplacementConstant && "Replacement constant not set");6840C = Constant::replaceUndefsWith(C, SafeReplacementConstant);6841}68426843CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);68446845// Increment or decrement the constant.6846Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);6847Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);68486849return std::make_pair(NewPred, NewC);6850}68516852/// If we have an icmp le or icmp ge instruction with a constant operand, turn6853/// it into the appropriate icmp lt or icmp gt instruction. This transform6854/// allows them to be folded in visitICmpInst.6855static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {6856ICmpInst::Predicate Pred = I.getPredicate();6857if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||6858InstCombiner::isCanonicalPredicate(Pred))6859return nullptr;68606861Value *Op0 = I.getOperand(0);6862Value *Op1 = I.getOperand(1);6863auto *Op1C = dyn_cast<Constant>(Op1);6864if (!Op1C)6865return nullptr;68666867auto FlippedStrictness =6868InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C);6869if (!FlippedStrictness)6870return nullptr;68716872return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);6873}68746875/// If we have a comparison with a non-canonical predicate, if we can update6876/// all the users, invert the predicate and adjust all the users.6877CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {6878// Is the predicate already canonical?6879CmpInst::Predicate Pred = I.getPredicate();6880if (InstCombiner::isCanonicalPredicate(Pred))6881return nullptr;68826883// Can all users be adjusted to predicate inversion?6884if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))6885return nullptr;68866887// Ok, we can canonicalize comparison!6888// Let's first invert the comparison's predicate.6889I.setPredicate(CmpInst::getInversePredicate(Pred));6890I.setName(I.getName() + ".not");68916892// And, adapt users.6893freelyInvertAllUsersOf(&I);68946895return &I;6896}68976898/// Integer compare with boolean values can always be turned into bitwise ops.6899static Instruction *canonicalizeICmpBool(ICmpInst &I,6900InstCombiner::BuilderTy &Builder) {6901Value *A = I.getOperand(0), *B = I.getOperand(1);6902assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");69036904// A boolean compared to true/false can be simplified to Op0/true/false in6905// 14 out of the 20 (10 predicates * 2 constants) possible combinations.6906// Cases not handled by InstSimplify are always 'not' of Op0.6907if (match(B, m_Zero())) {6908switch (I.getPredicate()) {6909case CmpInst::ICMP_EQ: // A == 0 -> !A6910case CmpInst::ICMP_ULE: // A <=u 0 -> !A6911case CmpInst::ICMP_SGE: // A >=s 0 -> !A6912return BinaryOperator::CreateNot(A);6913default:6914llvm_unreachable("ICmp i1 X, C not simplified as expected.");6915}6916} else if (match(B, m_One())) {6917switch (I.getPredicate()) {6918case CmpInst::ICMP_NE: // A != 1 -> !A6919case CmpInst::ICMP_ULT: // A <u 1 -> !A6920case CmpInst::ICMP_SGT: // A >s -1 -> !A6921return BinaryOperator::CreateNot(A);6922default:6923llvm_unreachable("ICmp i1 X, C not simplified as expected.");6924}6925}69266927switch (I.getPredicate()) {6928default:6929llvm_unreachable("Invalid icmp instruction!");6930case ICmpInst::ICMP_EQ:6931// icmp eq i1 A, B -> ~(A ^ B)6932return BinaryOperator::CreateNot(Builder.CreateXor(A, B));69336934case ICmpInst::ICMP_NE:6935// icmp ne i1 A, B -> A ^ B6936return BinaryOperator::CreateXor(A, B);69376938case ICmpInst::ICMP_UGT:6939// icmp ugt -> icmp ult6940std::swap(A, B);6941[[fallthrough]];6942case ICmpInst::ICMP_ULT:6943// icmp ult i1 A, B -> ~A & B6944return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);69456946case ICmpInst::ICMP_SGT:6947// icmp sgt -> icmp slt6948std::swap(A, B);6949[[fallthrough]];6950case ICmpInst::ICMP_SLT:6951// icmp slt i1 A, B -> A & ~B6952return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);69536954case ICmpInst::ICMP_UGE:6955// icmp uge -> icmp ule6956std::swap(A, B);6957[[fallthrough]];6958case ICmpInst::ICMP_ULE:6959// icmp ule i1 A, B -> ~A | B6960return BinaryOperator::CreateOr(Builder.CreateNot(A), B);69616962case ICmpInst::ICMP_SGE:6963// icmp sge -> icmp sle6964std::swap(A, B);6965[[fallthrough]];6966case ICmpInst::ICMP_SLE:6967// icmp sle i1 A, B -> A | ~B6968return BinaryOperator::CreateOr(Builder.CreateNot(B), A);6969}6970}69716972// Transform pattern like:6973// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X6974// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X6975// Into:6976// (X l>> Y) != 06977// (X l>> Y) == 06978static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,6979InstCombiner::BuilderTy &Builder) {6980ICmpInst::Predicate Pred, NewPred;6981Value *X, *Y;6982if (match(&Cmp,6983m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {6984switch (Pred) {6985case ICmpInst::ICMP_ULE:6986NewPred = ICmpInst::ICMP_NE;6987break;6988case ICmpInst::ICMP_UGT:6989NewPred = ICmpInst::ICMP_EQ;6990break;6991default:6992return nullptr;6993}6994} else if (match(&Cmp, m_c_ICmp(Pred,6995m_OneUse(m_CombineOr(6996m_Not(m_Shl(m_AllOnes(), m_Value(Y))),6997m_Add(m_Shl(m_One(), m_Value(Y)),6998m_AllOnes()))),6999m_Value(X)))) {7000// The variant with 'add' is not canonical, (the variant with 'not' is)7001// we only get it because it has extra uses, and can't be canonicalized,70027003switch (Pred) {7004case ICmpInst::ICMP_ULT:7005NewPred = ICmpInst::ICMP_NE;7006break;7007case ICmpInst::ICMP_UGE:7008NewPred = ICmpInst::ICMP_EQ;7009break;7010default:7011return nullptr;7012}7013} else7014return nullptr;70157016Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");7017Constant *Zero = Constant::getNullValue(NewX->getType());7018return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);7019}70207021static Instruction *foldVectorCmp(CmpInst &Cmp,7022InstCombiner::BuilderTy &Builder) {7023const CmpInst::Predicate Pred = Cmp.getPredicate();7024Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);7025Value *V1, *V2;70267027auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {7028Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());7029if (auto *I = dyn_cast<Instruction>(V))7030I->copyIRFlags(&Cmp);7031Module *M = Cmp.getModule();7032Function *F =7033Intrinsic::getDeclaration(M, Intrinsic::vector_reverse, V->getType());7034return CallInst::Create(F, V);7035};70367037if (match(LHS, m_VecReverse(m_Value(V1)))) {7038// cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)7039if (match(RHS, m_VecReverse(m_Value(V2))) &&7040(LHS->hasOneUse() || RHS->hasOneUse()))7041return createCmpReverse(Pred, V1, V2);70427043// cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)7044if (LHS->hasOneUse() && isSplatValue(RHS))7045return createCmpReverse(Pred, V1, RHS);7046}7047// cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)7048else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))7049return createCmpReverse(Pred, LHS, V2);70507051ArrayRef<int> M;7052if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))7053return nullptr;70547055// If both arguments of the cmp are shuffles that use the same mask and7056// shuffle within a single vector, move the shuffle after the cmp:7057// cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M7058Type *V1Ty = V1->getType();7059if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&7060V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {7061Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);7062return new ShuffleVectorInst(NewCmp, M);7063}70647065// Try to canonicalize compare with splatted operand and splat constant.7066// TODO: We could generalize this for more than splats. See/use the code in7067// InstCombiner::foldVectorBinop().7068Constant *C;7069if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))7070return nullptr;70717072// Length-changing splats are ok, so adjust the constants as needed:7073// cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M7074Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);7075int MaskSplatIndex;7076if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {7077// We allow poison in matching, but this transform removes it for safety.7078// Demanded elements analysis should be able to recover some/all of that.7079C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),7080ScalarC);7081SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);7082Value *NewCmp = Builder.CreateCmp(Pred, V1, C);7083return new ShuffleVectorInst(NewCmp, NewM);7084}70857086return nullptr;7087}70887089// extract(uadd.with.overflow(A, B), 0) ult A7090// -> extract(uadd.with.overflow(A, B), 1)7091static Instruction *foldICmpOfUAddOv(ICmpInst &I) {7092CmpInst::Predicate Pred = I.getPredicate();7093Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);70947095Value *UAddOv;7096Value *A, *B;7097auto UAddOvResultPat = m_ExtractValue<0>(7098m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));7099if (match(Op0, UAddOvResultPat) &&7100((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||7101(Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&7102(match(A, m_One()) || match(B, m_One()))) ||7103(Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&7104(match(A, m_AllOnes()) || match(B, m_AllOnes())))))7105// extract(uadd.with.overflow(A, B), 0) < A7106// extract(uadd.with.overflow(A, 1), 0) == 07107// extract(uadd.with.overflow(A, -1), 0) != -17108UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();7109else if (match(Op1, UAddOvResultPat) &&7110Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B))7111// A > extract(uadd.with.overflow(A, B), 0)7112UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();7113else7114return nullptr;71157116return ExtractValueInst::Create(UAddOv, 1);7117}71187119static Instruction *foldICmpInvariantGroup(ICmpInst &I) {7120if (!I.getOperand(0)->getType()->isPointerTy() ||7121NullPointerIsDefined(7122I.getParent()->getParent(),7123I.getOperand(0)->getType()->getPointerAddressSpace())) {7124return nullptr;7125}7126Instruction *Op;7127if (match(I.getOperand(0), m_Instruction(Op)) &&7128match(I.getOperand(1), m_Zero()) &&7129Op->isLaunderOrStripInvariantGroup()) {7130return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),7131Op->getOperand(0), I.getOperand(1));7132}7133return nullptr;7134}71357136/// This function folds patterns produced by lowering of reduce idioms, such as7137/// llvm.vector.reduce.and which are lowered into instruction chains. This code7138/// attempts to generate fewer number of scalar comparisons instead of vector7139/// comparisons when possible.7140static Instruction *foldReductionIdiom(ICmpInst &I,7141InstCombiner::BuilderTy &Builder,7142const DataLayout &DL) {7143if (I.getType()->isVectorTy())7144return nullptr;7145ICmpInst::Predicate OuterPred, InnerPred;7146Value *LHS, *RHS;71477148// Match lowering of @llvm.vector.reduce.and. Turn7149/// %vec_ne = icmp ne <8 x i8> %lhs, %rhs7150/// %scalar_ne = bitcast <8 x i1> %vec_ne to i87151/// %res = icmp <pred> i8 %scalar_ne, 07152///7153/// into7154///7155/// %lhs.scalar = bitcast <8 x i8> %lhs to i647156/// %rhs.scalar = bitcast <8 x i8> %rhs to i647157/// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar7158///7159/// for <pred> in {ne, eq}.7160if (!match(&I, m_ICmp(OuterPred,7161m_OneUse(m_BitCast(m_OneUse(7162m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),7163m_Zero())))7164return nullptr;7165auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());7166if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())7167return nullptr;7168unsigned NumBits =7169LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();7170// TODO: Relax this to "not wider than max legal integer type"?7171if (!DL.isLegalInteger(NumBits))7172return nullptr;71737174if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {7175auto *ScalarTy = Builder.getIntNTy(NumBits);7176LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");7177RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");7178return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,7179I.getName());7180}71817182return nullptr;7183}71847185// This helper will be called with icmp operands in both orders.7186Instruction *InstCombinerImpl::foldICmpCommutative(ICmpInst::Predicate Pred,7187Value *Op0, Value *Op1,7188ICmpInst &CxtI) {7189// Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.7190if (auto *GEP = dyn_cast<GEPOperator>(Op0))7191if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))7192return NI;71937194if (auto *SI = dyn_cast<SelectInst>(Op0))7195if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))7196return NI;71977198if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0))7199if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))7200return Res;72017202{7203Value *X;7204const APInt *C;7205// icmp X+Cst, X7206if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)7207return foldICmpAddOpConst(X, *C, Pred);7208}72097210// abs(X) >= X --> true7211// abs(X) u<= X --> true7212// abs(X) < X --> false7213// abs(X) u> X --> false7214// abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`7215// abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`7216// abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`7217// abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`7218// abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`7219// abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`7220{7221Value *X;7222Constant *C;7223if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(X), m_Constant(C))) &&7224match(Op1, m_Specific(X))) {7225Value *NullValue = Constant::getNullValue(X->getType());7226Value *AllOnesValue = Constant::getAllOnesValue(X->getType());7227const APInt SMin =7228APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());7229bool IsIntMinPosion = C->isAllOnesValue();7230switch (Pred) {7231case CmpInst::ICMP_ULE:7232case CmpInst::ICMP_SGE:7233return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));7234case CmpInst::ICMP_UGT:7235case CmpInst::ICMP_SLT:7236return replaceInstUsesWith(CxtI, ConstantInt::getFalse(CxtI.getType()));7237case CmpInst::ICMP_UGE:7238case CmpInst::ICMP_SLE:7239case CmpInst::ICMP_EQ: {7240return replaceInstUsesWith(7241CxtI, IsIntMinPosion7242? Builder.CreateICmpSGT(X, AllOnesValue)7243: Builder.CreateICmpULT(7244X, ConstantInt::get(X->getType(), SMin + 1)));7245}7246case CmpInst::ICMP_ULT:7247case CmpInst::ICMP_SGT:7248case CmpInst::ICMP_NE: {7249return replaceInstUsesWith(7250CxtI, IsIntMinPosion7251? Builder.CreateICmpSLT(X, NullValue)7252: Builder.CreateICmpUGT(7253X, ConstantInt::get(X->getType(), SMin)));7254}7255default:7256llvm_unreachable("Invalid predicate!");7257}7258}7259}72607261const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);7262if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))7263return replaceInstUsesWith(CxtI, V);72647265// Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 17266auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };7267{7268if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {7269return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,7270Constant::getNullValue(Op1->getType()));7271}72727273if (!ICmpInst::isUnsigned(Pred) &&7274match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {7275return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,7276Constant::getNullValue(Op1->getType()));7277}7278}72797280// Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 07281auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };7282{7283if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {7284return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,7285Constant::getNullValue(Op1->getType()));7286}72877288if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&7289match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {7290return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,7291Constant::getNullValue(Op1->getType()));7292}7293}72947295return nullptr;7296}72977298Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {7299bool Changed = false;7300const SimplifyQuery Q = SQ.getWithInstruction(&I);7301Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);7302unsigned Op0Cplxity = getComplexity(Op0);7303unsigned Op1Cplxity = getComplexity(Op1);73047305/// Orders the operands of the compare so that they are listed from most7306/// complex to least complex. This puts constants before unary operators,7307/// before binary operators.7308if (Op0Cplxity < Op1Cplxity) {7309I.swapOperands();7310std::swap(Op0, Op1);7311Changed = true;7312}73137314if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))7315return replaceInstUsesWith(I, V);73167317// Comparing -val or val with non-zero is the same as just comparing val7318// ie, abs(val) != 0 -> val != 07319if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {7320Value *Cond, *SelectTrue, *SelectFalse;7321if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),7322m_Value(SelectFalse)))) {7323if (Value *V = dyn_castNegVal(SelectTrue)) {7324if (V == SelectFalse)7325return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);7326}7327else if (Value *V = dyn_castNegVal(SelectFalse)) {7328if (V == SelectTrue)7329return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);7330}7331}7332}73337334if (Op0->getType()->isIntOrIntVectorTy(1))7335if (Instruction *Res = canonicalizeICmpBool(I, Builder))7336return Res;73377338if (Instruction *Res = canonicalizeCmpWithConstant(I))7339return Res;73407341if (Instruction *Res = canonicalizeICmpPredicate(I))7342return Res;73437344if (Instruction *Res = foldICmpWithConstant(I))7345return Res;73467347if (Instruction *Res = foldICmpWithDominatingICmp(I))7348return Res;73497350if (Instruction *Res = foldICmpUsingBoolRange(I))7351return Res;73527353if (Instruction *Res = foldICmpUsingKnownBits(I))7354return Res;73557356if (Instruction *Res = foldICmpTruncWithTruncOrExt(I, Q))7357return Res;73587359// Test if the ICmpInst instruction is used exclusively by a select as7360// part of a minimum or maximum operation. If so, refrain from doing7361// any other folding. This helps out other analyses which understand7362// non-obfuscated minimum and maximum idioms, such as ScalarEvolution7363// and CodeGen. And in this case, at least one of the comparison7364// operands has at least one user besides the compare (the select),7365// which would often largely negate the benefit of folding anyway.7366//7367// Do the same for the other patterns recognized by matchSelectPattern.7368if (I.hasOneUse())7369if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {7370Value *A, *B;7371SelectPatternResult SPR = matchSelectPattern(SI, A, B);7372if (SPR.Flavor != SPF_UNKNOWN)7373return nullptr;7374}73757376// Do this after checking for min/max to prevent infinite looping.7377if (Instruction *Res = foldICmpWithZero(I))7378return Res;73797380// FIXME: We only do this after checking for min/max to prevent infinite7381// looping caused by a reverse canonicalization of these patterns for min/max.7382// FIXME: The organization of folds is a mess. These would naturally go into7383// canonicalizeCmpWithConstant(), but we can't move all of the above folds7384// down here after the min/max restriction.7385ICmpInst::Predicate Pred = I.getPredicate();7386const APInt *C;7387if (match(Op1, m_APInt(C))) {7388// For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set7389if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {7390Constant *Zero = Constant::getNullValue(Op0->getType());7391return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);7392}73937394// For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear7395if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {7396Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());7397return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);7398}7399}74007401// The folds in here may rely on wrapping flags and special constants, so7402// they can break up min/max idioms in some cases but not seemingly similar7403// patterns.7404// FIXME: It may be possible to enhance select folding to make this7405// unnecessary. It may also be moot if we canonicalize to min/max7406// intrinsics.7407if (Instruction *Res = foldICmpBinOp(I, Q))7408return Res;74097410if (Instruction *Res = foldICmpInstWithConstant(I))7411return Res;74127413// Try to match comparison as a sign bit test. Intentionally do this after7414// foldICmpInstWithConstant() to potentially let other folds to happen first.7415if (Instruction *New = foldSignBitTest(I))7416return New;74177418if (Instruction *Res = foldICmpInstWithConstantNotInt(I))7419return Res;74207421if (Instruction *Res = foldICmpCommutative(I.getPredicate(), Op0, Op1, I))7422return Res;7423if (Instruction *Res =7424foldICmpCommutative(I.getSwappedPredicate(), Op1, Op0, I))7425return Res;74267427if (I.isCommutative()) {7428if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {7429replaceOperand(I, 0, Pair->first);7430replaceOperand(I, 1, Pair->second);7431return &I;7432}7433}74347435// In case of a comparison with two select instructions having the same7436// condition, check whether one of the resulting branches can be simplified.7437// If so, just compare the other branch and select the appropriate result.7438// For example:7439// %tmp1 = select i1 %cmp, i32 %y, i32 %x7440// %tmp2 = select i1 %cmp, i32 %z, i32 %x7441// %cmp2 = icmp slt i32 %tmp2, %tmp17442// The icmp will result false for the false value of selects and the result7443// will depend upon the comparison of true values of selects if %cmp is7444// true. Thus, transform this into:7445// %cmp = icmp slt i32 %y, %z7446// %sel = select i1 %cond, i1 %cmp, i1 false7447// This handles similar cases to transform.7448{7449Value *Cond, *A, *B, *C, *D;7450if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&7451match(Op1, m_Select(m_Specific(Cond), m_Value(C), m_Value(D))) &&7452(Op0->hasOneUse() || Op1->hasOneUse())) {7453// Check whether comparison of TrueValues can be simplified7454if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {7455Value *NewICMP = Builder.CreateICmp(Pred, B, D);7456return SelectInst::Create(Cond, Res, NewICMP);7457}7458// Check whether comparison of FalseValues can be simplified7459if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {7460Value *NewICMP = Builder.CreateICmp(Pred, A, C);7461return SelectInst::Create(Cond, NewICMP, Res);7462}7463}7464}74657466// Try to optimize equality comparisons against alloca-based pointers.7467if (Op0->getType()->isPointerTy() && I.isEquality()) {7468assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");7469if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))7470if (foldAllocaCmp(Alloca))7471return nullptr;7472if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))7473if (foldAllocaCmp(Alloca))7474return nullptr;7475}74767477if (Instruction *Res = foldICmpBitCast(I))7478return Res;74797480// TODO: Hoist this above the min/max bailout.7481if (Instruction *R = foldICmpWithCastOp(I))7482return R;74837484{7485Value *X, *Y;7486// Transform (X & ~Y) == 0 --> (X & Y) != 07487// and (X & ~Y) != 0 --> (X & Y) == 07488// if A is a power of 2.7489if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&7490match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, 0, &I) &&7491I.isEquality())7492return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),7493Op1);74947495// Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.7496if (Op0->getType()->isIntOrIntVectorTy()) {7497bool ConsumesOp0, ConsumesOp1;7498if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&7499isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&7500(ConsumesOp0 || ConsumesOp1)) {7501Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);7502Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);7503assert(InvOp0 && InvOp1 &&7504"Mismatch between isFreeToInvert and getFreelyInverted");7505return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);7506}7507}75087509Instruction *AddI = nullptr;7510if (match(&I, m_UAddWithOverflow(m_Value(X), m_Value(Y),7511m_Instruction(AddI))) &&7512isa<IntegerType>(X->getType())) {7513Value *Result;7514Constant *Overflow;7515// m_UAddWithOverflow can match patterns that do not include an explicit7516// "add" instruction, so check the opcode of the matched op.7517if (AddI->getOpcode() == Instruction::Add &&7518OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,7519Result, Overflow)) {7520replaceInstUsesWith(*AddI, Result);7521eraseInstFromFunction(*AddI);7522return replaceInstUsesWith(I, Overflow);7523}7524}75257526// (zext X) * (zext Y) --> llvm.umul.with.overflow.7527if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&7528match(Op1, m_APInt(C))) {7529if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))7530return R;7531}75327533// Signbit test folds7534// Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i17535// Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i17536Instruction *ExtI;7537if ((I.isUnsigned() || I.isEquality()) &&7538match(Op1,7539m_CombineAnd(m_Instruction(ExtI), m_ZExtOrSExt(m_Value(Y)))) &&7540Y->getType()->getScalarSizeInBits() == 1 &&7541(Op0->hasOneUse() || Op1->hasOneUse())) {7542unsigned OpWidth = Op0->getType()->getScalarSizeInBits();7543Instruction *ShiftI;7544if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),7545m_Shr(m_Value(X), m_SpecificIntAllowPoison(7546OpWidth - 1))))) {7547unsigned ExtOpc = ExtI->getOpcode();7548unsigned ShiftOpc = ShiftI->getOpcode();7549if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||7550(ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {7551Value *SLTZero =7552Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));7553Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());7554return replaceInstUsesWith(I, Cmp);7555}7556}7557}7558}75597560if (Instruction *Res = foldICmpEquality(I))7561return Res;75627563if (Instruction *Res = foldICmpPow2Test(I, Builder))7564return Res;75657566if (Instruction *Res = foldICmpOfUAddOv(I))7567return Res;75687569// The 'cmpxchg' instruction returns an aggregate containing the old value and7570// an i1 which indicates whether or not we successfully did the swap.7571//7572// Replace comparisons between the old value and the expected value with the7573// indicator that 'cmpxchg' returns.7574//7575// N.B. This transform is only valid when the 'cmpxchg' is not permitted to7576// spuriously fail. In those cases, the old value may equal the expected7577// value but it is possible for the swap to not occur.7578if (I.getPredicate() == ICmpInst::ICMP_EQ)7579if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))7580if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))7581if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&7582!ACXI->isWeak())7583return ExtractValueInst::Create(ACXI, 1);75847585if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))7586return Res;75877588if (I.getType()->isVectorTy())7589if (Instruction *Res = foldVectorCmp(I, Builder))7590return Res;75917592if (Instruction *Res = foldICmpInvariantGroup(I))7593return Res;75947595if (Instruction *Res = foldReductionIdiom(I, Builder, DL))7596return Res;75977598return Changed ? &I : nullptr;7599}76007601/// Fold fcmp ([us]itofp x, cst) if possible.7602Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,7603Instruction *LHSI,7604Constant *RHSC) {7605const APFloat *RHS;7606if (!match(RHSC, m_APFloat(RHS)))7607return nullptr;76087609// Get the width of the mantissa. We don't want to hack on conversions that7610// might lose information from the integer, e.g. "i64 -> float"7611int MantissaWidth = LHSI->getType()->getFPMantissaWidth();7612if (MantissaWidth == -1) return nullptr; // Unknown.76137614Type *IntTy = LHSI->getOperand(0)->getType();7615unsigned IntWidth = IntTy->getScalarSizeInBits();7616bool LHSUnsigned = isa<UIToFPInst>(LHSI);76177618if (I.isEquality()) {7619FCmpInst::Predicate P = I.getPredicate();7620bool IsExact = false;7621APSInt RHSCvt(IntWidth, LHSUnsigned);7622RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);76237624// If the floating point constant isn't an integer value, we know if we will7625// ever compare equal / not equal to it.7626if (!IsExact) {7627// TODO: Can never be -0.0 and other non-representable values7628APFloat RHSRoundInt(*RHS);7629RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);7630if (*RHS != RHSRoundInt) {7631if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)7632return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));76337634assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);7635return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7636}7637}76387639// TODO: If the constant is exactly representable, is it always OK to do7640// equality compares as integer?7641}76427643// Check to see that the input is converted from an integer type that is small7644// enough that preserves all bits. TODO: check here for "known" sign bits.7645// This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.76467647// Following test does NOT adjust IntWidth downwards for signed inputs,7648// because the most negative value still requires all the mantissa bits7649// to distinguish it from one less than that value.7650if ((int)IntWidth > MantissaWidth) {7651// Conversion would lose accuracy. Check if loss can impact comparison.7652int Exp = ilogb(*RHS);7653if (Exp == APFloat::IEK_Inf) {7654int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));7655if (MaxExponent < (int)IntWidth - !LHSUnsigned)7656// Conversion could create infinity.7657return nullptr;7658} else {7659// Note that if RHS is zero or NaN, then Exp is negative7660// and first condition is trivially false.7661if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)7662// Conversion could affect comparison.7663return nullptr;7664}7665}76667667// Otherwise, we can potentially simplify the comparison. We know that it7668// will always come through as an integer value and we know the constant is7669// not a NAN (it would have been previously simplified).7670assert(!RHS->isNaN() && "NaN comparison not already folded!");76717672ICmpInst::Predicate Pred;7673switch (I.getPredicate()) {7674default: llvm_unreachable("Unexpected predicate!");7675case FCmpInst::FCMP_UEQ:7676case FCmpInst::FCMP_OEQ:7677Pred = ICmpInst::ICMP_EQ;7678break;7679case FCmpInst::FCMP_UGT:7680case FCmpInst::FCMP_OGT:7681Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;7682break;7683case FCmpInst::FCMP_UGE:7684case FCmpInst::FCMP_OGE:7685Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;7686break;7687case FCmpInst::FCMP_ULT:7688case FCmpInst::FCMP_OLT:7689Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;7690break;7691case FCmpInst::FCMP_ULE:7692case FCmpInst::FCMP_OLE:7693Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;7694break;7695case FCmpInst::FCMP_UNE:7696case FCmpInst::FCMP_ONE:7697Pred = ICmpInst::ICMP_NE;7698break;7699case FCmpInst::FCMP_ORD:7700return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7701case FCmpInst::FCMP_UNO:7702return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7703}77047705// Now we know that the APFloat is a normal number, zero or inf.77067707// See if the FP constant is too large for the integer. For example,7708// comparing an i8 to 300.0.7709if (!LHSUnsigned) {7710// If the RHS value is > SignedMax, fold the comparison. This handles +INF7711// and large values.7712APFloat SMax(RHS->getSemantics());7713SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,7714APFloat::rmNearestTiesToEven);7715if (SMax < *RHS) { // smax < 13123.07716if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||7717Pred == ICmpInst::ICMP_SLE)7718return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7719return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7720}7721} else {7722// If the RHS value is > UnsignedMax, fold the comparison. This handles7723// +INF and large values.7724APFloat UMax(RHS->getSemantics());7725UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,7726APFloat::rmNearestTiesToEven);7727if (UMax < *RHS) { // umax < 13123.07728if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||7729Pred == ICmpInst::ICMP_ULE)7730return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7731return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7732}7733}77347735if (!LHSUnsigned) {7736// See if the RHS value is < SignedMin.7737APFloat SMin(RHS->getSemantics());7738SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,7739APFloat::rmNearestTiesToEven);7740if (SMin > *RHS) { // smin > 12312.07741if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||7742Pred == ICmpInst::ICMP_SGE)7743return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7744return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7745}7746} else {7747// See if the RHS value is < UnsignedMin.7748APFloat UMin(RHS->getSemantics());7749UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,7750APFloat::rmNearestTiesToEven);7751if (UMin > *RHS) { // umin > 12312.07752if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||7753Pred == ICmpInst::ICMP_UGE)7754return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7755return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7756}7757}77587759// Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or7760// [0, UMAX], but it may still be fractional. Check whether this is the case7761// using the IsExact flag.7762// Don't do this for zero, because -0.0 is not fractional.7763APSInt RHSInt(IntWidth, LHSUnsigned);7764bool IsExact;7765RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);7766if (!RHS->isZero()) {7767if (!IsExact) {7768// If we had a comparison against a fractional value, we have to adjust7769// the compare predicate and sometimes the value. RHSC is rounded towards7770// zero at this point.7771switch (Pred) {7772default: llvm_unreachable("Unexpected integer comparison!");7773case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true7774return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7775case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false7776return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7777case ICmpInst::ICMP_ULE:7778// (float)int <= 4.4 --> int <= 47779// (float)int <= -4.4 --> false7780if (RHS->isNegative())7781return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7782break;7783case ICmpInst::ICMP_SLE:7784// (float)int <= 4.4 --> int <= 47785// (float)int <= -4.4 --> int < -47786if (RHS->isNegative())7787Pred = ICmpInst::ICMP_SLT;7788break;7789case ICmpInst::ICMP_ULT:7790// (float)int < -4.4 --> false7791// (float)int < 4.4 --> int <= 47792if (RHS->isNegative())7793return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));7794Pred = ICmpInst::ICMP_ULE;7795break;7796case ICmpInst::ICMP_SLT:7797// (float)int < -4.4 --> int < -47798// (float)int < 4.4 --> int <= 47799if (!RHS->isNegative())7800Pred = ICmpInst::ICMP_SLE;7801break;7802case ICmpInst::ICMP_UGT:7803// (float)int > 4.4 --> int > 47804// (float)int > -4.4 --> true7805if (RHS->isNegative())7806return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7807break;7808case ICmpInst::ICMP_SGT:7809// (float)int > 4.4 --> int > 47810// (float)int > -4.4 --> int >= -47811if (RHS->isNegative())7812Pred = ICmpInst::ICMP_SGE;7813break;7814case ICmpInst::ICMP_UGE:7815// (float)int >= -4.4 --> true7816// (float)int >= 4.4 --> int > 47817if (RHS->isNegative())7818return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));7819Pred = ICmpInst::ICMP_UGT;7820break;7821case ICmpInst::ICMP_SGE:7822// (float)int >= -4.4 --> int >= -47823// (float)int >= 4.4 --> int > 47824if (!RHS->isNegative())7825Pred = ICmpInst::ICMP_SGT;7826break;7827}7828}7829}78307831// Lower this FP comparison into an appropriate integer version of the7832// comparison.7833return new ICmpInst(Pred, LHSI->getOperand(0),7834ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));7835}78367837/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.7838static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,7839Constant *RHSC) {7840// When C is not 0.0 and infinities are not allowed:7841// (C / X) < 0.0 is a sign-bit test of X7842// (C / X) < 0.0 --> X < 0.0 (if C is positive)7843// (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)7844//7845// Proof:7846// Multiply (C / X) < 0.0 by X * X / C.7847// - X is non zero, if it is the flag 'ninf' is violated.7848// - C defines the sign of X * X * C. Thus it also defines whether to swap7849// the predicate. C is also non zero by definition.7850//7851// Thus X * X / C is non zero and the transformation is valid. [qed]78527853FCmpInst::Predicate Pred = I.getPredicate();78547855// Check that predicates are valid.7856if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&7857(Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))7858return nullptr;78597860// Check that RHS operand is zero.7861if (!match(RHSC, m_AnyZeroFP()))7862return nullptr;78637864// Check fastmath flags ('ninf').7865if (!LHSI->hasNoInfs() || !I.hasNoInfs())7866return nullptr;78677868// Check the properties of the dividend. It must not be zero to avoid a7869// division by zero (see Proof).7870const APFloat *C;7871if (!match(LHSI->getOperand(0), m_APFloat(C)))7872return nullptr;78737874if (C->isZero())7875return nullptr;78767877// Get swapped predicate if necessary.7878if (C->isNegative())7879Pred = I.getSwappedPredicate();78807881return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);7882}78837884/// Optimize fabs(X) compared with zero.7885static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {7886Value *X;7887if (!match(I.getOperand(0), m_FAbs(m_Value(X))))7888return nullptr;78897890const APFloat *C;7891if (!match(I.getOperand(1), m_APFloat(C)))7892return nullptr;78937894if (!C->isPosZero()) {7895if (!C->isSmallestNormalized())7896return nullptr;78977898const Function *F = I.getFunction();7899DenormalMode Mode = F->getDenormalMode(C->getSemantics());7900if (Mode.Input == DenormalMode::PreserveSign ||7901Mode.Input == DenormalMode::PositiveZero) {79027903auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {7904Constant *Zero = ConstantFP::getZero(X->getType());7905return new FCmpInst(P, X, Zero, "", I);7906};79077908switch (I.getPredicate()) {7909case FCmpInst::FCMP_OLT:7910// fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.07911return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);7912case FCmpInst::FCMP_UGE:7913// fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.07914return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);7915case FCmpInst::FCMP_OGE:7916// fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.07917return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);7918case FCmpInst::FCMP_ULT:7919// fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.07920return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);7921default:7922break;7923}7924}79257926return nullptr;7927}79287929auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {7930I->setPredicate(P);7931return IC.replaceOperand(*I, 0, X);7932};79337934switch (I.getPredicate()) {7935case FCmpInst::FCMP_UGE:7936case FCmpInst::FCMP_OLT:7937// fabs(X) >= 0.0 --> true7938// fabs(X) < 0.0 --> false7939llvm_unreachable("fcmp should have simplified");79407941case FCmpInst::FCMP_OGT:7942// fabs(X) > 0.0 --> X != 0.07943return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);79447945case FCmpInst::FCMP_UGT:7946// fabs(X) u> 0.0 --> X u!= 0.07947return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);79487949case FCmpInst::FCMP_OLE:7950// fabs(X) <= 0.0 --> X == 0.07951return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);79527953case FCmpInst::FCMP_ULE:7954// fabs(X) u<= 0.0 --> X u== 0.07955return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);79567957case FCmpInst::FCMP_OGE:7958// fabs(X) >= 0.0 --> !isnan(X)7959assert(!I.hasNoNaNs() && "fcmp should have simplified");7960return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);79617962case FCmpInst::FCMP_ULT:7963// fabs(X) u< 0.0 --> isnan(X)7964assert(!I.hasNoNaNs() && "fcmp should have simplified");7965return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);79667967case FCmpInst::FCMP_OEQ:7968case FCmpInst::FCMP_UEQ:7969case FCmpInst::FCMP_ONE:7970case FCmpInst::FCMP_UNE:7971case FCmpInst::FCMP_ORD:7972case FCmpInst::FCMP_UNO:7973// Look through the fabs() because it doesn't change anything but the sign.7974// fabs(X) == 0.0 --> X == 0.0,7975// fabs(X) != 0.0 --> X != 0.07976// isnan(fabs(X)) --> isnan(X)7977// !isnan(fabs(X) --> !isnan(X)7978return replacePredAndOp0(&I, I.getPredicate(), X);79797980default:7981return nullptr;7982}7983}79847985static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {7986CmpInst::Predicate Pred = I.getPredicate();7987Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);79887989// Canonicalize fneg as Op1.7990if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {7991std::swap(Op0, Op1);7992Pred = I.getSwappedPredicate();7993}79947995if (!match(Op1, m_FNeg(m_Specific(Op0))))7996return nullptr;79977998// Replace the negated operand with 0.0:7999// fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.08000Constant *Zero = ConstantFP::getZero(Op0->getType());8001return new FCmpInst(Pred, Op0, Zero, "", &I);8002}80038004static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,8005Constant *RHSC, InstCombinerImpl &CI) {8006const CmpInst::Predicate Pred = I.getPredicate();8007Value *X = LHSI->getOperand(0);8008Value *Y = LHSI->getOperand(1);8009switch (Pred) {8010default:8011break;8012case FCmpInst::FCMP_UGT:8013case FCmpInst::FCMP_ULT:8014case FCmpInst::FCMP_UNE:8015case FCmpInst::FCMP_OEQ:8016case FCmpInst::FCMP_OGE:8017case FCmpInst::FCMP_OLE:8018// The optimization is not valid if X and Y are infinities of the same8019// sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan8020// flag then we can assume we do not have that case. Otherwise we might be8021// able to prove that either X or Y is not infinity.8022if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&8023!isKnownNeverInfinity(Y, /*Depth=*/0,8024CI.getSimplifyQuery().getWithInstruction(&I)) &&8025!isKnownNeverInfinity(X, /*Depth=*/0,8026CI.getSimplifyQuery().getWithInstruction(&I)))8027break;80288029[[fallthrough]];8030case FCmpInst::FCMP_OGT:8031case FCmpInst::FCMP_OLT:8032case FCmpInst::FCMP_ONE:8033case FCmpInst::FCMP_UEQ:8034case FCmpInst::FCMP_UGE:8035case FCmpInst::FCMP_ULE:8036// fcmp pred (x - y), 0 --> fcmp pred x, y8037if (match(RHSC, m_AnyZeroFP()) &&8038I.getFunction()->getDenormalMode(8039LHSI->getType()->getScalarType()->getFltSemantics()) ==8040DenormalMode::getIEEE()) {8041CI.replaceOperand(I, 0, X);8042CI.replaceOperand(I, 1, Y);8043return &I;8044}8045break;8046}80478048return nullptr;8049}80508051Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {8052bool Changed = false;80538054/// Orders the operands of the compare so that they are listed from most8055/// complex to least complex. This puts constants before unary operators,8056/// before binary operators.8057if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {8058I.swapOperands();8059Changed = true;8060}80618062const CmpInst::Predicate Pred = I.getPredicate();8063Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);8064if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),8065SQ.getWithInstruction(&I)))8066return replaceInstUsesWith(I, V);80678068// Simplify 'fcmp pred X, X'8069Type *OpType = Op0->getType();8070assert(OpType == Op1->getType() && "fcmp with different-typed operands?");8071if (Op0 == Op1) {8072switch (Pred) {8073default: break;8074case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)8075case FCmpInst::FCMP_ULT: // True if unordered or less than8076case FCmpInst::FCMP_UGT: // True if unordered or greater than8077case FCmpInst::FCMP_UNE: // True if unordered or not equal8078// Canonicalize these to be 'fcmp uno %X, 0.0'.8079I.setPredicate(FCmpInst::FCMP_UNO);8080I.setOperand(1, Constant::getNullValue(OpType));8081return &I;80828083case FCmpInst::FCMP_ORD: // True if ordered (no nans)8084case FCmpInst::FCMP_OEQ: // True if ordered and equal8085case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal8086case FCmpInst::FCMP_OLE: // True if ordered and less than or equal8087// Canonicalize these to be 'fcmp ord %X, 0.0'.8088I.setPredicate(FCmpInst::FCMP_ORD);8089I.setOperand(1, Constant::getNullValue(OpType));8090return &I;8091}8092}80938094if (I.isCommutative()) {8095if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {8096replaceOperand(I, 0, Pair->first);8097replaceOperand(I, 1, Pair->second);8098return &I;8099}8100}81018102// If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,8103// then canonicalize the operand to 0.0.8104if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {8105if (!match(Op0, m_PosZeroFP()) &&8106isKnownNeverNaN(Op0, 0, getSimplifyQuery().getWithInstruction(&I)))8107return replaceOperand(I, 0, ConstantFP::getZero(OpType));81088109if (!match(Op1, m_PosZeroFP()) &&8110isKnownNeverNaN(Op1, 0, getSimplifyQuery().getWithInstruction(&I)))8111return replaceOperand(I, 1, ConstantFP::getZero(OpType));8112}81138114// fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y8115Value *X, *Y;8116if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))8117return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);81188119if (Instruction *R = foldFCmpFNegCommonOp(I))8120return R;81218122// Test if the FCmpInst instruction is used exclusively by a select as8123// part of a minimum or maximum operation. If so, refrain from doing8124// any other folding. This helps out other analyses which understand8125// non-obfuscated minimum and maximum idioms, such as ScalarEvolution8126// and CodeGen. And in this case, at least one of the comparison8127// operands has at least one user besides the compare (the select),8128// which would often largely negate the benefit of folding anyway.8129if (I.hasOneUse())8130if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {8131Value *A, *B;8132SelectPatternResult SPR = matchSelectPattern(SI, A, B);8133if (SPR.Flavor != SPF_UNKNOWN)8134return nullptr;8135}81368137// The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:8138// fcmp Pred X, -0.0 --> fcmp Pred X, 0.08139if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))8140return replaceOperand(I, 1, ConstantFP::getZero(OpType));81418142// Canonicalize:8143// fcmp olt X, +inf -> fcmp one X, +inf8144// fcmp ole X, +inf -> fcmp ord X, 08145// fcmp ogt X, +inf -> false8146// fcmp oge X, +inf -> fcmp oeq X, +inf8147// fcmp ult X, +inf -> fcmp une X, +inf8148// fcmp ule X, +inf -> true8149// fcmp ugt X, +inf -> fcmp uno X, 08150// fcmp uge X, +inf -> fcmp ueq X, +inf8151// fcmp olt X, -inf -> false8152// fcmp ole X, -inf -> fcmp oeq X, -inf8153// fcmp ogt X, -inf -> fcmp one X, -inf8154// fcmp oge X, -inf -> fcmp ord X, 08155// fcmp ult X, -inf -> fcmp uno X, 08156// fcmp ule X, -inf -> fcmp ueq X, -inf8157// fcmp ugt X, -inf -> fcmp une X, -inf8158// fcmp uge X, -inf -> true8159const APFloat *C;8160if (match(Op1, m_APFloat(C)) && C->isInfinity()) {8161switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {8162default:8163break;8164case FCmpInst::FCMP_ORD:8165case FCmpInst::FCMP_UNO:8166case FCmpInst::FCMP_TRUE:8167case FCmpInst::FCMP_FALSE:8168case FCmpInst::FCMP_OGT:8169case FCmpInst::FCMP_ULE:8170llvm_unreachable("Should be simplified by InstSimplify");8171case FCmpInst::FCMP_OLT:8172return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);8173case FCmpInst::FCMP_OLE:8174return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),8175"", &I);8176case FCmpInst::FCMP_OGE:8177return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);8178case FCmpInst::FCMP_ULT:8179return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);8180case FCmpInst::FCMP_UGT:8181return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),8182"", &I);8183case FCmpInst::FCMP_UGE:8184return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);8185}8186}81878188// Ignore signbit of bitcasted int when comparing equality to FP 0.0:8189// fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 08190if (match(Op1, m_PosZeroFP()) &&8191match(Op0, m_OneUse(m_ElementWiseBitCast(m_Value(X))))) {8192ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;8193if (Pred == FCmpInst::FCMP_OEQ)8194IntPred = ICmpInst::ICMP_EQ;8195else if (Pred == FCmpInst::FCMP_UNE)8196IntPred = ICmpInst::ICMP_NE;81978198if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {8199Type *IntTy = X->getType();8200const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());8201Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));8202return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));8203}8204}82058206// Handle fcmp with instruction LHS and constant RHS.8207Instruction *LHSI;8208Constant *RHSC;8209if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {8210switch (LHSI->getOpcode()) {8211case Instruction::Select:8212// fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 08213if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&8214(match(LHSI,8215m_Select(m_Value(), m_Value(X), m_FNeg(m_Deferred(X)))) ||8216match(LHSI, m_Select(m_Value(), m_FNeg(m_Value(X)), m_Deferred(X)))))8217return replaceOperand(I, 0, X);8218if (Instruction *NV = FoldOpIntoSelect(I, cast<SelectInst>(LHSI)))8219return NV;8220break;8221case Instruction::FSub:8222if (LHSI->hasOneUse())8223if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))8224return NV;8225break;8226case Instruction::PHI:8227if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))8228return NV;8229break;8230case Instruction::SIToFP:8231case Instruction::UIToFP:8232if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))8233return NV;8234break;8235case Instruction::FDiv:8236if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))8237return NV;8238break;8239case Instruction::Load:8240if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))8241if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))8242if (Instruction *Res = foldCmpLoadFromIndexedGlobal(8243cast<LoadInst>(LHSI), GEP, GV, I))8244return Res;8245break;8246}8247}82488249if (Instruction *R = foldFabsWithFcmpZero(I, *this))8250return R;82518252if (match(Op0, m_FNeg(m_Value(X)))) {8253// fcmp pred (fneg X), C --> fcmp swap(pred) X, -C8254Constant *C;8255if (match(Op1, m_Constant(C)))8256if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))8257return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);8258}82598260// fcmp (fadd X, 0.0), Y --> fcmp X, Y8261if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))8262return new FCmpInst(Pred, X, Op1, "", &I);82638264// fcmp X, (fadd Y, 0.0) --> fcmp X, Y8265if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))8266return new FCmpInst(Pred, Op0, Y, "", &I);82678268if (match(Op0, m_FPExt(m_Value(X)))) {8269// fcmp (fpext X), (fpext Y) -> fcmp X, Y8270if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())8271return new FCmpInst(Pred, X, Y, "", &I);82728273const APFloat *C;8274if (match(Op1, m_APFloat(C))) {8275const fltSemantics &FPSem =8276X->getType()->getScalarType()->getFltSemantics();8277bool Lossy;8278APFloat TruncC = *C;8279TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);82808281if (Lossy) {8282// X can't possibly equal the higher-precision constant, so reduce any8283// equality comparison.8284// TODO: Other predicates can be handled via getFCmpCode().8285switch (Pred) {8286case FCmpInst::FCMP_OEQ:8287// X is ordered and equal to an impossible constant --> false8288return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));8289case FCmpInst::FCMP_ONE:8290// X is ordered and not equal to an impossible constant --> ordered8291return new FCmpInst(FCmpInst::FCMP_ORD, X,8292ConstantFP::getZero(X->getType()));8293case FCmpInst::FCMP_UEQ:8294// X is unordered or equal to an impossible constant --> unordered8295return new FCmpInst(FCmpInst::FCMP_UNO, X,8296ConstantFP::getZero(X->getType()));8297case FCmpInst::FCMP_UNE:8298// X is unordered or not equal to an impossible constant --> true8299return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));8300default:8301break;8302}8303}83048305// fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless8306// Avoid lossy conversions and denormals.8307// Zero is a special case that's OK to convert.8308APFloat Fabs = TruncC;8309Fabs.clearSign();8310if (!Lossy &&8311(Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {8312Constant *NewC = ConstantFP::get(X->getType(), TruncC);8313return new FCmpInst(Pred, X, NewC, "", &I);8314}8315}8316}83178318// Convert a sign-bit test of an FP value into a cast and integer compare.8319// TODO: Simplify if the copysign constant is 0.0 or NaN.8320// TODO: Handle non-zero compare constants.8321// TODO: Handle other predicates.8322if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),8323m_Value(X)))) &&8324match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {8325Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());8326if (auto *VecTy = dyn_cast<VectorType>(OpType))8327IntType = VectorType::get(IntType, VecTy->getElementCount());83288329// copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 08330if (Pred == FCmpInst::FCMP_OLT) {8331Value *IntX = Builder.CreateBitCast(X, IntType);8332return new ICmpInst(ICmpInst::ICMP_SLT, IntX,8333ConstantInt::getNullValue(IntType));8334}8335}83368337{8338Value *CanonLHS = nullptr, *CanonRHS = nullptr;8339match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));8340match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));83418342// (canonicalize(x) == x) => (x == x)8343if (CanonLHS == Op1)8344return new FCmpInst(Pred, Op1, Op1, "", &I);83458346// (x == canonicalize(x)) => (x == x)8347if (CanonRHS == Op0)8348return new FCmpInst(Pred, Op0, Op0, "", &I);83498350// (canonicalize(x) == canonicalize(y)) => (x == y)8351if (CanonLHS && CanonRHS)8352return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);8353}83548355if (I.getType()->isVectorTy())8356if (Instruction *Res = foldVectorCmp(I, Builder))8357return Res;83588359return Changed ? &I : nullptr;8360}836183628363