Index: lib/Analysis/InstructionSimplify.cpp =================================================================== --- lib/Analysis/InstructionSimplify.cpp +++ lib/Analysis/InstructionSimplify.cpp @@ -2128,6 +2128,32 @@ return nullptr; } +static ConstantRange GetCRFromRangeMetadata(Value *Val, uint32_t BitWidth) { + if (Instruction *I = dyn_cast(Val)) { + if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) { + const unsigned NumRanges = Ranges->getNumOperands() / 2; + assert(NumRanges >= 1); + + ConstantRange CR = ConstantRange(BitWidth, false); + for (unsigned i = 0; i < NumRanges; ++i) { + ConstantInt *Lower = + mdconst::extract(Ranges->getOperand(2 * i + 0)); + ConstantInt *Upper = + mdconst::extract(Ranges->getOperand(2 * i + 1)); + + ConstantRange Range(Lower->getValue(), Upper->getValue()); + + CR = CR.unionWith(Range); + } + + return CR; + } + } + + // If no range metadata available, return a full range. + return ConstantRange(BitWidth, true); +} + /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can /// fold the result. If not, this returns null. static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, @@ -2364,8 +2390,15 @@ // 'add nuw x, CI2' produces [CI2, UINT_MAX]. Lower = CI2->getValue(); } - if (Lower != Upper) { - ConstantRange LHS_CR = ConstantRange(Lower, Upper); + + uint32_t LHS_BitWidth = Q.DL.getTypeSizeInBits(LHS->getType()); + + ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper) + : ConstantRange(LHS_BitWidth, true); + + LHS_CR = LHS_CR.intersectWith(GetCRFromRangeMetadata(LHS, LHS_BitWidth)); + + if (!LHS_CR.isFullSet()) { if (RHS_CR.contains(LHS_CR)) return ConstantInt::getTrue(RHS->getContext()); if (RHS_CR.inverse().contains(LHS_CR)) Index: test/Transforms/InstCombine/icmp-range.ll =================================================================== --- test/Transforms/InstCombine/icmp-range.ll +++ test/Transforms/InstCombine/icmp-range.ll @@ -54,6 +54,14 @@ ret i1 %rval } +; Constant not in range, should return true +define i1 @test_not_in_range(i32* nocapture readonly %arg) { +; CHECK-LABEL: test_not_in_range +; CHECK: ret i1 true + %val = load i32, i32* %arg, !range !1 + %rval = icmp ne i32 %val, 6 + ret i1 %rval +} !0 = !{i32 1, i32 6} !1 = !{i32 0, i32 6}