1 //===- InstCombineCompares.cpp --------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the visitICmp and visitFCmp functions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombine.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/Analysis/MemoryBuiltins.h" 18 #include "llvm/IR/DataLayout.h" 19 #include "llvm/IR/IntrinsicInst.h" 20 #include "llvm/Support/ConstantRange.h" 21 #include "llvm/Support/GetElementPtrTypeIterator.h" 22 #include "llvm/Support/PatternMatch.h" 23 #include "llvm/Target/TargetLibraryInfo.h" 24 using namespace llvm; 25 using namespace PatternMatch; 26 27 static ConstantInt *getOne(Constant *C) { 28 return ConstantInt::get(cast<IntegerType>(C->getType()), 1); 29 } 30 31 /// AddOne - Add one to a ConstantInt 32 static Constant *AddOne(Constant *C) { 33 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1)); 34 } 35 /// SubOne - Subtract one from a ConstantInt 36 static Constant *SubOne(Constant *C) { 37 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1)); 38 } 39 40 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) { 41 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx)); 42 } 43 44 static bool HasAddOverflow(ConstantInt *Result, 45 ConstantInt *In1, ConstantInt *In2, 46 bool IsSigned) { 47 if (!IsSigned) 48 return Result->getValue().ult(In1->getValue()); 49 50 if (In2->isNegative()) 51 return Result->getValue().sgt(In1->getValue()); 52 return Result->getValue().slt(In1->getValue()); 53 } 54 55 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result 56 /// overflowed for this type. 57 static bool AddWithOverflow(Constant *&Result, Constant *In1, 58 Constant *In2, bool IsSigned = false) { 59 Result = ConstantExpr::getAdd(In1, In2); 60 61 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 62 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 63 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 64 if (HasAddOverflow(ExtractElement(Result, Idx), 65 ExtractElement(In1, Idx), 66 ExtractElement(In2, Idx), 67 IsSigned)) 68 return true; 69 } 70 return false; 71 } 72 73 return HasAddOverflow(cast<ConstantInt>(Result), 74 cast<ConstantInt>(In1), cast<ConstantInt>(In2), 75 IsSigned); 76 } 77 78 static bool HasSubOverflow(ConstantInt *Result, 79 ConstantInt *In1, ConstantInt *In2, 80 bool IsSigned) { 81 if (!IsSigned) 82 return Result->getValue().ugt(In1->getValue()); 83 84 if (In2->isNegative()) 85 return Result->getValue().slt(In1->getValue()); 86 87 return Result->getValue().sgt(In1->getValue()); 88 } 89 90 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result 91 /// overflowed for this type. 92 static bool SubWithOverflow(Constant *&Result, Constant *In1, 93 Constant *In2, bool IsSigned = false) { 94 Result = ConstantExpr::getSub(In1, In2); 95 96 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 97 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 98 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 99 if (HasSubOverflow(ExtractElement(Result, Idx), 100 ExtractElement(In1, Idx), 101 ExtractElement(In2, Idx), 102 IsSigned)) 103 return true; 104 } 105 return false; 106 } 107 108 return HasSubOverflow(cast<ConstantInt>(Result), 109 cast<ConstantInt>(In1), cast<ConstantInt>(In2), 110 IsSigned); 111 } 112 113 /// isSignBitCheck - Given an exploded icmp instruction, return true if the 114 /// comparison only checks the sign bit. If it only checks the sign bit, set 115 /// TrueIfSigned if the result of the comparison is true when the input value is 116 /// signed. 117 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS, 118 bool &TrueIfSigned) { 119 switch (pred) { 120 case ICmpInst::ICMP_SLT: // True if LHS s< 0 121 TrueIfSigned = true; 122 return RHS->isZero(); 123 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 124 TrueIfSigned = true; 125 return RHS->isAllOnesValue(); 126 case ICmpInst::ICMP_SGT: // True if LHS s> -1 127 TrueIfSigned = false; 128 return RHS->isAllOnesValue(); 129 case ICmpInst::ICMP_UGT: 130 // True if LHS u> RHS and RHS == high-bit-mask - 1 131 TrueIfSigned = true; 132 return RHS->isMaxValue(true); 133 case ICmpInst::ICMP_UGE: 134 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) 135 TrueIfSigned = true; 136 return RHS->getValue().isSignBit(); 137 default: 138 return false; 139 } 140 } 141 142 /// Returns true if the exploded icmp can be expressed as a signed comparison 143 /// to zero and updates the predicate accordingly. 144 /// The signedness of the comparison is preserved. 145 static bool isSignTest(ICmpInst::Predicate &pred, const ConstantInt *RHS) { 146 if (!ICmpInst::isSigned(pred)) 147 return false; 148 149 if (RHS->isZero()) 150 return ICmpInst::isRelational(pred); 151 152 if (RHS->isOne()) { 153 if (pred == ICmpInst::ICMP_SLT) { 154 pred = ICmpInst::ICMP_SLE; 155 return true; 156 } 157 } else if (RHS->isAllOnesValue()) { 158 if (pred == ICmpInst::ICMP_SGT) { 159 pred = ICmpInst::ICMP_SGE; 160 return true; 161 } 162 } 163 164 return false; 165 } 166 167 // isHighOnes - Return true if the constant is of the form 1+0+. 168 // This is the same as lowones(~X). 169 static bool isHighOnes(const ConstantInt *CI) { 170 return (~CI->getValue() + 1).isPowerOf2(); 171 } 172 173 /// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 174 /// set of known zero and one bits, compute the maximum and minimum values that 175 /// could have the specified known zero and known one bits, returning them in 176 /// min/max. 177 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero, 178 const APInt& KnownOne, 179 APInt& Min, APInt& Max) { 180 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 181 KnownZero.getBitWidth() == Min.getBitWidth() && 182 KnownZero.getBitWidth() == Max.getBitWidth() && 183 "KnownZero, KnownOne and Min, Max must have equal bitwidth."); 184 APInt UnknownBits = ~(KnownZero|KnownOne); 185 186 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign 187 // bit if it is unknown. 188 Min = KnownOne; 189 Max = KnownOne|UnknownBits; 190 191 if (UnknownBits.isNegative()) { // Sign bit is unknown 192 Min.setBit(Min.getBitWidth()-1); 193 Max.clearBit(Max.getBitWidth()-1); 194 } 195 } 196 197 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and 198 // a set of known zero and one bits, compute the maximum and minimum values that 199 // could have the specified known zero and known one bits, returning them in 200 // min/max. 201 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero, 202 const APInt &KnownOne, 203 APInt &Min, APInt &Max) { 204 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 205 KnownZero.getBitWidth() == Min.getBitWidth() && 206 KnownZero.getBitWidth() == Max.getBitWidth() && 207 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); 208 APInt UnknownBits = ~(KnownZero|KnownOne); 209 210 // The minimum value is when the unknown bits are all zeros. 211 Min = KnownOne; 212 // The maximum value is when the unknown bits are all ones. 213 Max = KnownOne|UnknownBits; 214 } 215 216 217 218 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern: 219 /// cmp pred (load (gep GV, ...)), cmpcst 220 /// where GV is a global variable with a constant initializer. Try to simplify 221 /// this into some simple computation that does not need the load. For example 222 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 223 /// 224 /// If AndCst is non-null, then the loaded value is masked with that constant 225 /// before doing the comparison. This handles cases like "A[i]&4 == 0". 226 Instruction *InstCombiner:: 227 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV, 228 CmpInst &ICI, ConstantInt *AndCst) { 229 if (!GEP->isInBounds()) 230 return 0; 231 232 Constant *Init = GV->getInitializer(); 233 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init)) 234 return 0; 235 236 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); 237 if (ArrayElementCount > 1024) return 0; // Don't blow up on huge arrays. 238 239 // There are many forms of this optimization we can handle, for now, just do 240 // the simple index into a single-dimensional array. 241 // 242 // Require: GEP GV, 0, i {{, constant indices}} 243 if (GEP->getNumOperands() < 3 || 244 !isa<ConstantInt>(GEP->getOperand(1)) || 245 !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 246 isa<Constant>(GEP->getOperand(2))) 247 return 0; 248 249 // Check that indices after the variable are constants and in-range for the 250 // type they index. Collect the indices. This is typically for arrays of 251 // structs. 252 SmallVector<unsigned, 4> LaterIndices; 253 254 Type *EltTy = Init->getType()->getArrayElementType(); 255 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 256 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 257 if (Idx == 0) return 0; // Variable index. 258 259 uint64_t IdxVal = Idx->getZExtValue(); 260 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index. 261 262 if (StructType *STy = dyn_cast<StructType>(EltTy)) 263 EltTy = STy->getElementType(IdxVal); 264 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 265 if (IdxVal >= ATy->getNumElements()) return 0; 266 EltTy = ATy->getElementType(); 267 } else { 268 return 0; // Unknown type. 269 } 270 271 LaterIndices.push_back(IdxVal); 272 } 273 274 enum { Overdefined = -3, Undefined = -2 }; 275 276 // Variables for our state machines. 277 278 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 279 // "i == 47 | i == 87", where 47 is the first index the condition is true for, 280 // and 87 is the second (and last) index. FirstTrueElement is -2 when 281 // undefined, otherwise set to the first true element. SecondTrueElement is 282 // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 283 int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 284 285 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 286 // form "i != 47 & i != 87". Same state transitions as for true elements. 287 int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 288 289 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 290 /// define a state machine that triggers for ranges of values that the index 291 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 292 /// This is -2 when undefined, -3 when overdefined, and otherwise the last 293 /// index in the range (inclusive). We use -2 for undefined here because we 294 /// use relative comparisons and don't want 0-1 to match -1. 295 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 296 297 // MagicBitvector - This is a magic bitvector where we set a bit if the 298 // comparison is true for element 'i'. If there are 64 elements or less in 299 // the array, this will fully represent all the comparison results. 300 uint64_t MagicBitvector = 0; 301 302 303 // Scan the array and see if one of our patterns matches. 304 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 305 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { 306 Constant *Elt = Init->getAggregateElement(i); 307 if (Elt == 0) return 0; 308 309 // If this is indexing an array of structures, get the structure element. 310 if (!LaterIndices.empty()) 311 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices); 312 313 // If the element is masked, handle it. 314 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 315 316 // Find out if the comparison would be true or false for the i'th element. 317 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 318 CompareRHS, TD, TLI); 319 // If the result is undef for this element, ignore it. 320 if (isa<UndefValue>(C)) { 321 // Extend range state machines to cover this element in case there is an 322 // undef in the middle of the range. 323 if (TrueRangeEnd == (int)i-1) 324 TrueRangeEnd = i; 325 if (FalseRangeEnd == (int)i-1) 326 FalseRangeEnd = i; 327 continue; 328 } 329 330 // If we can't compute the result for any of the elements, we have to give 331 // up evaluating the entire conditional. 332 if (!isa<ConstantInt>(C)) return 0; 333 334 // Otherwise, we know if the comparison is true or false for this element, 335 // update our state machines. 336 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 337 338 // State machine for single/double/range index comparison. 339 if (IsTrueForElt) { 340 // Update the TrueElement state machine. 341 if (FirstTrueElement == Undefined) 342 FirstTrueElement = TrueRangeEnd = i; // First true element. 343 else { 344 // Update double-compare state machine. 345 if (SecondTrueElement == Undefined) 346 SecondTrueElement = i; 347 else 348 SecondTrueElement = Overdefined; 349 350 // Update range state machine. 351 if (TrueRangeEnd == (int)i-1) 352 TrueRangeEnd = i; 353 else 354 TrueRangeEnd = Overdefined; 355 } 356 } else { 357 // Update the FalseElement state machine. 358 if (FirstFalseElement == Undefined) 359 FirstFalseElement = FalseRangeEnd = i; // First false element. 360 else { 361 // Update double-compare state machine. 362 if (SecondFalseElement == Undefined) 363 SecondFalseElement = i; 364 else 365 SecondFalseElement = Overdefined; 366 367 // Update range state machine. 368 if (FalseRangeEnd == (int)i-1) 369 FalseRangeEnd = i; 370 else 371 FalseRangeEnd = Overdefined; 372 } 373 } 374 375 376 // If this element is in range, update our magic bitvector. 377 if (i < 64 && IsTrueForElt) 378 MagicBitvector |= 1ULL << i; 379 380 // If all of our states become overdefined, bail out early. Since the 381 // predicate is expensive, only check it every 8 elements. This is only 382 // really useful for really huge arrays. 383 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 384 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 385 FalseRangeEnd == Overdefined) 386 return 0; 387 } 388 389 // Now that we've scanned the entire array, emit our new comparison(s). We 390 // order the state machines in complexity of the generated code. 391 Value *Idx = GEP->getOperand(2); 392 393 // If the comparison is only true for one or two elements, emit direct 394 // comparisons. 395 if (SecondTrueElement != Overdefined) { 396 // None true -> false. 397 if (FirstTrueElement == Undefined) 398 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 399 400 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 401 402 // True for one element -> 'i == 47'. 403 if (SecondTrueElement == Undefined) 404 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 405 406 // True for two elements -> 'i == 47 | i == 72'. 407 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); 408 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 409 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); 410 return BinaryOperator::CreateOr(C1, C2); 411 } 412 413 // If the comparison is only false for one or two elements, emit direct 414 // comparisons. 415 if (SecondFalseElement != Overdefined) { 416 // None false -> true. 417 if (FirstFalseElement == Undefined) 418 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 419 420 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 421 422 // False for one element -> 'i != 47'. 423 if (SecondFalseElement == Undefined) 424 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 425 426 // False for two elements -> 'i != 47 & i != 72'. 427 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); 428 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 429 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); 430 return BinaryOperator::CreateAnd(C1, C2); 431 } 432 433 // If the comparison can be replaced with a range comparison for the elements 434 // where it is true, emit the range check. 435 if (TrueRangeEnd != Overdefined) { 436 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 437 438 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 439 if (FirstTrueElement) { 440 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 441 Idx = Builder->CreateAdd(Idx, Offs); 442 } 443 444 Value *End = ConstantInt::get(Idx->getType(), 445 TrueRangeEnd-FirstTrueElement+1); 446 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 447 } 448 449 // False range check. 450 if (FalseRangeEnd != Overdefined) { 451 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 452 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 453 if (FirstFalseElement) { 454 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 455 Idx = Builder->CreateAdd(Idx, Offs); 456 } 457 458 Value *End = ConstantInt::get(Idx->getType(), 459 FalseRangeEnd-FirstFalseElement); 460 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 461 } 462 463 464 // If a magic bitvector captures the entire comparison state 465 // of this load, replace it with computation that does: 466 // ((magic_cst >> i) & 1) != 0 467 { 468 Type *Ty = 0; 469 470 // Look for an appropriate type: 471 // - The type of Idx if the magic fits 472 // - The smallest fitting legal type if we have a DataLayout 473 // - Default to i32 474 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) 475 Ty = Idx->getType(); 476 else if (TD) 477 Ty = TD->getSmallestLegalIntType(Init->getContext(), ArrayElementCount); 478 else if (ArrayElementCount <= 32) 479 Ty = Type::getInt32Ty(Init->getContext()); 480 481 if (Ty != 0) { 482 Value *V = Builder->CreateIntCast(Idx, Ty, false); 483 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 484 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); 485 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 486 } 487 } 488 489 return 0; 490 } 491 492 493 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare 494 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we 495 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can 496 /// be complex, and scales are involved. The above expression would also be 497 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). 498 /// This later form is less amenable to optimization though, and we are allowed 499 /// to generate the first by knowing that pointer arithmetic doesn't overflow. 500 /// 501 /// If we can't emit an optimized form for this expression, this returns null. 502 /// 503 static Value *EvaluateGEPOffsetExpression(User *GEP, InstCombiner &IC) { 504 DataLayout &TD = *IC.getDataLayout(); 505 gep_type_iterator GTI = gep_type_begin(GEP); 506 507 // Check to see if this gep only has a single variable index. If so, and if 508 // any constant indices are a multiple of its scale, then we can compute this 509 // in terms of the scale of the variable index. For example, if the GEP 510 // implies an offset of "12 + i*4", then we can codegen this as "3 + i", 511 // because the expression will cross zero at the same point. 512 unsigned i, e = GEP->getNumOperands(); 513 int64_t Offset = 0; 514 for (i = 1; i != e; ++i, ++GTI) { 515 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 516 // Compute the aggregate offset of constant indices. 517 if (CI->isZero()) continue; 518 519 // Handle a struct index, which adds its field offset to the pointer. 520 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 521 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 522 } else { 523 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 524 Offset += Size*CI->getSExtValue(); 525 } 526 } else { 527 // Found our variable index. 528 break; 529 } 530 } 531 532 // If there are no variable indices, we must have a constant offset, just 533 // evaluate it the general way. 534 if (i == e) return 0; 535 536 Value *VariableIdx = GEP->getOperand(i); 537 // Determine the scale factor of the variable element. For example, this is 538 // 4 if the variable index is into an array of i32. 539 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType()); 540 541 // Verify that there are no other variable indices. If so, emit the hard way. 542 for (++i, ++GTI; i != e; ++i, ++GTI) { 543 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); 544 if (!CI) return 0; 545 546 // Compute the aggregate offset of constant indices. 547 if (CI->isZero()) continue; 548 549 // Handle a struct index, which adds its field offset to the pointer. 550 if (StructType *STy = dyn_cast<StructType>(*GTI)) { 551 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 552 } else { 553 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()); 554 Offset += Size*CI->getSExtValue(); 555 } 556 } 557 558 // Okay, we know we have a single variable index, which must be a 559 // pointer/array/vector index. If there is no offset, life is simple, return 560 // the index. 561 unsigned IntPtrWidth = TD.getPointerSizeInBits(); 562 if (Offset == 0) { 563 // Cast to intptrty in case a truncation occurs. If an extension is needed, 564 // we don't need to bother extending: the extension won't affect where the 565 // computation crosses zero. 566 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) { 567 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext()); 568 VariableIdx = IC.Builder->CreateTrunc(VariableIdx, IntPtrTy); 569 } 570 return VariableIdx; 571 } 572 573 // Otherwise, there is an index. The computation we will do will be modulo 574 // the pointer size, so get it. 575 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth); 576 577 Offset &= PtrSizeMask; 578 VariableScale &= PtrSizeMask; 579 580 // To do this transformation, any constant index must be a multiple of the 581 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", 582 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a 583 // multiple of the variable scale. 584 int64_t NewOffs = Offset / (int64_t)VariableScale; 585 if (Offset != NewOffs*(int64_t)VariableScale) 586 return 0; 587 588 // Okay, we can do this evaluation. Start by converting the index to intptr. 589 Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext()); 590 if (VariableIdx->getType() != IntPtrTy) 591 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy, 592 true /*Signed*/); 593 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 594 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset"); 595 } 596 597 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something 598 /// else. At this point we know that the GEP is on the LHS of the comparison. 599 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 600 ICmpInst::Predicate Cond, 601 Instruction &I) { 602 // Don't transform signed compares of GEPs into index compares. Even if the 603 // GEP is inbounds, the final add of the base pointer can have signed overflow 604 // and would change the result of the icmp. 605 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be 606 // the maximum signed value for the pointer type. 607 if (ICmpInst::isSigned(Cond)) 608 return 0; 609 610 // Look through bitcasts. 611 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS)) 612 RHS = BCI->getOperand(0); 613 614 Value *PtrBase = GEPLHS->getOperand(0); 615 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) { 616 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 617 // This transformation (ignoring the base and scales) is valid because we 618 // know pointers can't overflow since the gep is inbounds. See if we can 619 // output an optimized form. 620 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, *this); 621 622 // If not, synthesize the offset the hard way. 623 if (Offset == 0) 624 Offset = EmitGEPOffset(GEPLHS); 625 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 626 Constant::getNullValue(Offset->getType())); 627 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 628 // If the base pointers are different, but the indices are the same, just 629 // compare the base pointer. 630 if (PtrBase != GEPRHS->getOperand(0)) { 631 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); 632 IndicesTheSame &= GEPLHS->getOperand(0)->getType() == 633 GEPRHS->getOperand(0)->getType(); 634 if (IndicesTheSame) 635 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 636 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 637 IndicesTheSame = false; 638 break; 639 } 640 641 // If all indices are the same, just compare the base pointers. 642 if (IndicesTheSame) 643 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 644 645 // If we're comparing GEPs with two base pointers that only differ in type 646 // and both GEPs have only constant indices or just one use, then fold 647 // the compare with the adjusted indices. 648 if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() && 649 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && 650 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && 651 PtrBase->stripPointerCasts() == 652 GEPRHS->getOperand(0)->stripPointerCasts()) { 653 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond), 654 EmitGEPOffset(GEPLHS), 655 EmitGEPOffset(GEPRHS)); 656 return ReplaceInstUsesWith(I, Cmp); 657 } 658 659 // Otherwise, the base pointers are different and the indices are 660 // different, bail out. 661 return 0; 662 } 663 664 // If one of the GEPs has all zero indices, recurse. 665 bool AllZeros = true; 666 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 667 if (!isa<Constant>(GEPLHS->getOperand(i)) || 668 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) { 669 AllZeros = false; 670 break; 671 } 672 if (AllZeros) 673 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 674 ICmpInst::getSwappedPredicate(Cond), I); 675 676 // If the other GEP has all zero indices, recurse. 677 AllZeros = true; 678 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 679 if (!isa<Constant>(GEPRHS->getOperand(i)) || 680 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) { 681 AllZeros = false; 682 break; 683 } 684 if (AllZeros) 685 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 686 687 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); 688 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { 689 // If the GEPs only differ by one index, compare it. 690 unsigned NumDifferences = 0; // Keep track of # differences. 691 unsigned DiffOperand = 0; // The operand that differs. 692 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 693 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 694 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != 695 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { 696 // Irreconcilable differences. 697 NumDifferences = 2; 698 break; 699 } else { 700 if (NumDifferences++) break; 701 DiffOperand = i; 702 } 703 } 704 705 if (NumDifferences == 0) // SAME GEP? 706 return ReplaceInstUsesWith(I, // No comparison is needed here. 707 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond))); 708 709 else if (NumDifferences == 1 && GEPsInBounds) { 710 Value *LHSV = GEPLHS->getOperand(DiffOperand); 711 Value *RHSV = GEPRHS->getOperand(DiffOperand); 712 // Make sure we do a signed comparison here. 713 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 714 } 715 } 716 717 // Only lower this if the icmp is the only user of the GEP or if we expect 718 // the result to fold to a constant! 719 if (TD && 720 GEPsInBounds && 721 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 722 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 723 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 724 Value *L = EmitGEPOffset(GEPLHS); 725 Value *R = EmitGEPOffset(GEPRHS); 726 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 727 } 728 } 729 return 0; 730 } 731 732 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X". 733 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI, 734 Value *X, ConstantInt *CI, 735 ICmpInst::Predicate Pred, 736 Value *TheAdd) { 737 // If we have X+0, exit early (simplifying logic below) and let it get folded 738 // elsewhere. icmp X+0, X -> icmp X, X 739 if (CI->isZero()) { 740 bool isTrue = ICmpInst::isTrueWhenEqual(Pred); 741 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue)); 742 } 743 744 // (X+4) == X -> false. 745 if (Pred == ICmpInst::ICMP_EQ) 746 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 747 748 // (X+4) != X -> true. 749 if (Pred == ICmpInst::ICMP_NE) 750 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 751 752 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 753 // so the values can never be equal. Similarly for all other "or equals" 754 // operators. 755 756 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 757 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 758 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 759 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 760 Value *R = 761 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI); 762 return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 763 } 764 765 // (X+1) >u X --> X <u (0-1) --> X != 255 766 // (X+2) >u X --> X <u (0-2) --> X <u 254 767 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 768 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) 769 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI)); 770 771 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits(); 772 ConstantInt *SMax = ConstantInt::get(X->getContext(), 773 APInt::getSignedMaxValue(BitWidth)); 774 775 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 776 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 777 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 778 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 779 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 780 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 781 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 782 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI)); 783 784 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 785 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 786 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 787 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 788 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 789 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 790 791 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 792 Constant *C = Builder->getInt(CI->getValue()-1); 793 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C)); 794 } 795 796 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS 797 /// and CmpRHS are both known to be integer constants. 798 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI, 799 ConstantInt *DivRHS) { 800 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1)); 801 const APInt &CmpRHSV = CmpRHS->getValue(); 802 803 // FIXME: If the operand types don't match the type of the divide 804 // then don't attempt this transform. The code below doesn't have the 805 // logic to deal with a signed divide and an unsigned compare (and 806 // vice versa). This is because (x /s C1) <s C2 produces different 807 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even 808 // (x /u C1) <u C2. Simply casting the operands and result won't 809 // work. :( The if statement below tests that condition and bails 810 // if it finds it. 811 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv; 812 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned()) 813 return 0; 814 if (DivRHS->isZero()) 815 return 0; // The ProdOV computation fails on divide by zero. 816 if (DivIsSigned && DivRHS->isAllOnesValue()) 817 return 0; // The overflow computation also screws up here 818 if (DivRHS->isOne()) { 819 // This eliminates some funny cases with INT_MIN. 820 ICI.setOperand(0, DivI->getOperand(0)); // X/1 == X. 821 return &ICI; 822 } 823 824 // Compute Prod = CI * DivRHS. We are essentially solving an equation 825 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 826 // C2 (CI). By solving for X we can turn this into a range check 827 // instead of computing a divide. 828 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS); 829 830 // Determine if the product overflows by seeing if the product is 831 // not equal to the divide. Make sure we do the same kind of divide 832 // as in the LHS instruction that we're folding. 833 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) : 834 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; 835 836 // Get the ICmp opcode 837 ICmpInst::Predicate Pred = ICI.getPredicate(); 838 839 /// If the division is known to be exact, then there is no remainder from the 840 /// divide, so the covered range size is unit, otherwise it is the divisor. 841 ConstantInt *RangeSize = DivI->isExact() ? getOne(Prod) : DivRHS; 842 843 // Figure out the interval that is being checked. For example, a comparison 844 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 845 // Compute this interval based on the constants involved and the signedness of 846 // the compare/divide. This computes a half-open interval, keeping track of 847 // whether either value in the interval overflows. After analysis each 848 // overflow variable is set to 0 if it's corresponding bound variable is valid 849 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 850 int LoOverflow = 0, HiOverflow = 0; 851 Constant *LoBound = 0, *HiBound = 0; 852 853 if (!DivIsSigned) { // udiv 854 // e.g. X/5 op 3 --> [15, 20) 855 LoBound = Prod; 856 HiOverflow = LoOverflow = ProdOV; 857 if (!HiOverflow) { 858 // If this is not an exact divide, then many values in the range collapse 859 // to the same result value. 860 HiOverflow = AddWithOverflow(HiBound, LoBound, RangeSize, false); 861 } 862 863 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0. 864 if (CmpRHSV == 0) { // (X / pos) op 0 865 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 866 LoBound = ConstantExpr::getNeg(SubOne(RangeSize)); 867 HiBound = RangeSize; 868 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos 869 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 870 HiOverflow = LoOverflow = ProdOV; 871 if (!HiOverflow) 872 HiOverflow = AddWithOverflow(HiBound, Prod, RangeSize, true); 873 } else { // (X / pos) op neg 874 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 875 HiBound = AddOne(Prod); 876 LoOverflow = HiOverflow = ProdOV ? -1 : 0; 877 if (!LoOverflow) { 878 ConstantInt *DivNeg =cast<ConstantInt>(ConstantExpr::getNeg(RangeSize)); 879 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 880 } 881 } 882 } else if (DivRHS->isNegative()) { // Divisor is < 0. 883 if (DivI->isExact()) 884 RangeSize = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize)); 885 if (CmpRHSV == 0) { // (X / neg) op 0 886 // e.g. X/-5 op 0 --> [-4, 5) 887 LoBound = AddOne(RangeSize); 888 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(RangeSize)); 889 if (HiBound == DivRHS) { // -INTMIN = INTMIN 890 HiOverflow = 1; // [INTMIN+1, overflow) 891 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN 892 } 893 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos 894 // e.g. X/-5 op 3 --> [-19, -14) 895 HiBound = AddOne(Prod); 896 HiOverflow = LoOverflow = ProdOV ? -1 : 0; 897 if (!LoOverflow) 898 LoOverflow = AddWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; 899 } else { // (X / neg) op neg 900 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 901 LoOverflow = HiOverflow = ProdOV; 902 if (!HiOverflow) 903 HiOverflow = SubWithOverflow(HiBound, Prod, RangeSize, true); 904 } 905 906 // Dividing by a negative swaps the condition. LT <-> GT 907 Pred = ICmpInst::getSwappedPredicate(Pred); 908 } 909 910 Value *X = DivI->getOperand(0); 911 switch (Pred) { 912 default: llvm_unreachable("Unhandled icmp opcode!"); 913 case ICmpInst::ICMP_EQ: 914 if (LoOverflow && HiOverflow) 915 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 916 if (HiOverflow) 917 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 918 ICmpInst::ICMP_UGE, X, LoBound); 919 if (LoOverflow) 920 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 921 ICmpInst::ICMP_ULT, X, HiBound); 922 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound, 923 DivIsSigned, true)); 924 case ICmpInst::ICMP_NE: 925 if (LoOverflow && HiOverflow) 926 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 927 if (HiOverflow) 928 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 929 ICmpInst::ICMP_ULT, X, LoBound); 930 if (LoOverflow) 931 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 932 ICmpInst::ICMP_UGE, X, HiBound); 933 return ReplaceInstUsesWith(ICI, InsertRangeTest(X, LoBound, HiBound, 934 DivIsSigned, false)); 935 case ICmpInst::ICMP_ULT: 936 case ICmpInst::ICMP_SLT: 937 if (LoOverflow == +1) // Low bound is greater than input range. 938 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 939 if (LoOverflow == -1) // Low bound is less than input range. 940 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 941 return new ICmpInst(Pred, X, LoBound); 942 case ICmpInst::ICMP_UGT: 943 case ICmpInst::ICMP_SGT: 944 if (HiOverflow == +1) // High bound greater than input range. 945 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 946 if (HiOverflow == -1) // High bound less than input range. 947 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 948 if (Pred == ICmpInst::ICMP_UGT) 949 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); 950 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); 951 } 952 } 953 954 /// FoldICmpShrCst - Handle "icmp(([al]shr X, cst1), cst2)". 955 Instruction *InstCombiner::FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *Shr, 956 ConstantInt *ShAmt) { 957 const APInt &CmpRHSV = cast<ConstantInt>(ICI.getOperand(1))->getValue(); 958 959 // Check that the shift amount is in range. If not, don't perform 960 // undefined shifts. When the shift is visited it will be 961 // simplified. 962 uint32_t TypeBits = CmpRHSV.getBitWidth(); 963 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); 964 if (ShAmtVal >= TypeBits || ShAmtVal == 0) 965 return 0; 966 967 if (!ICI.isEquality()) { 968 // If we have an unsigned comparison and an ashr, we can't simplify this. 969 // Similarly for signed comparisons with lshr. 970 if (ICI.isSigned() != (Shr->getOpcode() == Instruction::AShr)) 971 return 0; 972 973 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv 974 // by a power of 2. Since we already have logic to simplify these, 975 // transform to div and then simplify the resultant comparison. 976 if (Shr->getOpcode() == Instruction::AShr && 977 (!Shr->isExact() || ShAmtVal == TypeBits - 1)) 978 return 0; 979 980 // Revisit the shift (to delete it). 981 Worklist.Add(Shr); 982 983 Constant *DivCst = 984 ConstantInt::get(Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal)); 985 986 Value *Tmp = 987 Shr->getOpcode() == Instruction::AShr ? 988 Builder->CreateSDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()) : 989 Builder->CreateUDiv(Shr->getOperand(0), DivCst, "", Shr->isExact()); 990 991 ICI.setOperand(0, Tmp); 992 993 // If the builder folded the binop, just return it. 994 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp); 995 if (TheDiv == 0) 996 return &ICI; 997 998 // Otherwise, fold this div/compare. 999 assert(TheDiv->getOpcode() == Instruction::SDiv || 1000 TheDiv->getOpcode() == Instruction::UDiv); 1001 1002 Instruction *Res = FoldICmpDivCst(ICI, TheDiv, cast<ConstantInt>(DivCst)); 1003 assert(Res && "This div/cst should have folded!"); 1004 return Res; 1005 } 1006 1007 1008 // If we are comparing against bits always shifted out, the 1009 // comparison cannot succeed. 1010 APInt Comp = CmpRHSV << ShAmtVal; 1011 ConstantInt *ShiftedCmpRHS = Builder->getInt(Comp); 1012 if (Shr->getOpcode() == Instruction::LShr) 1013 Comp = Comp.lshr(ShAmtVal); 1014 else 1015 Comp = Comp.ashr(ShAmtVal); 1016 1017 if (Comp != CmpRHSV) { // Comparing against a bit that we know is zero. 1018 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1019 Constant *Cst = Builder->getInt1(IsICMP_NE); 1020 return ReplaceInstUsesWith(ICI, Cst); 1021 } 1022 1023 // Otherwise, check to see if the bits shifted out are known to be zero. 1024 // If so, we can compare against the unshifted value: 1025 // (X & 4) >> 1 == 2 --> (X & 4) == 4. 1026 if (Shr->hasOneUse() && Shr->isExact()) 1027 return new ICmpInst(ICI.getPredicate(), Shr->getOperand(0), ShiftedCmpRHS); 1028 1029 if (Shr->hasOneUse()) { 1030 // Otherwise strength reduce the shift into an and. 1031 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 1032 Constant *Mask = Builder->getInt(Val); 1033 1034 Value *And = Builder->CreateAnd(Shr->getOperand(0), 1035 Mask, Shr->getName()+".mask"); 1036 return new ICmpInst(ICI.getPredicate(), And, ShiftedCmpRHS); 1037 } 1038 return 0; 1039 } 1040 1041 1042 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)". 1043 /// 1044 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI, 1045 Instruction *LHSI, 1046 ConstantInt *RHS) { 1047 const APInt &RHSV = RHS->getValue(); 1048 1049 switch (LHSI->getOpcode()) { 1050 case Instruction::Trunc: 1051 if (ICI.isEquality() && LHSI->hasOneUse()) { 1052 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 1053 // of the high bits truncated out of x are known. 1054 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(), 1055 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits(); 1056 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); 1057 ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne); 1058 1059 // If all the high bits are known, we can do this xform. 1060 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) { 1061 // Pull in the high bits from known-ones set. 1062 APInt NewRHS = RHS->getValue().zext(SrcBits); 1063 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits-DstBits); 1064 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 1065 Builder->getInt(NewRHS)); 1066 } 1067 } 1068 break; 1069 1070 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI) 1071 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) { 1072 // If this is a comparison that tests the signbit (X < 0) or (x > -1), 1073 // fold the xor. 1074 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) || 1075 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) { 1076 Value *CompareVal = LHSI->getOperand(0); 1077 1078 // If the sign bit of the XorCST is not set, there is no change to 1079 // the operation, just stop using the Xor. 1080 if (!XorCST->isNegative()) { 1081 ICI.setOperand(0, CompareVal); 1082 Worklist.Add(LHSI); 1083 return &ICI; 1084 } 1085 1086 // Was the old condition true if the operand is positive? 1087 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT; 1088 1089 // If so, the new one isn't. 1090 isTrueIfPositive ^= true; 1091 1092 if (isTrueIfPositive) 1093 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, 1094 SubOne(RHS)); 1095 else 1096 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, 1097 AddOne(RHS)); 1098 } 1099 1100 if (LHSI->hasOneUse()) { 1101 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit)) 1102 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) { 1103 const APInt &SignBit = XorCST->getValue(); 1104 ICmpInst::Predicate Pred = ICI.isSigned() 1105 ? ICI.getUnsignedPredicate() 1106 : ICI.getSignedPredicate(); 1107 return new ICmpInst(Pred, LHSI->getOperand(0), 1108 Builder->getInt(RHSV ^ SignBit)); 1109 } 1110 1111 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A) 1112 if (!ICI.isEquality() && XorCST->isMaxValue(true)) { 1113 const APInt &NotSignBit = XorCST->getValue(); 1114 ICmpInst::Predicate Pred = ICI.isSigned() 1115 ? ICI.getUnsignedPredicate() 1116 : ICI.getSignedPredicate(); 1117 Pred = ICI.getSwappedPredicate(Pred); 1118 return new ICmpInst(Pred, LHSI->getOperand(0), 1119 Builder->getInt(RHSV ^ NotSignBit)); 1120 } 1121 } 1122 1123 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C) 1124 // iff -C is a power of 2 1125 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && 1126 XorCST->getValue() == ~RHSV && (RHSV + 1).isPowerOf2()) 1127 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), XorCST); 1128 1129 // (icmp ult (xor X, C), -C) -> (icmp uge X, C) 1130 // iff -C is a power of 2 1131 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && 1132 XorCST->getValue() == -RHSV && RHSV.isPowerOf2()) 1133 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), XorCST); 1134 } 1135 break; 1136 case Instruction::And: // (icmp pred (and X, AndCST), RHS) 1137 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) && 1138 LHSI->getOperand(0)->hasOneUse()) { 1139 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1)); 1140 1141 // If the LHS is an AND of a truncating cast, we can widen the 1142 // and/compare to be the input width without changing the value 1143 // produced, eliminating a cast. 1144 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) { 1145 // We can do this transformation if either the AND constant does not 1146 // have its sign bit set or if it is an equality comparison. 1147 // Extending a relational comparison when we're checking the sign 1148 // bit would not work. 1149 if (ICI.isEquality() || 1150 (!AndCST->isNegative() && RHSV.isNonNegative())) { 1151 Value *NewAnd = 1152 Builder->CreateAnd(Cast->getOperand(0), 1153 ConstantExpr::getZExt(AndCST, Cast->getSrcTy())); 1154 NewAnd->takeName(LHSI); 1155 return new ICmpInst(ICI.getPredicate(), NewAnd, 1156 ConstantExpr::getZExt(RHS, Cast->getSrcTy())); 1157 } 1158 } 1159 1160 // If the LHS is an AND of a zext, and we have an equality compare, we can 1161 // shrink the and/compare to the smaller type, eliminating the cast. 1162 if (ZExtInst *Cast = dyn_cast<ZExtInst>(LHSI->getOperand(0))) { 1163 IntegerType *Ty = cast<IntegerType>(Cast->getSrcTy()); 1164 // Make sure we don't compare the upper bits, SimplifyDemandedBits 1165 // should fold the icmp to true/false in that case. 1166 if (ICI.isEquality() && RHSV.getActiveBits() <= Ty->getBitWidth()) { 1167 Value *NewAnd = 1168 Builder->CreateAnd(Cast->getOperand(0), 1169 ConstantExpr::getTrunc(AndCST, Ty)); 1170 NewAnd->takeName(LHSI); 1171 return new ICmpInst(ICI.getPredicate(), NewAnd, 1172 ConstantExpr::getTrunc(RHS, Ty)); 1173 } 1174 } 1175 1176 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare 1177 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This 1178 // happens a LOT in code produced by the C front-end, for bitfield 1179 // access. 1180 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0)); 1181 if (Shift && !Shift->isShift()) 1182 Shift = 0; 1183 1184 ConstantInt *ShAmt; 1185 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0; 1186 Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift. 1187 Type *AndTy = AndCST->getType(); // Type of the and. 1188 1189 // We can fold this as long as we can't shift unknown bits 1190 // into the mask. This can only happen with signed shift 1191 // rights, as they sign-extend. 1192 if (ShAmt) { 1193 bool CanFold = Shift->isLogicalShift(); 1194 if (!CanFold) { 1195 // To test for the bad case of the signed shr, see if any 1196 // of the bits shifted in could be tested after the mask. 1197 uint32_t TyBits = Ty->getPrimitiveSizeInBits(); 1198 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits); 1199 1200 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits(); 1201 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 1202 AndCST->getValue()) == 0) 1203 CanFold = true; 1204 } 1205 1206 if (CanFold) { 1207 Constant *NewCst; 1208 if (Shift->getOpcode() == Instruction::Shl) 1209 NewCst = ConstantExpr::getLShr(RHS, ShAmt); 1210 else 1211 NewCst = ConstantExpr::getShl(RHS, ShAmt); 1212 1213 // Check to see if we are shifting out any of the bits being 1214 // compared. 1215 if (ConstantExpr::get(Shift->getOpcode(), 1216 NewCst, ShAmt) != RHS) { 1217 // If we shifted bits out, the fold is not going to work out. 1218 // As a special case, check to see if this means that the 1219 // result is always true or false now. 1220 if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1221 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 1222 if (ICI.getPredicate() == ICmpInst::ICMP_NE) 1223 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 1224 } else { 1225 ICI.setOperand(1, NewCst); 1226 Constant *NewAndCST; 1227 if (Shift->getOpcode() == Instruction::Shl) 1228 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt); 1229 else 1230 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt); 1231 LHSI->setOperand(1, NewAndCST); 1232 LHSI->setOperand(0, Shift->getOperand(0)); 1233 Worklist.Add(Shift); // Shift is dead. 1234 return &ICI; 1235 } 1236 } 1237 } 1238 1239 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is 1240 // preferable because it allows the C<<Y expression to be hoisted out 1241 // of a loop if Y is invariant and X is not. 1242 if (Shift && Shift->hasOneUse() && RHSV == 0 && 1243 ICI.isEquality() && !Shift->isArithmeticShift() && 1244 !isa<Constant>(Shift->getOperand(0))) { 1245 // Compute C << Y. 1246 Value *NS; 1247 if (Shift->getOpcode() == Instruction::LShr) { 1248 NS = Builder->CreateShl(AndCST, Shift->getOperand(1)); 1249 } else { 1250 // Insert a logical shift. 1251 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1)); 1252 } 1253 1254 // Compute X & (C << Y). 1255 Value *NewAnd = 1256 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName()); 1257 1258 ICI.setOperand(0, NewAnd); 1259 return &ICI; 1260 } 1261 1262 // Replace ((X & AndCST) > RHSV) with ((X & AndCST) != 0), if any 1263 // bit set in (X & AndCST) will produce a result greater than RHSV. 1264 if (ICI.getPredicate() == ICmpInst::ICMP_UGT) { 1265 unsigned NTZ = AndCST->getValue().countTrailingZeros(); 1266 if ((NTZ < AndCST->getBitWidth()) && 1267 APInt::getOneBitSet(AndCST->getBitWidth(), NTZ).ugt(RHSV)) 1268 return new ICmpInst(ICmpInst::ICMP_NE, LHSI, 1269 Constant::getNullValue(RHS->getType())); 1270 } 1271 } 1272 1273 // Try to optimize things like "A[i]&42 == 0" to index computations. 1274 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) { 1275 if (GetElementPtrInst *GEP = 1276 dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1277 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1278 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1279 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) { 1280 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1)); 1281 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C)) 1282 return Res; 1283 } 1284 } 1285 1286 // X & -C == -C -> X > u ~C 1287 // X & -C != -C -> X <= u ~C 1288 // iff C is a power of 2 1289 if (ICI.isEquality() && RHS == LHSI->getOperand(1) && (-RHSV).isPowerOf2()) 1290 return new ICmpInst( 1291 ICI.getPredicate() == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT 1292 : ICmpInst::ICMP_ULE, 1293 LHSI->getOperand(0), SubOne(RHS)); 1294 break; 1295 1296 case Instruction::Or: { 1297 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse()) 1298 break; 1299 Value *P, *Q; 1300 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1301 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1302 // -> and (icmp eq P, null), (icmp eq Q, null). 1303 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P, 1304 Constant::getNullValue(P->getType())); 1305 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q, 1306 Constant::getNullValue(Q->getType())); 1307 Instruction *Op; 1308 if (ICI.getPredicate() == ICmpInst::ICMP_EQ) 1309 Op = BinaryOperator::CreateAnd(ICIP, ICIQ); 1310 else 1311 Op = BinaryOperator::CreateOr(ICIP, ICIQ); 1312 return Op; 1313 } 1314 break; 1315 } 1316 1317 case Instruction::Mul: { // (icmp pred (mul X, Val), CI) 1318 ConstantInt *Val = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1319 if (!Val) break; 1320 1321 // If this is a signed comparison to 0 and the mul is sign preserving, 1322 // use the mul LHS operand instead. 1323 ICmpInst::Predicate pred = ICI.getPredicate(); 1324 if (isSignTest(pred, RHS) && !Val->isZero() && 1325 cast<BinaryOperator>(LHSI)->hasNoSignedWrap()) 1326 return new ICmpInst(Val->isNegative() ? 1327 ICmpInst::getSwappedPredicate(pred) : pred, 1328 LHSI->getOperand(0), 1329 Constant::getNullValue(RHS->getType())); 1330 1331 break; 1332 } 1333 1334 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI) 1335 uint32_t TypeBits = RHSV.getBitWidth(); 1336 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1337 if (!ShAmt) { 1338 Value *X; 1339 // (1 << X) pred P2 -> X pred Log2(P2) 1340 if (match(LHSI, m_Shl(m_One(), m_Value(X)))) { 1341 bool RHSVIsPowerOf2 = RHSV.isPowerOf2(); 1342 ICmpInst::Predicate Pred = ICI.getPredicate(); 1343 if (ICI.isUnsigned()) { 1344 if (!RHSVIsPowerOf2) { 1345 // (1 << X) < 30 -> X <= 4 1346 // (1 << X) <= 30 -> X <= 4 1347 // (1 << X) >= 30 -> X > 4 1348 // (1 << X) > 30 -> X > 4 1349 if (Pred == ICmpInst::ICMP_ULT) 1350 Pred = ICmpInst::ICMP_ULE; 1351 else if (Pred == ICmpInst::ICMP_UGE) 1352 Pred = ICmpInst::ICMP_UGT; 1353 } 1354 unsigned RHSLog2 = RHSV.logBase2(); 1355 1356 // (1 << X) >= 2147483648 -> X >= 31 -> X == 31 1357 // (1 << X) > 2147483648 -> X > 31 -> false 1358 // (1 << X) <= 2147483648 -> X <= 31 -> true 1359 // (1 << X) < 2147483648 -> X < 31 -> X != 31 1360 if (RHSLog2 == TypeBits-1) { 1361 if (Pred == ICmpInst::ICMP_UGE) 1362 Pred = ICmpInst::ICMP_EQ; 1363 else if (Pred == ICmpInst::ICMP_UGT) 1364 return ReplaceInstUsesWith(ICI, Builder->getFalse()); 1365 else if (Pred == ICmpInst::ICMP_ULE) 1366 return ReplaceInstUsesWith(ICI, Builder->getTrue()); 1367 else if (Pred == ICmpInst::ICMP_ULT) 1368 Pred = ICmpInst::ICMP_NE; 1369 } 1370 1371 return new ICmpInst(Pred, X, 1372 ConstantInt::get(RHS->getType(), RHSLog2)); 1373 } else if (ICI.isSigned()) { 1374 if (RHSV.isAllOnesValue()) { 1375 // (1 << X) <= -1 -> X == 31 1376 if (Pred == ICmpInst::ICMP_SLE) 1377 return new ICmpInst(ICmpInst::ICMP_EQ, X, 1378 ConstantInt::get(RHS->getType(), TypeBits-1)); 1379 1380 // (1 << X) > -1 -> X != 31 1381 if (Pred == ICmpInst::ICMP_SGT) 1382 return new ICmpInst(ICmpInst::ICMP_NE, X, 1383 ConstantInt::get(RHS->getType(), TypeBits-1)); 1384 } else if (!RHSV) { 1385 // (1 << X) < 0 -> X == 31 1386 // (1 << X) <= 0 -> X == 31 1387 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1388 return new ICmpInst(ICmpInst::ICMP_EQ, X, 1389 ConstantInt::get(RHS->getType(), TypeBits-1)); 1390 1391 // (1 << X) >= 0 -> X != 31 1392 // (1 << X) > 0 -> X != 31 1393 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) 1394 return new ICmpInst(ICmpInst::ICMP_NE, X, 1395 ConstantInt::get(RHS->getType(), TypeBits-1)); 1396 } 1397 } else if (ICI.isEquality()) { 1398 if (RHSVIsPowerOf2) 1399 return new ICmpInst( 1400 Pred, X, ConstantInt::get(RHS->getType(), RHSV.logBase2())); 1401 1402 return ReplaceInstUsesWith( 1403 ICI, Pred == ICmpInst::ICMP_EQ ? Builder->getFalse() 1404 : Builder->getTrue()); 1405 } 1406 } 1407 break; 1408 } 1409 1410 // Check that the shift amount is in range. If not, don't perform 1411 // undefined shifts. When the shift is visited it will be 1412 // simplified. 1413 if (ShAmt->uge(TypeBits)) 1414 break; 1415 1416 if (ICI.isEquality()) { 1417 // If we are comparing against bits always shifted out, the 1418 // comparison cannot succeed. 1419 Constant *Comp = 1420 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), 1421 ShAmt); 1422 if (Comp != RHS) {// Comparing against a bit that we know is zero. 1423 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1424 Constant *Cst = Builder->getInt1(IsICMP_NE); 1425 return ReplaceInstUsesWith(ICI, Cst); 1426 } 1427 1428 // If the shift is NUW, then it is just shifting out zeros, no need for an 1429 // AND. 1430 if (cast<BinaryOperator>(LHSI)->hasNoUnsignedWrap()) 1431 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 1432 ConstantExpr::getLShr(RHS, ShAmt)); 1433 1434 // If the shift is NSW and we compare to 0, then it is just shifting out 1435 // sign bits, no need for an AND either. 1436 if (cast<BinaryOperator>(LHSI)->hasNoSignedWrap() && RHSV == 0) 1437 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0), 1438 ConstantExpr::getLShr(RHS, ShAmt)); 1439 1440 if (LHSI->hasOneUse()) { 1441 // Otherwise strength reduce the shift into an and. 1442 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits); 1443 Constant *Mask = Builder->getInt(APInt::getLowBitsSet(TypeBits, 1444 TypeBits - ShAmtVal)); 1445 1446 Value *And = 1447 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask"); 1448 return new ICmpInst(ICI.getPredicate(), And, 1449 ConstantExpr::getLShr(RHS, ShAmt)); 1450 } 1451 } 1452 1453 // If this is a signed comparison to 0 and the shift is sign preserving, 1454 // use the shift LHS operand instead. 1455 ICmpInst::Predicate pred = ICI.getPredicate(); 1456 if (isSignTest(pred, RHS) && 1457 cast<BinaryOperator>(LHSI)->hasNoSignedWrap()) 1458 return new ICmpInst(pred, 1459 LHSI->getOperand(0), 1460 Constant::getNullValue(RHS->getType())); 1461 1462 // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 1463 bool TrueIfSigned = false; 1464 if (LHSI->hasOneUse() && 1465 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) { 1466 // (X << 31) <s 0 --> (X&1) != 0 1467 Constant *Mask = ConstantInt::get(LHSI->getOperand(0)->getType(), 1468 APInt::getOneBitSet(TypeBits, 1469 TypeBits-ShAmt->getZExtValue()-1)); 1470 Value *And = 1471 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask"); 1472 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 1473 And, Constant::getNullValue(And->getType())); 1474 } 1475 1476 // Transform (icmp pred iM (shl iM %v, N), CI) 1477 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (CI>>N)) 1478 // Transform the shl to a trunc if (trunc (CI>>N)) has no loss and M-N. 1479 // This enables to get rid of the shift in favor of a trunc which can be 1480 // free on the target. It has the additional benefit of comparing to a 1481 // smaller constant, which will be target friendly. 1482 unsigned Amt = ShAmt->getLimitedValue(TypeBits-1); 1483 if (LHSI->hasOneUse() && 1484 Amt != 0 && RHSV.countTrailingZeros() >= Amt) { 1485 Type *NTy = IntegerType::get(ICI.getContext(), TypeBits - Amt); 1486 Constant *NCI = ConstantExpr::getTrunc( 1487 ConstantExpr::getAShr(RHS, 1488 ConstantInt::get(RHS->getType(), Amt)), 1489 NTy); 1490 return new ICmpInst(ICI.getPredicate(), 1491 Builder->CreateTrunc(LHSI->getOperand(0), NTy), 1492 NCI); 1493 } 1494 1495 break; 1496 } 1497 1498 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI) 1499 case Instruction::AShr: { 1500 // Handle equality comparisons of shift-by-constant. 1501 BinaryOperator *BO = cast<BinaryOperator>(LHSI); 1502 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) { 1503 if (Instruction *Res = FoldICmpShrCst(ICI, BO, ShAmt)) 1504 return Res; 1505 } 1506 1507 // Handle exact shr's. 1508 if (ICI.isEquality() && BO->isExact() && BO->hasOneUse()) { 1509 if (RHSV.isMinValue()) 1510 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), RHS); 1511 } 1512 break; 1513 } 1514 1515 case Instruction::SDiv: 1516 case Instruction::UDiv: 1517 // Fold: icmp pred ([us]div X, C1), C2 -> range test 1518 // Fold this div into the comparison, producing a range check. 1519 // Determine, based on the divide type, what the range is being 1520 // checked. If there is an overflow on the low or high side, remember 1521 // it, otherwise compute the range [low, hi) bounding the new value. 1522 // See: InsertRangeTest above for the kinds of replacements possible. 1523 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) 1524 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI), 1525 DivRHS)) 1526 return R; 1527 break; 1528 1529 case Instruction::Sub: { 1530 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(0)); 1531 if (!LHSC) break; 1532 const APInt &LHSV = LHSC->getValue(); 1533 1534 // C1-X <u C2 -> (X|(C2-1)) == C1 1535 // iff C1 & (C2-1) == C2-1 1536 // C2 is a power of 2 1537 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() && 1538 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == (RHSV - 1)) 1539 return new ICmpInst(ICmpInst::ICMP_EQ, 1540 Builder->CreateOr(LHSI->getOperand(1), RHSV - 1), 1541 LHSC); 1542 1543 // C1-X >u C2 -> (X|C2) != C1 1544 // iff C1 & C2 == C2 1545 // C2+1 is a power of 2 1546 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() && 1547 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == RHSV) 1548 return new ICmpInst(ICmpInst::ICMP_NE, 1549 Builder->CreateOr(LHSI->getOperand(1), RHSV), LHSC); 1550 break; 1551 } 1552 1553 case Instruction::Add: 1554 // Fold: icmp pred (add X, C1), C2 1555 if (!ICI.isEquality()) { 1556 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1)); 1557 if (!LHSC) break; 1558 const APInt &LHSV = LHSC->getValue(); 1559 1560 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV) 1561 .subtract(LHSV); 1562 1563 if (ICI.isSigned()) { 1564 if (CR.getLower().isSignBit()) { 1565 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0), 1566 Builder->getInt(CR.getUpper())); 1567 } else if (CR.getUpper().isSignBit()) { 1568 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0), 1569 Builder->getInt(CR.getLower())); 1570 } 1571 } else { 1572 if (CR.getLower().isMinValue()) { 1573 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0), 1574 Builder->getInt(CR.getUpper())); 1575 } else if (CR.getUpper().isMinValue()) { 1576 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0), 1577 Builder->getInt(CR.getLower())); 1578 } 1579 } 1580 1581 // X-C1 <u C2 -> (X & -C2) == C1 1582 // iff C1 & (C2-1) == 0 1583 // C2 is a power of 2 1584 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && LHSI->hasOneUse() && 1585 RHSV.isPowerOf2() && (LHSV & (RHSV - 1)) == 0) 1586 return new ICmpInst(ICmpInst::ICMP_EQ, 1587 Builder->CreateAnd(LHSI->getOperand(0), -RHSV), 1588 ConstantExpr::getNeg(LHSC)); 1589 1590 // X-C1 >u C2 -> (X & ~C2) != C1 1591 // iff C1 & C2 == 0 1592 // C2+1 is a power of 2 1593 if (ICI.getPredicate() == ICmpInst::ICMP_UGT && LHSI->hasOneUse() && 1594 (RHSV + 1).isPowerOf2() && (LHSV & RHSV) == 0) 1595 return new ICmpInst(ICmpInst::ICMP_NE, 1596 Builder->CreateAnd(LHSI->getOperand(0), ~RHSV), 1597 ConstantExpr::getNeg(LHSC)); 1598 } 1599 break; 1600 } 1601 1602 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS. 1603 if (ICI.isEquality()) { 1604 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE; 1605 1606 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 1607 // the second operand is a constant, simplify a bit. 1608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) { 1609 switch (BO->getOpcode()) { 1610 case Instruction::SRem: 1611 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 1612 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){ 1613 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue(); 1614 if (V.sgt(1) && V.isPowerOf2()) { 1615 Value *NewRem = 1616 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1), 1617 BO->getName()); 1618 return new ICmpInst(ICI.getPredicate(), NewRem, 1619 Constant::getNullValue(BO->getType())); 1620 } 1621 } 1622 break; 1623 case Instruction::Add: 1624 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 1625 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1626 if (BO->hasOneUse()) 1627 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1628 ConstantExpr::getSub(RHS, BOp1C)); 1629 } else if (RHSV == 0) { 1630 // Replace ((add A, B) != 0) with (A != -B) if A or B is 1631 // efficiently invertible, or if the add has just this one use. 1632 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 1633 1634 if (Value *NegVal = dyn_castNegVal(BOp1)) 1635 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal); 1636 if (Value *NegVal = dyn_castNegVal(BOp0)) 1637 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1); 1638 if (BO->hasOneUse()) { 1639 Value *Neg = Builder->CreateNeg(BOp1); 1640 Neg->takeName(BO); 1641 return new ICmpInst(ICI.getPredicate(), BOp0, Neg); 1642 } 1643 } 1644 break; 1645 case Instruction::Xor: 1646 // For the xor case, we can xor two constants together, eliminating 1647 // the explicit xor. 1648 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) { 1649 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1650 ConstantExpr::getXor(RHS, BOC)); 1651 } else if (RHSV == 0) { 1652 // Replace ((xor A, B) != 0) with (A != B) 1653 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1654 BO->getOperand(1)); 1655 } 1656 break; 1657 case Instruction::Sub: 1658 // Replace ((sub A, B) != C) with (B != A-C) if A & C are constants. 1659 if (ConstantInt *BOp0C = dyn_cast<ConstantInt>(BO->getOperand(0))) { 1660 if (BO->hasOneUse()) 1661 return new ICmpInst(ICI.getPredicate(), BO->getOperand(1), 1662 ConstantExpr::getSub(BOp0C, RHS)); 1663 } else if (RHSV == 0) { 1664 // Replace ((sub A, B) != 0) with (A != B) 1665 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1666 BO->getOperand(1)); 1667 } 1668 break; 1669 case Instruction::Or: 1670 // If bits are being or'd in that are not present in the constant we 1671 // are comparing against, then the comparison could never succeed! 1672 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1673 Constant *NotCI = ConstantExpr::getNot(RHS); 1674 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue()) 1675 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE)); 1676 } 1677 break; 1678 1679 case Instruction::And: 1680 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1681 // If bits are being compared against that are and'd out, then the 1682 // comparison can never succeed! 1683 if ((RHSV & ~BOC->getValue()) != 0) 1684 return ReplaceInstUsesWith(ICI, Builder->getInt1(isICMP_NE)); 1685 1686 // If we have ((X & C) == C), turn it into ((X & C) != 0). 1687 if (RHS == BOC && RHSV.isPowerOf2()) 1688 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : 1689 ICmpInst::ICMP_NE, LHSI, 1690 Constant::getNullValue(RHS->getType())); 1691 1692 // Don't perform the following transforms if the AND has multiple uses 1693 if (!BO->hasOneUse()) 1694 break; 1695 1696 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 1697 if (BOC->getValue().isSignBit()) { 1698 Value *X = BO->getOperand(0); 1699 Constant *Zero = Constant::getNullValue(X->getType()); 1700 ICmpInst::Predicate pred = isICMP_NE ? 1701 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 1702 return new ICmpInst(pred, X, Zero); 1703 } 1704 1705 // ((X & ~7) == 0) --> X < 8 1706 if (RHSV == 0 && isHighOnes(BOC)) { 1707 Value *X = BO->getOperand(0); 1708 Constant *NegX = ConstantExpr::getNeg(BOC); 1709 ICmpInst::Predicate pred = isICMP_NE ? 1710 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 1711 return new ICmpInst(pred, X, NegX); 1712 } 1713 } 1714 break; 1715 case Instruction::Mul: 1716 if (RHSV == 0 && BO->hasNoSignedWrap()) { 1717 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) { 1718 // The trivial case (mul X, 0) is handled by InstSimplify 1719 // General case : (mul X, C) != 0 iff X != 0 1720 // (mul X, C) == 0 iff X == 0 1721 if (!BOC->isZero()) 1722 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 1723 Constant::getNullValue(RHS->getType())); 1724 } 1725 } 1726 break; 1727 default: break; 1728 } 1729 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) { 1730 // Handle icmp {eq|ne} <intrinsic>, intcst. 1731 switch (II->getIntrinsicID()) { 1732 case Intrinsic::bswap: 1733 Worklist.Add(II); 1734 ICI.setOperand(0, II->getArgOperand(0)); 1735 ICI.setOperand(1, Builder->getInt(RHSV.byteSwap())); 1736 return &ICI; 1737 case Intrinsic::ctlz: 1738 case Intrinsic::cttz: 1739 // ctz(A) == bitwidth(a) -> A == 0 and likewise for != 1740 if (RHSV == RHS->getType()->getBitWidth()) { 1741 Worklist.Add(II); 1742 ICI.setOperand(0, II->getArgOperand(0)); 1743 ICI.setOperand(1, ConstantInt::get(RHS->getType(), 0)); 1744 return &ICI; 1745 } 1746 break; 1747 case Intrinsic::ctpop: 1748 // popcount(A) == 0 -> A == 0 and likewise for != 1749 if (RHS->isZero()) { 1750 Worklist.Add(II); 1751 ICI.setOperand(0, II->getArgOperand(0)); 1752 ICI.setOperand(1, RHS); 1753 return &ICI; 1754 } 1755 break; 1756 default: 1757 break; 1758 } 1759 } 1760 } 1761 return 0; 1762 } 1763 1764 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst). 1765 /// We only handle extending casts so far. 1766 /// 1767 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) { 1768 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0)); 1769 Value *LHSCIOp = LHSCI->getOperand(0); 1770 Type *SrcTy = LHSCIOp->getType(); 1771 Type *DestTy = LHSCI->getType(); 1772 Value *RHSCIOp; 1773 1774 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 1775 // integer type is the same size as the pointer type. 1776 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt && 1777 TD->getPointerSizeInBits() == 1778 cast<IntegerType>(DestTy)->getBitWidth()) { 1779 Value *RHSOp = 0; 1780 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) { 1781 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); 1782 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) { 1783 RHSOp = RHSC->getOperand(0); 1784 // If the pointer types don't match, insert a bitcast. 1785 if (LHSCIOp->getType() != RHSOp->getType()) 1786 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType()); 1787 } 1788 1789 if (RHSOp) 1790 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp); 1791 } 1792 1793 // The code below only handles extension cast instructions, so far. 1794 // Enforce this. 1795 if (LHSCI->getOpcode() != Instruction::ZExt && 1796 LHSCI->getOpcode() != Instruction::SExt) 1797 return 0; 1798 1799 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; 1800 bool isSignedCmp = ICI.isSigned(); 1801 1802 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) { 1803 // Not an extension from the same type? 1804 RHSCIOp = CI->getOperand(0); 1805 if (RHSCIOp->getType() != LHSCIOp->getType()) 1806 return 0; 1807 1808 // If the signedness of the two casts doesn't agree (i.e. one is a sext 1809 // and the other is a zext), then we can't handle this. 1810 if (CI->getOpcode() != LHSCI->getOpcode()) 1811 return 0; 1812 1813 // Deal with equality cases early. 1814 if (ICI.isEquality()) 1815 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); 1816 1817 // A signed comparison of sign extended values simplifies into a 1818 // signed comparison. 1819 if (isSignedCmp && isSignedExt) 1820 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp); 1821 1822 // The other three cases all fold into an unsigned comparison. 1823 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp); 1824 } 1825 1826 // If we aren't dealing with a constant on the RHS, exit early 1827 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1)); 1828 if (!CI) 1829 return 0; 1830 1831 // Compute the constant that would happen if we truncated to SrcTy then 1832 // reextended to DestTy. 1833 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy); 1834 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), 1835 Res1, DestTy); 1836 1837 // If the re-extended constant didn't change... 1838 if (Res2 == CI) { 1839 // Deal with equality cases early. 1840 if (ICI.isEquality()) 1841 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); 1842 1843 // A signed comparison of sign extended values simplifies into a 1844 // signed comparison. 1845 if (isSignedExt && isSignedCmp) 1846 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1); 1847 1848 // The other three cases all fold into an unsigned comparison. 1849 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1); 1850 } 1851 1852 // The re-extended constant changed so the constant cannot be represented 1853 // in the shorter type. Consequently, we cannot emit a simple comparison. 1854 // All the cases that fold to true or false will have already been handled 1855 // by SimplifyICmpInst, so only deal with the tricky case. 1856 1857 if (isSignedCmp || !isSignedExt) 1858 return 0; 1859 1860 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases 1861 // should have been folded away previously and not enter in here. 1862 1863 // We're performing an unsigned comp with a sign extended value. 1864 // This is true if the input is >= 0. [aka >s -1] 1865 Constant *NegOne = Constant::getAllOnesValue(SrcTy); 1866 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName()); 1867 1868 // Finally, return the value computed. 1869 if (ICI.getPredicate() == ICmpInst::ICMP_ULT) 1870 return ReplaceInstUsesWith(ICI, Result); 1871 1872 assert(ICI.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); 1873 return BinaryOperator::CreateNot(Result); 1874 } 1875 1876 /// ProcessUGT_ADDCST_ADD - The caller has matched a pattern of the form: 1877 /// I = icmp ugt (add (add A, B), CI2), CI1 1878 /// If this is of the form: 1879 /// sum = a + b 1880 /// if (sum+128 >u 255) 1881 /// Then replace it with llvm.sadd.with.overflow.i8. 1882 /// 1883 static Instruction *ProcessUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, 1884 ConstantInt *CI2, ConstantInt *CI1, 1885 InstCombiner &IC) { 1886 // The transformation we're trying to do here is to transform this into an 1887 // llvm.sadd.with.overflow. To do this, we have to replace the original add 1888 // with a narrower add, and discard the add-with-constant that is part of the 1889 // range check (if we can't eliminate it, this isn't profitable). 1890 1891 // In order to eliminate the add-with-constant, the compare can be its only 1892 // use. 1893 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); 1894 if (!AddWithCst->hasOneUse()) return 0; 1895 1896 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. 1897 if (!CI2->getValue().isPowerOf2()) return 0; 1898 unsigned NewWidth = CI2->getValue().countTrailingZeros(); 1899 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) return 0; 1900 1901 // The width of the new add formed is 1 more than the bias. 1902 ++NewWidth; 1903 1904 // Check to see that CI1 is an all-ones value with NewWidth bits. 1905 if (CI1->getBitWidth() == NewWidth || 1906 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) 1907 return 0; 1908 1909 // This is only really a signed overflow check if the inputs have been 1910 // sign-extended; check for that condition. For example, if CI2 is 2^31 and 1911 // the operands of the add are 64 bits wide, we need at least 33 sign bits. 1912 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1; 1913 if (IC.ComputeNumSignBits(A) < NeededSignBits || 1914 IC.ComputeNumSignBits(B) < NeededSignBits) 1915 return 0; 1916 1917 // In order to replace the original add with a narrower 1918 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant 1919 // and truncates that discard the high bits of the add. Verify that this is 1920 // the case. 1921 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); 1922 for (Value::use_iterator UI = OrigAdd->use_begin(), E = OrigAdd->use_end(); 1923 UI != E; ++UI) { 1924 if (*UI == AddWithCst) continue; 1925 1926 // Only accept truncates for now. We would really like a nice recursive 1927 // predicate like SimplifyDemandedBits, but which goes downwards the use-def 1928 // chain to see which bits of a value are actually demanded. If the 1929 // original add had another add which was then immediately truncated, we 1930 // could still do the transformation. 1931 TruncInst *TI = dyn_cast<TruncInst>(*UI); 1932 if (TI == 0 || 1933 TI->getType()->getPrimitiveSizeInBits() > NewWidth) return 0; 1934 } 1935 1936 // If the pattern matches, truncate the inputs to the narrower type and 1937 // use the sadd_with_overflow intrinsic to efficiently compute both the 1938 // result and the overflow bit. 1939 Module *M = I.getParent()->getParent()->getParent(); 1940 1941 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); 1942 Value *F = Intrinsic::getDeclaration(M, Intrinsic::sadd_with_overflow, 1943 NewType); 1944 1945 InstCombiner::BuilderTy *Builder = IC.Builder; 1946 1947 // Put the new code above the original add, in case there are any uses of the 1948 // add between the add and the compare. 1949 Builder->SetInsertPoint(OrigAdd); 1950 1951 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName()+".trunc"); 1952 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName()+".trunc"); 1953 CallInst *Call = Builder->CreateCall2(F, TruncA, TruncB, "sadd"); 1954 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result"); 1955 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType()); 1956 1957 // The inner add was the result of the narrow add, zero extended to the 1958 // wider type. Replace it with the result computed by the intrinsic. 1959 IC.ReplaceInstUsesWith(*OrigAdd, ZExt); 1960 1961 // The original icmp gets replaced with the overflow value. 1962 return ExtractValueInst::Create(Call, 1, "sadd.overflow"); 1963 } 1964 1965 static Instruction *ProcessUAddIdiom(Instruction &I, Value *OrigAddV, 1966 InstCombiner &IC) { 1967 // Don't bother doing this transformation for pointers, don't do it for 1968 // vectors. 1969 if (!isa<IntegerType>(OrigAddV->getType())) return 0; 1970 1971 // If the add is a constant expr, then we don't bother transforming it. 1972 Instruction *OrigAdd = dyn_cast<Instruction>(OrigAddV); 1973 if (OrigAdd == 0) return 0; 1974 1975 Value *LHS = OrigAdd->getOperand(0), *RHS = OrigAdd->getOperand(1); 1976 1977 // Put the new code above the original add, in case there are any uses of the 1978 // add between the add and the compare. 1979 InstCombiner::BuilderTy *Builder = IC.Builder; 1980 Builder->SetInsertPoint(OrigAdd); 1981 1982 Module *M = I.getParent()->getParent()->getParent(); 1983 Type *Ty = LHS->getType(); 1984 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); 1985 CallInst *Call = Builder->CreateCall2(F, LHS, RHS, "uadd"); 1986 Value *Add = Builder->CreateExtractValue(Call, 0); 1987 1988 IC.ReplaceInstUsesWith(*OrigAdd, Add); 1989 1990 // The original icmp gets replaced with the overflow value. 1991 return ExtractValueInst::Create(Call, 1, "uadd.overflow"); 1992 } 1993 1994 // DemandedBitsLHSMask - When performing a comparison against a constant, 1995 // it is possible that not all the bits in the LHS are demanded. This helper 1996 // method computes the mask that IS demanded. 1997 static APInt DemandedBitsLHSMask(ICmpInst &I, 1998 unsigned BitWidth, bool isSignCheck) { 1999 if (isSignCheck) 2000 return APInt::getSignBit(BitWidth); 2001 2002 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1)); 2003 if (!CI) return APInt::getAllOnesValue(BitWidth); 2004 const APInt &RHS = CI->getValue(); 2005 2006 switch (I.getPredicate()) { 2007 // For a UGT comparison, we don't care about any bits that 2008 // correspond to the trailing ones of the comparand. The value of these 2009 // bits doesn't impact the outcome of the comparison, because any value 2010 // greater than the RHS must differ in a bit higher than these due to carry. 2011 case ICmpInst::ICMP_UGT: { 2012 unsigned trailingOnes = RHS.countTrailingOnes(); 2013 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes); 2014 return ~lowBitsSet; 2015 } 2016 2017 // Similarly, for a ULT comparison, we don't care about the trailing zeros. 2018 // Any value less than the RHS must differ in a higher bit because of carries. 2019 case ICmpInst::ICMP_ULT: { 2020 unsigned trailingZeros = RHS.countTrailingZeros(); 2021 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros); 2022 return ~lowBitsSet; 2023 } 2024 2025 default: 2026 return APInt::getAllOnesValue(BitWidth); 2027 } 2028 2029 } 2030 2031 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) { 2032 bool Changed = false; 2033 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2034 2035 /// Orders the operands of the compare so that they are listed from most 2036 /// complex to least complex. This puts constants before unary operators, 2037 /// before binary operators. 2038 if (getComplexity(Op0) < getComplexity(Op1)) { 2039 I.swapOperands(); 2040 std::swap(Op0, Op1); 2041 Changed = true; 2042 } 2043 2044 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD)) 2045 return ReplaceInstUsesWith(I, V); 2046 2047 // comparing -val or val with non-zero is the same as just comparing val 2048 // ie, abs(val) != 0 -> val != 0 2049 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) 2050 { 2051 Value *Cond, *SelectTrue, *SelectFalse; 2052 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue), 2053 m_Value(SelectFalse)))) { 2054 if (Value *V = dyn_castNegVal(SelectTrue)) { 2055 if (V == SelectFalse) 2056 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 2057 } 2058 else if (Value *V = dyn_castNegVal(SelectFalse)) { 2059 if (V == SelectTrue) 2060 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 2061 } 2062 } 2063 } 2064 2065 Type *Ty = Op0->getType(); 2066 2067 // icmp's with boolean values can always be turned into bitwise operations 2068 if (Ty->isIntegerTy(1)) { 2069 switch (I.getPredicate()) { 2070 default: llvm_unreachable("Invalid icmp instruction!"); 2071 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B) 2072 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp"); 2073 return BinaryOperator::CreateNot(Xor); 2074 } 2075 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B 2076 return BinaryOperator::CreateXor(Op0, Op1); 2077 2078 case ICmpInst::ICMP_UGT: 2079 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult 2080 // FALL THROUGH 2081 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B 2082 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp"); 2083 return BinaryOperator::CreateAnd(Not, Op1); 2084 } 2085 case ICmpInst::ICMP_SGT: 2086 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt 2087 // FALL THROUGH 2088 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B 2089 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp"); 2090 return BinaryOperator::CreateAnd(Not, Op0); 2091 } 2092 case ICmpInst::ICMP_UGE: 2093 std::swap(Op0, Op1); // Change icmp uge -> icmp ule 2094 // FALL THROUGH 2095 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B 2096 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp"); 2097 return BinaryOperator::CreateOr(Not, Op1); 2098 } 2099 case ICmpInst::ICMP_SGE: 2100 std::swap(Op0, Op1); // Change icmp sge -> icmp sle 2101 // FALL THROUGH 2102 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B 2103 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp"); 2104 return BinaryOperator::CreateOr(Not, Op0); 2105 } 2106 } 2107 } 2108 2109 unsigned BitWidth = 0; 2110 if (Ty->isIntOrIntVectorTy()) 2111 BitWidth = Ty->getScalarSizeInBits(); 2112 else if (TD) // Pointers require TD info to get their size. 2113 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType()); 2114 2115 bool isSignBit = false; 2116 2117 // See if we are doing a comparison with a constant. 2118 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2119 Value *A = 0, *B = 0; 2120 2121 // Match the following pattern, which is a common idiom when writing 2122 // overflow-safe integer arithmetic function. The source performs an 2123 // addition in wider type, and explicitly checks for overflow using 2124 // comparisons against INT_MIN and INT_MAX. Simplify this by using the 2125 // sadd_with_overflow intrinsic. 2126 // 2127 // TODO: This could probably be generalized to handle other overflow-safe 2128 // operations if we worked out the formulas to compute the appropriate 2129 // magic constants. 2130 // 2131 // sum = a + b 2132 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 2133 { 2134 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI 2135 if (I.getPredicate() == ICmpInst::ICMP_UGT && 2136 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) 2137 if (Instruction *Res = ProcessUGT_ADDCST_ADD(I, A, B, CI2, CI, *this)) 2138 return Res; 2139 } 2140 2141 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B) 2142 if (I.isEquality() && CI->isZero() && 2143 match(Op0, m_Sub(m_Value(A), m_Value(B)))) { 2144 // (icmp cond A B) if cond is equality 2145 return new ICmpInst(I.getPredicate(), A, B); 2146 } 2147 2148 // If we have an icmp le or icmp ge instruction, turn it into the 2149 // appropriate icmp lt or icmp gt instruction. This allows us to rely on 2150 // them being folded in the code below. The SimplifyICmpInst code has 2151 // already handled the edge cases for us, so we just assert on them. 2152 switch (I.getPredicate()) { 2153 default: break; 2154 case ICmpInst::ICMP_ULE: 2155 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE 2156 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, 2157 Builder->getInt(CI->getValue()+1)); 2158 case ICmpInst::ICMP_SLE: 2159 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE 2160 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 2161 Builder->getInt(CI->getValue()+1)); 2162 case ICmpInst::ICMP_UGE: 2163 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE 2164 return new ICmpInst(ICmpInst::ICMP_UGT, Op0, 2165 Builder->getInt(CI->getValue()-1)); 2166 case ICmpInst::ICMP_SGE: 2167 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE 2168 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, 2169 Builder->getInt(CI->getValue()-1)); 2170 } 2171 2172 // If this comparison is a normal comparison, it demands all 2173 // bits, if it is a sign bit comparison, it only demands the sign bit. 2174 bool UnusedBit; 2175 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit); 2176 } 2177 2178 // See if we can fold the comparison based on range information we can get 2179 // by checking whether bits are known to be zero or one in the input. 2180 if (BitWidth != 0) { 2181 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0); 2182 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0); 2183 2184 if (SimplifyDemandedBits(I.getOperandUse(0), 2185 DemandedBitsLHSMask(I, BitWidth, isSignBit), 2186 Op0KnownZero, Op0KnownOne, 0)) 2187 return &I; 2188 if (SimplifyDemandedBits(I.getOperandUse(1), 2189 APInt::getAllOnesValue(BitWidth), 2190 Op1KnownZero, Op1KnownOne, 0)) 2191 return &I; 2192 2193 // Given the known and unknown bits, compute a range that the LHS could be 2194 // in. Compute the Min, Max and RHS values based on the known bits. For the 2195 // EQ and NE we use unsigned values. 2196 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 2197 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 2198 if (I.isSigned()) { 2199 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, 2200 Op0Min, Op0Max); 2201 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, 2202 Op1Min, Op1Max); 2203 } else { 2204 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, 2205 Op0Min, Op0Max); 2206 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, 2207 Op1Min, Op1Max); 2208 } 2209 2210 // If Min and Max are known to be the same, then SimplifyDemandedBits 2211 // figured out that the LHS is a constant. Just constant fold this now so 2212 // that code below can assume that Min != Max. 2213 if (!isa<Constant>(Op0) && Op0Min == Op0Max) 2214 return new ICmpInst(I.getPredicate(), 2215 ConstantInt::get(Op0->getType(), Op0Min), Op1); 2216 if (!isa<Constant>(Op1) && Op1Min == Op1Max) 2217 return new ICmpInst(I.getPredicate(), Op0, 2218 ConstantInt::get(Op1->getType(), Op1Min)); 2219 2220 // Based on the range information we know about the LHS, see if we can 2221 // simplify this comparison. For example, (x&4) < 8 is always true. 2222 switch (I.getPredicate()) { 2223 default: llvm_unreachable("Unknown icmp opcode!"); 2224 case ICmpInst::ICMP_EQ: { 2225 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 2226 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2227 2228 // If all bits are known zero except for one, then we know at most one 2229 // bit is set. If the comparison is against zero, then this is a check 2230 // to see if *that* bit is set. 2231 APInt Op0KnownZeroInverted = ~Op0KnownZero; 2232 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) { 2233 // If the LHS is an AND with the same constant, look through it. 2234 Value *LHS = 0; 2235 ConstantInt *LHSC = 0; 2236 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) || 2237 LHSC->getValue() != Op0KnownZeroInverted) 2238 LHS = Op0; 2239 2240 // If the LHS is 1 << x, and we know the result is a power of 2 like 8, 2241 // then turn "((1 << x)&8) == 0" into "x != 3". 2242 Value *X = 0; 2243 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 2244 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros(); 2245 return new ICmpInst(ICmpInst::ICMP_NE, X, 2246 ConstantInt::get(X->getType(), CmpVal)); 2247 } 2248 2249 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1, 2250 // then turn "((8 >>u x)&1) == 0" into "x != 3". 2251 const APInt *CI; 2252 if (Op0KnownZeroInverted == 1 && 2253 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) 2254 return new ICmpInst(ICmpInst::ICMP_NE, X, 2255 ConstantInt::get(X->getType(), 2256 CI->countTrailingZeros())); 2257 } 2258 2259 break; 2260 } 2261 case ICmpInst::ICMP_NE: { 2262 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) 2263 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2264 2265 // If all bits are known zero except for one, then we know at most one 2266 // bit is set. If the comparison is against zero, then this is a check 2267 // to see if *that* bit is set. 2268 APInt Op0KnownZeroInverted = ~Op0KnownZero; 2269 if (~Op1KnownZero == 0 && Op0KnownZeroInverted.isPowerOf2()) { 2270 // If the LHS is an AND with the same constant, look through it. 2271 Value *LHS = 0; 2272 ConstantInt *LHSC = 0; 2273 if (!match(Op0, m_And(m_Value(LHS), m_ConstantInt(LHSC))) || 2274 LHSC->getValue() != Op0KnownZeroInverted) 2275 LHS = Op0; 2276 2277 // If the LHS is 1 << x, and we know the result is a power of 2 like 8, 2278 // then turn "((1 << x)&8) != 0" into "x == 3". 2279 Value *X = 0; 2280 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 2281 unsigned CmpVal = Op0KnownZeroInverted.countTrailingZeros(); 2282 return new ICmpInst(ICmpInst::ICMP_EQ, X, 2283 ConstantInt::get(X->getType(), CmpVal)); 2284 } 2285 2286 // If the LHS is 8 >>u x, and we know the result is a power of 2 like 1, 2287 // then turn "((8 >>u x)&1) != 0" into "x == 3". 2288 const APInt *CI; 2289 if (Op0KnownZeroInverted == 1 && 2290 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) 2291 return new ICmpInst(ICmpInst::ICMP_EQ, X, 2292 ConstantInt::get(X->getType(), 2293 CI->countTrailingZeros())); 2294 } 2295 2296 break; 2297 } 2298 case ICmpInst::ICMP_ULT: 2299 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 2300 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2301 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 2302 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2303 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 2304 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 2305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2306 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C 2307 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2308 Builder->getInt(CI->getValue()-1)); 2309 2310 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear 2311 if (CI->isMinValue(true)) 2312 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, 2313 Constant::getAllOnesValue(Op0->getType())); 2314 } 2315 break; 2316 case ICmpInst::ICMP_UGT: 2317 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 2318 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2319 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 2320 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2321 2322 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 2323 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 2324 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2325 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C 2326 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2327 Builder->getInt(CI->getValue()+1)); 2328 2329 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set 2330 if (CI->isMaxValue(true)) 2331 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 2332 Constant::getNullValue(Op0->getType())); 2333 } 2334 break; 2335 case ICmpInst::ICMP_SLT: 2336 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 2337 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2338 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 2339 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2340 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 2341 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 2342 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2343 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C 2344 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2345 Builder->getInt(CI->getValue()-1)); 2346 } 2347 break; 2348 case ICmpInst::ICMP_SGT: 2349 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 2350 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2351 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 2352 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2353 2354 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 2355 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 2356 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2357 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C 2358 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 2359 Builder->getInt(CI->getValue()+1)); 2360 } 2361 break; 2362 case ICmpInst::ICMP_SGE: 2363 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 2364 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 2365 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2366 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 2367 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2368 break; 2369 case ICmpInst::ICMP_SLE: 2370 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 2371 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 2372 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2373 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 2374 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2375 break; 2376 case ICmpInst::ICMP_UGE: 2377 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 2378 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 2379 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2380 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 2381 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2382 break; 2383 case ICmpInst::ICMP_ULE: 2384 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 2385 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 2386 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2387 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 2388 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2389 break; 2390 } 2391 2392 // Turn a signed comparison into an unsigned one if both operands 2393 // are known to have the same sign. 2394 if (I.isSigned() && 2395 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) || 2396 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative()))) 2397 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 2398 } 2399 2400 // Test if the ICmpInst instruction is used exclusively by a select as 2401 // part of a minimum or maximum operation. If so, refrain from doing 2402 // any other folding. This helps out other analyses which understand 2403 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 2404 // and CodeGen. And in this case, at least one of the comparison 2405 // operands has at least one user besides the compare (the select), 2406 // which would often largely negate the benefit of folding anyway. 2407 if (I.hasOneUse()) 2408 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin())) 2409 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || 2410 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) 2411 return 0; 2412 2413 // See if we are doing a comparison between a constant and an instruction that 2414 // can be folded into the comparison. 2415 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 2416 // Since the RHS is a ConstantInt (CI), if the left hand side is an 2417 // instruction, see if that instruction also has constants so that the 2418 // instruction can be folded into the icmp 2419 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 2420 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI)) 2421 return Res; 2422 } 2423 2424 // Handle icmp with constant (but not simple integer constant) RHS 2425 if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 2426 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 2427 switch (LHSI->getOpcode()) { 2428 case Instruction::GetElementPtr: 2429 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 2430 if (RHSC->isNullValue() && 2431 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 2432 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), 2433 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2434 break; 2435 case Instruction::PHI: 2436 // Only fold icmp into the PHI if the phi and icmp are in the same 2437 // block. If in the same block, we're encouraging jump threading. If 2438 // not, we are just pessimizing the code by making an i1 phi. 2439 if (LHSI->getParent() == I.getParent()) 2440 if (Instruction *NV = FoldOpIntoPhi(I)) 2441 return NV; 2442 break; 2443 case Instruction::Select: { 2444 // If either operand of the select is a constant, we can fold the 2445 // comparison into the select arms, which will cause one to be 2446 // constant folded and the select turned into a bitwise or. 2447 Value *Op1 = 0, *Op2 = 0; 2448 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) 2449 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2450 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) 2451 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2452 2453 // We only want to perform this transformation if it will not lead to 2454 // additional code. This is true if either both sides of the select 2455 // fold to a constant (in which case the icmp is replaced with a select 2456 // which will usually simplify) or this is the only user of the 2457 // select (in which case we are trading a select+icmp for a simpler 2458 // select+icmp). 2459 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) { 2460 if (!Op1) 2461 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), 2462 RHSC, I.getName()); 2463 if (!Op2) 2464 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), 2465 RHSC, I.getName()); 2466 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 2467 } 2468 break; 2469 } 2470 case Instruction::IntToPtr: 2471 // icmp pred inttoptr(X), null -> icmp pred X, 0 2472 if (RHSC->isNullValue() && TD && 2473 TD->getIntPtrType(RHSC->getContext()) == 2474 LHSI->getOperand(0)->getType()) 2475 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0), 2476 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2477 break; 2478 2479 case Instruction::Load: 2480 // Try to optimize things like "A[i] > 4" to index computations. 2481 if (GetElementPtrInst *GEP = 2482 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 2483 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 2484 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 2485 !cast<LoadInst>(LHSI)->isVolatile()) 2486 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) 2487 return Res; 2488 } 2489 break; 2490 } 2491 } 2492 2493 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. 2494 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) 2495 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I)) 2496 return NI; 2497 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) 2498 if (Instruction *NI = FoldGEPICmp(GEP, Op0, 2499 ICmpInst::getSwappedPredicate(I.getPredicate()), I)) 2500 return NI; 2501 2502 // Test to see if the operands of the icmp are casted versions of other 2503 // values. If the ptr->ptr cast can be stripped off both arguments, we do so 2504 // now. 2505 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { 2506 if (Op0->getType()->isPointerTy() && 2507 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 2508 // We keep moving the cast from the left operand over to the right 2509 // operand, where it can often be eliminated completely. 2510 Op0 = CI->getOperand(0); 2511 2512 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 2513 // so eliminate it as well. 2514 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) 2515 Op1 = CI2->getOperand(0); 2516 2517 // If Op1 is a constant, we can fold the cast into the constant. 2518 if (Op0->getType() != Op1->getType()) { 2519 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 2520 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); 2521 } else { 2522 // Otherwise, cast the RHS right before the icmp 2523 Op1 = Builder->CreateBitCast(Op1, Op0->getType()); 2524 } 2525 } 2526 return new ICmpInst(I.getPredicate(), Op0, Op1); 2527 } 2528 } 2529 2530 if (isa<CastInst>(Op0)) { 2531 // Handle the special case of: icmp (cast bool to X), <cst> 2532 // This comes up when you have code like 2533 // int X = A < B; 2534 // if (X) ... 2535 // For generality, we handle any zero-extension of any operand comparison 2536 // with a constant or another cast from the same type. 2537 if (isa<Constant>(Op1) || isa<CastInst>(Op1)) 2538 if (Instruction *R = visitICmpInstWithCastAndCast(I)) 2539 return R; 2540 } 2541 2542 // Special logic for binary operators. 2543 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0); 2544 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1); 2545 if (BO0 || BO1) { 2546 CmpInst::Predicate Pred = I.getPredicate(); 2547 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; 2548 if (BO0 && isa<OverflowingBinaryOperator>(BO0)) 2549 NoOp0WrapProblem = ICmpInst::isEquality(Pred) || 2550 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) || 2551 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap()); 2552 if (BO1 && isa<OverflowingBinaryOperator>(BO1)) 2553 NoOp1WrapProblem = ICmpInst::isEquality(Pred) || 2554 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) || 2555 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap()); 2556 2557 // Analyze the case when either Op0 or Op1 is an add instruction. 2558 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null). 2559 Value *A = 0, *B = 0, *C = 0, *D = 0; 2560 if (BO0 && BO0->getOpcode() == Instruction::Add) 2561 A = BO0->getOperand(0), B = BO0->getOperand(1); 2562 if (BO1 && BO1->getOpcode() == Instruction::Add) 2563 C = BO1->getOperand(0), D = BO1->getOperand(1); 2564 2565 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 2566 if ((A == Op1 || B == Op1) && NoOp0WrapProblem) 2567 return new ICmpInst(Pred, A == Op1 ? B : A, 2568 Constant::getNullValue(Op1->getType())); 2569 2570 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 2571 if ((C == Op0 || D == Op0) && NoOp1WrapProblem) 2572 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()), 2573 C == Op0 ? D : C); 2574 2575 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow. 2576 if (A && C && (A == C || A == D || B == C || B == D) && 2577 NoOp0WrapProblem && NoOp1WrapProblem && 2578 // Try not to increase register pressure. 2579 BO0->hasOneUse() && BO1->hasOneUse()) { 2580 // Determine Y and Z in the form icmp (X+Y), (X+Z). 2581 Value *Y, *Z; 2582 if (A == C) { 2583 // C + B == C + D -> B == D 2584 Y = B; 2585 Z = D; 2586 } else if (A == D) { 2587 // D + B == C + D -> B == C 2588 Y = B; 2589 Z = C; 2590 } else if (B == C) { 2591 // A + C == C + D -> A == D 2592 Y = A; 2593 Z = D; 2594 } else { 2595 assert(B == D); 2596 // A + D == C + D -> A == C 2597 Y = A; 2598 Z = C; 2599 } 2600 return new ICmpInst(Pred, Y, Z); 2601 } 2602 2603 // icmp slt (X + -1), Y -> icmp sle X, Y 2604 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT && 2605 match(B, m_AllOnes())) 2606 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1); 2607 2608 // icmp sge (X + -1), Y -> icmp sgt X, Y 2609 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE && 2610 match(B, m_AllOnes())) 2611 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1); 2612 2613 // icmp sle (X + 1), Y -> icmp slt X, Y 2614 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && 2615 match(B, m_One())) 2616 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1); 2617 2618 // icmp sgt (X + 1), Y -> icmp sge X, Y 2619 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && 2620 match(B, m_One())) 2621 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1); 2622 2623 // if C1 has greater magnitude than C2: 2624 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y 2625 // s.t. C3 = C1 - C2 2626 // 2627 // if C2 has greater magnitude than C1: 2628 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3) 2629 // s.t. C3 = C2 - C1 2630 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem && 2631 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) 2632 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B)) 2633 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) { 2634 const APInt &AP1 = C1->getValue(); 2635 const APInt &AP2 = C2->getValue(); 2636 if (AP1.isNegative() == AP2.isNegative()) { 2637 APInt AP1Abs = C1->getValue().abs(); 2638 APInt AP2Abs = C2->getValue().abs(); 2639 if (AP1Abs.uge(AP2Abs)) { 2640 ConstantInt *C3 = Builder->getInt(AP1 - AP2); 2641 Value *NewAdd = Builder->CreateNSWAdd(A, C3); 2642 return new ICmpInst(Pred, NewAdd, C); 2643 } else { 2644 ConstantInt *C3 = Builder->getInt(AP2 - AP1); 2645 Value *NewAdd = Builder->CreateNSWAdd(C, C3); 2646 return new ICmpInst(Pred, A, NewAdd); 2647 } 2648 } 2649 } 2650 2651 2652 // Analyze the case when either Op0 or Op1 is a sub instruction. 2653 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null). 2654 A = 0; B = 0; C = 0; D = 0; 2655 if (BO0 && BO0->getOpcode() == Instruction::Sub) 2656 A = BO0->getOperand(0), B = BO0->getOperand(1); 2657 if (BO1 && BO1->getOpcode() == Instruction::Sub) 2658 C = BO1->getOperand(0), D = BO1->getOperand(1); 2659 2660 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow. 2661 if (A == Op1 && NoOp0WrapProblem) 2662 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B); 2663 2664 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow. 2665 if (C == Op0 && NoOp1WrapProblem) 2666 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType())); 2667 2668 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow. 2669 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem && 2670 // Try not to increase register pressure. 2671 BO0->hasOneUse() && BO1->hasOneUse()) 2672 return new ICmpInst(Pred, A, C); 2673 2674 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow. 2675 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem && 2676 // Try not to increase register pressure. 2677 BO0->hasOneUse() && BO1->hasOneUse()) 2678 return new ICmpInst(Pred, D, B); 2679 2680 BinaryOperator *SRem = NULL; 2681 // icmp (srem X, Y), Y 2682 if (BO0 && BO0->getOpcode() == Instruction::SRem && 2683 Op1 == BO0->getOperand(1)) 2684 SRem = BO0; 2685 // icmp Y, (srem X, Y) 2686 else if (BO1 && BO1->getOpcode() == Instruction::SRem && 2687 Op0 == BO1->getOperand(1)) 2688 SRem = BO1; 2689 if (SRem) { 2690 // We don't check hasOneUse to avoid increasing register pressure because 2691 // the value we use is the same value this instruction was already using. 2692 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) { 2693 default: break; 2694 case ICmpInst::ICMP_EQ: 2695 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2696 case ICmpInst::ICMP_NE: 2697 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2698 case ICmpInst::ICMP_SGT: 2699 case ICmpInst::ICMP_SGE: 2700 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1), 2701 Constant::getAllOnesValue(SRem->getType())); 2702 case ICmpInst::ICMP_SLT: 2703 case ICmpInst::ICMP_SLE: 2704 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1), 2705 Constant::getNullValue(SRem->getType())); 2706 } 2707 } 2708 2709 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && 2710 BO0->hasOneUse() && BO1->hasOneUse() && 2711 BO0->getOperand(1) == BO1->getOperand(1)) { 2712 switch (BO0->getOpcode()) { 2713 default: break; 2714 case Instruction::Add: 2715 case Instruction::Sub: 2716 case Instruction::Xor: 2717 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 2718 return new ICmpInst(I.getPredicate(), BO0->getOperand(0), 2719 BO1->getOperand(0)); 2720 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b 2721 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { 2722 if (CI->getValue().isSignBit()) { 2723 ICmpInst::Predicate Pred = I.isSigned() 2724 ? I.getUnsignedPredicate() 2725 : I.getSignedPredicate(); 2726 return new ICmpInst(Pred, BO0->getOperand(0), 2727 BO1->getOperand(0)); 2728 } 2729 2730 if (CI->isMaxValue(true)) { 2731 ICmpInst::Predicate Pred = I.isSigned() 2732 ? I.getUnsignedPredicate() 2733 : I.getSignedPredicate(); 2734 Pred = I.getSwappedPredicate(Pred); 2735 return new ICmpInst(Pred, BO0->getOperand(0), 2736 BO1->getOperand(0)); 2737 } 2738 } 2739 break; 2740 case Instruction::Mul: 2741 if (!I.isEquality()) 2742 break; 2743 2744 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { 2745 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask 2746 // Mask = -1 >> count-trailing-zeros(Cst). 2747 if (!CI->isZero() && !CI->isOne()) { 2748 const APInt &AP = CI->getValue(); 2749 ConstantInt *Mask = ConstantInt::get(I.getContext(), 2750 APInt::getLowBitsSet(AP.getBitWidth(), 2751 AP.getBitWidth() - 2752 AP.countTrailingZeros())); 2753 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask); 2754 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask); 2755 return new ICmpInst(I.getPredicate(), And1, And2); 2756 } 2757 } 2758 break; 2759 case Instruction::UDiv: 2760 case Instruction::LShr: 2761 if (I.isSigned()) 2762 break; 2763 // fall-through 2764 case Instruction::SDiv: 2765 case Instruction::AShr: 2766 if (!BO0->isExact() || !BO1->isExact()) 2767 break; 2768 return new ICmpInst(I.getPredicate(), BO0->getOperand(0), 2769 BO1->getOperand(0)); 2770 case Instruction::Shl: { 2771 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); 2772 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); 2773 if (!NUW && !NSW) 2774 break; 2775 if (!NSW && I.isSigned()) 2776 break; 2777 return new ICmpInst(I.getPredicate(), BO0->getOperand(0), 2778 BO1->getOperand(0)); 2779 } 2780 } 2781 } 2782 } 2783 2784 { Value *A, *B; 2785 // Transform (A & ~B) == 0 --> (A & B) != 0 2786 // and (A & ~B) != 0 --> (A & B) == 0 2787 // if A is a power of 2. 2788 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) && 2789 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(A) && I.isEquality()) 2790 return new ICmpInst(I.getInversePredicate(), 2791 Builder->CreateAnd(A, B), 2792 Op1); 2793 2794 // ~x < ~y --> y < x 2795 // ~x < cst --> ~cst < x 2796 if (match(Op0, m_Not(m_Value(A)))) { 2797 if (match(Op1, m_Not(m_Value(B)))) 2798 return new ICmpInst(I.getPredicate(), B, A); 2799 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) 2800 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A); 2801 } 2802 2803 // (a+b) <u a --> llvm.uadd.with.overflow. 2804 // (a+b) <u b --> llvm.uadd.with.overflow. 2805 if (I.getPredicate() == ICmpInst::ICMP_ULT && 2806 match(Op0, m_Add(m_Value(A), m_Value(B))) && 2807 (Op1 == A || Op1 == B)) 2808 if (Instruction *R = ProcessUAddIdiom(I, Op0, *this)) 2809 return R; 2810 2811 // a >u (a+b) --> llvm.uadd.with.overflow. 2812 // b >u (a+b) --> llvm.uadd.with.overflow. 2813 if (I.getPredicate() == ICmpInst::ICMP_UGT && 2814 match(Op1, m_Add(m_Value(A), m_Value(B))) && 2815 (Op0 == A || Op0 == B)) 2816 if (Instruction *R = ProcessUAddIdiom(I, Op1, *this)) 2817 return R; 2818 } 2819 2820 if (I.isEquality()) { 2821 Value *A, *B, *C, *D; 2822 2823 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 2824 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 2825 Value *OtherVal = A == Op1 ? B : A; 2826 return new ICmpInst(I.getPredicate(), OtherVal, 2827 Constant::getNullValue(A->getType())); 2828 } 2829 2830 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 2831 // A^c1 == C^c2 --> A == C^(c1^c2) 2832 ConstantInt *C1, *C2; 2833 if (match(B, m_ConstantInt(C1)) && 2834 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) { 2835 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue()); 2836 Value *Xor = Builder->CreateXor(C, NC); 2837 return new ICmpInst(I.getPredicate(), A, Xor); 2838 } 2839 2840 // A^B == A^D -> B == D 2841 if (A == C) return new ICmpInst(I.getPredicate(), B, D); 2842 if (A == D) return new ICmpInst(I.getPredicate(), B, C); 2843 if (B == C) return new ICmpInst(I.getPredicate(), A, D); 2844 if (B == D) return new ICmpInst(I.getPredicate(), A, C); 2845 } 2846 } 2847 2848 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && 2849 (A == Op0 || B == Op0)) { 2850 // A == (A^B) -> B == 0 2851 Value *OtherVal = A == Op0 ? B : A; 2852 return new ICmpInst(I.getPredicate(), OtherVal, 2853 Constant::getNullValue(A->getType())); 2854 } 2855 2856 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 2857 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && 2858 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) { 2859 Value *X = 0, *Y = 0, *Z = 0; 2860 2861 if (A == C) { 2862 X = B; Y = D; Z = A; 2863 } else if (A == D) { 2864 X = B; Y = C; Z = A; 2865 } else if (B == C) { 2866 X = A; Y = D; Z = B; 2867 } else if (B == D) { 2868 X = A; Y = C; Z = B; 2869 } 2870 2871 if (X) { // Build (X^Y) & Z 2872 Op1 = Builder->CreateXor(X, Y); 2873 Op1 = Builder->CreateAnd(Op1, Z); 2874 I.setOperand(0, Op1); 2875 I.setOperand(1, Constant::getNullValue(Op1->getType())); 2876 return &I; 2877 } 2878 } 2879 2880 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B) 2881 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B) 2882 ConstantInt *Cst1; 2883 if ((Op0->hasOneUse() && 2884 match(Op0, m_ZExt(m_Value(A))) && 2885 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) || 2886 (Op1->hasOneUse() && 2887 match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) && 2888 match(Op1, m_ZExt(m_Value(A))))) { 2889 APInt Pow2 = Cst1->getValue() + 1; 2890 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) && 2891 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth()) 2892 return new ICmpInst(I.getPredicate(), A, 2893 Builder->CreateTrunc(B, A->getType())); 2894 } 2895 2896 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to 2897 // "icmp (and X, mask), cst" 2898 uint64_t ShAmt = 0; 2899 if (Op0->hasOneUse() && 2900 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), 2901 m_ConstantInt(ShAmt))))) && 2902 match(Op1, m_ConstantInt(Cst1)) && 2903 // Only do this when A has multiple uses. This is most important to do 2904 // when it exposes other optimizations. 2905 !A->hasOneUse()) { 2906 unsigned ASize =cast<IntegerType>(A->getType())->getPrimitiveSizeInBits(); 2907 2908 if (ShAmt < ASize) { 2909 APInt MaskV = 2910 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits()); 2911 MaskV <<= ShAmt; 2912 2913 APInt CmpV = Cst1->getValue().zext(ASize); 2914 CmpV <<= ShAmt; 2915 2916 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV)); 2917 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV)); 2918 } 2919 } 2920 } 2921 2922 { 2923 Value *X; ConstantInt *Cst; 2924 // icmp X+Cst, X 2925 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X) 2926 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0); 2927 2928 // icmp X, X+Cst 2929 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X) 2930 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1); 2931 } 2932 return Changed ? &I : 0; 2933 } 2934 2935 2936 2937 2938 2939 2940 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible. 2941 /// 2942 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I, 2943 Instruction *LHSI, 2944 Constant *RHSC) { 2945 if (!isa<ConstantFP>(RHSC)) return 0; 2946 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 2947 2948 // Get the width of the mantissa. We don't want to hack on conversions that 2949 // might lose information from the integer, e.g. "i64 -> float" 2950 int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 2951 if (MantissaWidth == -1) return 0; // Unknown. 2952 2953 // Check to see that the input is converted from an integer type that is small 2954 // enough that preserves all bits. TODO: check here for "known" sign bits. 2955 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 2956 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits(); 2957 2958 // If this is a uitofp instruction, we need an extra bit to hold the sign. 2959 bool LHSUnsigned = isa<UIToFPInst>(LHSI); 2960 if (LHSUnsigned) 2961 ++InputSize; 2962 2963 // If the conversion would lose info, don't hack on this. 2964 if ((int)InputSize > MantissaWidth) 2965 return 0; 2966 2967 // Otherwise, we can potentially simplify the comparison. We know that it 2968 // will always come through as an integer value and we know the constant is 2969 // not a NAN (it would have been previously simplified). 2970 assert(!RHS.isNaN() && "NaN comparison not already folded!"); 2971 2972 ICmpInst::Predicate Pred; 2973 switch (I.getPredicate()) { 2974 default: llvm_unreachable("Unexpected predicate!"); 2975 case FCmpInst::FCMP_UEQ: 2976 case FCmpInst::FCMP_OEQ: 2977 Pred = ICmpInst::ICMP_EQ; 2978 break; 2979 case FCmpInst::FCMP_UGT: 2980 case FCmpInst::FCMP_OGT: 2981 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 2982 break; 2983 case FCmpInst::FCMP_UGE: 2984 case FCmpInst::FCMP_OGE: 2985 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 2986 break; 2987 case FCmpInst::FCMP_ULT: 2988 case FCmpInst::FCMP_OLT: 2989 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 2990 break; 2991 case FCmpInst::FCMP_ULE: 2992 case FCmpInst::FCMP_OLE: 2993 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 2994 break; 2995 case FCmpInst::FCMP_UNE: 2996 case FCmpInst::FCMP_ONE: 2997 Pred = ICmpInst::ICMP_NE; 2998 break; 2999 case FCmpInst::FCMP_ORD: 3000 return ReplaceInstUsesWith(I, Builder->getTrue()); 3001 case FCmpInst::FCMP_UNO: 3002 return ReplaceInstUsesWith(I, Builder->getFalse()); 3003 } 3004 3005 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 3006 3007 // Now we know that the APFloat is a normal number, zero or inf. 3008 3009 // See if the FP constant is too large for the integer. For example, 3010 // comparing an i8 to 300.0. 3011 unsigned IntWidth = IntTy->getScalarSizeInBits(); 3012 3013 if (!LHSUnsigned) { 3014 // If the RHS value is > SignedMax, fold the comparison. This handles +INF 3015 // and large values. 3016 APFloat SMax(RHS.getSemantics()); 3017 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 3018 APFloat::rmNearestTiesToEven); 3019 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 3020 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 3021 Pred == ICmpInst::ICMP_SLE) 3022 return ReplaceInstUsesWith(I, Builder->getTrue()); 3023 return ReplaceInstUsesWith(I, Builder->getFalse()); 3024 } 3025 } else { 3026 // If the RHS value is > UnsignedMax, fold the comparison. This handles 3027 // +INF and large values. 3028 APFloat UMax(RHS.getSemantics()); 3029 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 3030 APFloat::rmNearestTiesToEven); 3031 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 3032 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 3033 Pred == ICmpInst::ICMP_ULE) 3034 return ReplaceInstUsesWith(I, Builder->getTrue()); 3035 return ReplaceInstUsesWith(I, Builder->getFalse()); 3036 } 3037 } 3038 3039 if (!LHSUnsigned) { 3040 // See if the RHS value is < SignedMin. 3041 APFloat SMin(RHS.getSemantics()); 3042 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 3043 APFloat::rmNearestTiesToEven); 3044 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 3045 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 3046 Pred == ICmpInst::ICMP_SGE) 3047 return ReplaceInstUsesWith(I, Builder->getTrue()); 3048 return ReplaceInstUsesWith(I, Builder->getFalse()); 3049 } 3050 } else { 3051 // See if the RHS value is < UnsignedMin. 3052 APFloat SMin(RHS.getSemantics()); 3053 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true, 3054 APFloat::rmNearestTiesToEven); 3055 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0 3056 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT || 3057 Pred == ICmpInst::ICMP_UGE) 3058 return ReplaceInstUsesWith(I, Builder->getTrue()); 3059 return ReplaceInstUsesWith(I, Builder->getFalse()); 3060 } 3061 } 3062 3063 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 3064 // [0, UMAX], but it may still be fractional. See if it is fractional by 3065 // casting the FP value to the integer value and back, checking for equality. 3066 // Don't do this for zero, because -0.0 is not fractional. 3067 Constant *RHSInt = LHSUnsigned 3068 ? ConstantExpr::getFPToUI(RHSC, IntTy) 3069 : ConstantExpr::getFPToSI(RHSC, IntTy); 3070 if (!RHS.isZero()) { 3071 bool Equal = LHSUnsigned 3072 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 3073 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 3074 if (!Equal) { 3075 // If we had a comparison against a fractional value, we have to adjust 3076 // the compare predicate and sometimes the value. RHSC is rounded towards 3077 // zero at this point. 3078 switch (Pred) { 3079 default: llvm_unreachable("Unexpected integer comparison!"); 3080 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 3081 return ReplaceInstUsesWith(I, Builder->getTrue()); 3082 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 3083 return ReplaceInstUsesWith(I, Builder->getFalse()); 3084 case ICmpInst::ICMP_ULE: 3085 // (float)int <= 4.4 --> int <= 4 3086 // (float)int <= -4.4 --> false 3087 if (RHS.isNegative()) 3088 return ReplaceInstUsesWith(I, Builder->getFalse()); 3089 break; 3090 case ICmpInst::ICMP_SLE: 3091 // (float)int <= 4.4 --> int <= 4 3092 // (float)int <= -4.4 --> int < -4 3093 if (RHS.isNegative()) 3094 Pred = ICmpInst::ICMP_SLT; 3095 break; 3096 case ICmpInst::ICMP_ULT: 3097 // (float)int < -4.4 --> false 3098 // (float)int < 4.4 --> int <= 4 3099 if (RHS.isNegative()) 3100 return ReplaceInstUsesWith(I, Builder->getFalse()); 3101 Pred = ICmpInst::ICMP_ULE; 3102 break; 3103 case ICmpInst::ICMP_SLT: 3104 // (float)int < -4.4 --> int < -4 3105 // (float)int < 4.4 --> int <= 4 3106 if (!RHS.isNegative()) 3107 Pred = ICmpInst::ICMP_SLE; 3108 break; 3109 case ICmpInst::ICMP_UGT: 3110 // (float)int > 4.4 --> int > 4 3111 // (float)int > -4.4 --> true 3112 if (RHS.isNegative()) 3113 return ReplaceInstUsesWith(I, Builder->getTrue()); 3114 break; 3115 case ICmpInst::ICMP_SGT: 3116 // (float)int > 4.4 --> int > 4 3117 // (float)int > -4.4 --> int >= -4 3118 if (RHS.isNegative()) 3119 Pred = ICmpInst::ICMP_SGE; 3120 break; 3121 case ICmpInst::ICMP_UGE: 3122 // (float)int >= -4.4 --> true 3123 // (float)int >= 4.4 --> int > 4 3124 if (RHS.isNegative()) 3125 return ReplaceInstUsesWith(I, Builder->getTrue()); 3126 Pred = ICmpInst::ICMP_UGT; 3127 break; 3128 case ICmpInst::ICMP_SGE: 3129 // (float)int >= -4.4 --> int >= -4 3130 // (float)int >= 4.4 --> int > 4 3131 if (!RHS.isNegative()) 3132 Pred = ICmpInst::ICMP_SGT; 3133 break; 3134 } 3135 } 3136 } 3137 3138 // Lower this FP comparison into an appropriate integer version of the 3139 // comparison. 3140 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 3141 } 3142 3143 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { 3144 bool Changed = false; 3145 3146 /// Orders the operands of the compare so that they are listed from most 3147 /// complex to least complex. This puts constants before unary operators, 3148 /// before binary operators. 3149 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 3150 I.swapOperands(); 3151 Changed = true; 3152 } 3153 3154 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3155 3156 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD)) 3157 return ReplaceInstUsesWith(I, V); 3158 3159 // Simplify 'fcmp pred X, X' 3160 if (Op0 == Op1) { 3161 switch (I.getPredicate()) { 3162 default: llvm_unreachable("Unknown predicate!"); 3163 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 3164 case FCmpInst::FCMP_ULT: // True if unordered or less than 3165 case FCmpInst::FCMP_UGT: // True if unordered or greater than 3166 case FCmpInst::FCMP_UNE: // True if unordered or not equal 3167 // Canonicalize these to be 'fcmp uno %X, 0.0'. 3168 I.setPredicate(FCmpInst::FCMP_UNO); 3169 I.setOperand(1, Constant::getNullValue(Op0->getType())); 3170 return &I; 3171 3172 case FCmpInst::FCMP_ORD: // True if ordered (no nans) 3173 case FCmpInst::FCMP_OEQ: // True if ordered and equal 3174 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 3175 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 3176 // Canonicalize these to be 'fcmp ord %X, 0.0'. 3177 I.setPredicate(FCmpInst::FCMP_ORD); 3178 I.setOperand(1, Constant::getNullValue(Op0->getType())); 3179 return &I; 3180 } 3181 } 3182 3183 // Handle fcmp with constant RHS 3184 if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 3185 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 3186 switch (LHSI->getOpcode()) { 3187 case Instruction::FPExt: { 3188 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless 3189 FPExtInst *LHSExt = cast<FPExtInst>(LHSI); 3190 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC); 3191 if (!RHSF) 3192 break; 3193 3194 const fltSemantics *Sem; 3195 // FIXME: This shouldn't be here. 3196 if (LHSExt->getSrcTy()->isHalfTy()) 3197 Sem = &APFloat::IEEEhalf; 3198 else if (LHSExt->getSrcTy()->isFloatTy()) 3199 Sem = &APFloat::IEEEsingle; 3200 else if (LHSExt->getSrcTy()->isDoubleTy()) 3201 Sem = &APFloat::IEEEdouble; 3202 else if (LHSExt->getSrcTy()->isFP128Ty()) 3203 Sem = &APFloat::IEEEquad; 3204 else if (LHSExt->getSrcTy()->isX86_FP80Ty()) 3205 Sem = &APFloat::x87DoubleExtended; 3206 else if (LHSExt->getSrcTy()->isPPC_FP128Ty()) 3207 Sem = &APFloat::PPCDoubleDouble; 3208 else 3209 break; 3210 3211 bool Lossy; 3212 APFloat F = RHSF->getValueAPF(); 3213 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy); 3214 3215 // Avoid lossy conversions and denormals. Zero is a special case 3216 // that's OK to convert. 3217 APFloat Fabs = F; 3218 Fabs.clearSign(); 3219 if (!Lossy && 3220 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) != 3221 APFloat::cmpLessThan) || Fabs.isZero())) 3222 3223 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0), 3224 ConstantFP::get(RHSC->getContext(), F)); 3225 break; 3226 } 3227 case Instruction::PHI: 3228 // Only fold fcmp into the PHI if the phi and fcmp are in the same 3229 // block. If in the same block, we're encouraging jump threading. If 3230 // not, we are just pessimizing the code by making an i1 phi. 3231 if (LHSI->getParent() == I.getParent()) 3232 if (Instruction *NV = FoldOpIntoPhi(I)) 3233 return NV; 3234 break; 3235 case Instruction::SIToFP: 3236 case Instruction::UIToFP: 3237 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC)) 3238 return NV; 3239 break; 3240 case Instruction::Select: { 3241 // If either operand of the select is a constant, we can fold the 3242 // comparison into the select arms, which will cause one to be 3243 // constant folded and the select turned into a bitwise or. 3244 Value *Op1 = 0, *Op2 = 0; 3245 if (LHSI->hasOneUse()) { 3246 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { 3247 // Fold the known value into the constant operand. 3248 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); 3249 // Insert a new FCmp of the other select operand. 3250 Op2 = Builder->CreateFCmp(I.getPredicate(), 3251 LHSI->getOperand(2), RHSC, I.getName()); 3252 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { 3253 // Fold the known value into the constant operand. 3254 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC); 3255 // Insert a new FCmp of the other select operand. 3256 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1), 3257 RHSC, I.getName()); 3258 } 3259 } 3260 3261 if (Op1) 3262 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 3263 break; 3264 } 3265 case Instruction::FSub: { 3266 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C 3267 Value *Op; 3268 if (match(LHSI, m_FNeg(m_Value(Op)))) 3269 return new FCmpInst(I.getSwappedPredicate(), Op, 3270 ConstantExpr::getFNeg(RHSC)); 3271 break; 3272 } 3273 case Instruction::Load: 3274 if (GetElementPtrInst *GEP = 3275 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 3276 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 3277 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 3278 !cast<LoadInst>(LHSI)->isVolatile()) 3279 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I)) 3280 return Res; 3281 } 3282 break; 3283 case Instruction::Call: { 3284 CallInst *CI = cast<CallInst>(LHSI); 3285 LibFunc::Func Func; 3286 // Various optimization for fabs compared with zero. 3287 if (RHSC->isNullValue() && CI->getCalledFunction() && 3288 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) && 3289 TLI->has(Func)) { 3290 if (Func == LibFunc::fabs || Func == LibFunc::fabsf || 3291 Func == LibFunc::fabsl) { 3292 switch (I.getPredicate()) { 3293 default: break; 3294 // fabs(x) < 0 --> false 3295 case FCmpInst::FCMP_OLT: 3296 return ReplaceInstUsesWith(I, Builder->getFalse()); 3297 // fabs(x) > 0 --> x != 0 3298 case FCmpInst::FCMP_OGT: 3299 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), 3300 RHSC); 3301 // fabs(x) <= 0 --> x == 0 3302 case FCmpInst::FCMP_OLE: 3303 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), 3304 RHSC); 3305 // fabs(x) >= 0 --> !isnan(x) 3306 case FCmpInst::FCMP_OGE: 3307 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), 3308 RHSC); 3309 // fabs(x) == 0 --> x == 0 3310 // fabs(x) != 0 --> x != 0 3311 case FCmpInst::FCMP_OEQ: 3312 case FCmpInst::FCMP_UEQ: 3313 case FCmpInst::FCMP_ONE: 3314 case FCmpInst::FCMP_UNE: 3315 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), 3316 RHSC); 3317 } 3318 } 3319 } 3320 } 3321 } 3322 } 3323 3324 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y 3325 Value *X, *Y; 3326 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 3327 return new FCmpInst(I.getSwappedPredicate(), X, Y); 3328 3329 // fcmp (fpext x), (fpext y) -> fcmp x, y 3330 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0)) 3331 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1)) 3332 if (LHSExt->getSrcTy() == RHSExt->getSrcTy()) 3333 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0), 3334 RHSExt->getOperand(0)); 3335 3336 return Changed ? &I : 0; 3337 } 3338