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 "InstCombineInternal.h" 15 #include "llvm/ADT/APSInt.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/ConstantFolding.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/MemoryBuiltins.h" 21 #include "llvm/Analysis/TargetLibraryInfo.h" 22 #include "llvm/Analysis/VectorUtils.h" 23 #include "llvm/IR/ConstantRange.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/GetElementPtrTypeIterator.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/PatternMatch.h" 28 #include "llvm/Support/Debug.h" 29 30 using namespace llvm; 31 using namespace PatternMatch; 32 33 #define DEBUG_TYPE "instcombine" 34 35 // How many times is a select replaced by one of its operands? 36 STATISTIC(NumSel, "Number of select opts"); 37 38 39 static ConstantInt *extractElement(Constant *V, Constant *Idx) { 40 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx)); 41 } 42 43 static bool hasAddOverflow(ConstantInt *Result, 44 ConstantInt *In1, ConstantInt *In2, 45 bool IsSigned) { 46 if (!IsSigned) 47 return Result->getValue().ult(In1->getValue()); 48 49 if (In2->isNegative()) 50 return Result->getValue().sgt(In1->getValue()); 51 return Result->getValue().slt(In1->getValue()); 52 } 53 54 /// Compute Result = In1+In2, returning true if the result overflowed for this 55 /// type. 56 static bool addWithOverflow(Constant *&Result, Constant *In1, 57 Constant *In2, bool IsSigned = false) { 58 Result = ConstantExpr::getAdd(In1, In2); 59 60 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 61 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 62 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 63 if (hasAddOverflow(extractElement(Result, Idx), 64 extractElement(In1, Idx), 65 extractElement(In2, Idx), 66 IsSigned)) 67 return true; 68 } 69 return false; 70 } 71 72 return hasAddOverflow(cast<ConstantInt>(Result), 73 cast<ConstantInt>(In1), cast<ConstantInt>(In2), 74 IsSigned); 75 } 76 77 static bool hasSubOverflow(ConstantInt *Result, 78 ConstantInt *In1, ConstantInt *In2, 79 bool IsSigned) { 80 if (!IsSigned) 81 return Result->getValue().ugt(In1->getValue()); 82 83 if (In2->isNegative()) 84 return Result->getValue().slt(In1->getValue()); 85 86 return Result->getValue().sgt(In1->getValue()); 87 } 88 89 /// Compute Result = In1-In2, returning true if the result overflowed for this 90 /// type. 91 static bool subWithOverflow(Constant *&Result, Constant *In1, 92 Constant *In2, bool IsSigned = false) { 93 Result = ConstantExpr::getSub(In1, In2); 94 95 if (VectorType *VTy = dyn_cast<VectorType>(In1->getType())) { 96 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 97 Constant *Idx = ConstantInt::get(Type::getInt32Ty(In1->getContext()), i); 98 if (hasSubOverflow(extractElement(Result, Idx), 99 extractElement(In1, Idx), 100 extractElement(In2, Idx), 101 IsSigned)) 102 return true; 103 } 104 return false; 105 } 106 107 return hasSubOverflow(cast<ConstantInt>(Result), 108 cast<ConstantInt>(In1), cast<ConstantInt>(In2), 109 IsSigned); 110 } 111 112 /// Given an icmp instruction, return true if any use of this comparison is a 113 /// branch on sign bit comparison. 114 static bool isBranchOnSignBitCheck(ICmpInst &I, bool isSignBit) { 115 for (auto *U : I.users()) 116 if (isa<BranchInst>(U)) 117 return isSignBit; 118 return false; 119 } 120 121 /// Given an exploded icmp instruction, return true if the comparison only 122 /// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if the 123 /// result of the comparison is true when the input value is signed. 124 static bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, 125 bool &TrueIfSigned) { 126 switch (Pred) { 127 case ICmpInst::ICMP_SLT: // True if LHS s< 0 128 TrueIfSigned = true; 129 return RHS == 0; 130 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1 131 TrueIfSigned = true; 132 return RHS.isAllOnesValue(); 133 case ICmpInst::ICMP_SGT: // True if LHS s> -1 134 TrueIfSigned = false; 135 return RHS.isAllOnesValue(); 136 case ICmpInst::ICMP_UGT: 137 // True if LHS u> RHS and RHS == high-bit-mask - 1 138 TrueIfSigned = true; 139 return RHS.isMaxSignedValue(); 140 case ICmpInst::ICMP_UGE: 141 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc) 142 TrueIfSigned = true; 143 return RHS.isSignBit(); 144 default: 145 return false; 146 } 147 } 148 149 /// Returns true if the exploded icmp can be expressed as a signed comparison 150 /// to zero and updates the predicate accordingly. 151 /// The signedness of the comparison is preserved. 152 /// TODO: Refactor with decomposeBitTestICmp()? 153 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) { 154 if (!ICmpInst::isSigned(Pred)) 155 return false; 156 157 if (C == 0) 158 return ICmpInst::isRelational(Pred); 159 160 if (C == 1) { 161 if (Pred == ICmpInst::ICMP_SLT) { 162 Pred = ICmpInst::ICMP_SLE; 163 return true; 164 } 165 } else if (C.isAllOnesValue()) { 166 if (Pred == ICmpInst::ICMP_SGT) { 167 Pred = ICmpInst::ICMP_SGE; 168 return true; 169 } 170 } 171 172 return false; 173 } 174 175 /// Given a signed integer type and a set of known zero and one bits, compute 176 /// the maximum and minimum values that could have the specified known zero and 177 /// known one bits, returning them in Min/Max. 178 static void computeSignedMinMaxValuesFromKnownBits(const APInt &KnownZero, 179 const APInt &KnownOne, 180 APInt &Min, APInt &Max) { 181 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() && 182 KnownZero.getBitWidth() == Min.getBitWidth() && 183 KnownZero.getBitWidth() == Max.getBitWidth() && 184 "KnownZero, KnownOne and Min, Max must have equal bitwidth."); 185 APInt UnknownBits = ~(KnownZero|KnownOne); 186 187 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign 188 // bit if it is unknown. 189 Min = KnownOne; 190 Max = KnownOne|UnknownBits; 191 192 if (UnknownBits.isNegative()) { // Sign bit is unknown 193 Min.setBit(Min.getBitWidth()-1); 194 Max.clearBit(Max.getBitWidth()-1); 195 } 196 } 197 198 /// Given an unsigned integer type and a set of known zero and one bits, compute 199 /// the maximum and minimum values that could have the specified known zero and 200 /// known one bits, returning them in 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 /// This is called when we see this pattern: 217 /// cmp pred (load (gep GV, ...)), cmpcst 218 /// where GV is a global variable with a constant initializer. Try to simplify 219 /// this into some simple computation that does not need the load. For example 220 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 221 /// 222 /// If AndCst is non-null, then the loaded value is masked with that constant 223 /// before doing the comparison. This handles cases like "A[i]&4 == 0". 224 Instruction *InstCombiner::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, 225 GlobalVariable *GV, 226 CmpInst &ICI, 227 ConstantInt *AndCst) { 228 Constant *Init = GV->getInitializer(); 229 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init)) 230 return nullptr; 231 232 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); 233 if (ArrayElementCount > 1024) return nullptr; // Don't blow up on huge arrays. 234 235 // There are many forms of this optimization we can handle, for now, just do 236 // the simple index into a single-dimensional array. 237 // 238 // Require: GEP GV, 0, i {{, constant indices}} 239 if (GEP->getNumOperands() < 3 || 240 !isa<ConstantInt>(GEP->getOperand(1)) || 241 !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 242 isa<Constant>(GEP->getOperand(2))) 243 return nullptr; 244 245 // Check that indices after the variable are constants and in-range for the 246 // type they index. Collect the indices. This is typically for arrays of 247 // structs. 248 SmallVector<unsigned, 4> LaterIndices; 249 250 Type *EltTy = Init->getType()->getArrayElementType(); 251 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 252 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 253 if (!Idx) return nullptr; // Variable index. 254 255 uint64_t IdxVal = Idx->getZExtValue(); 256 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index. 257 258 if (StructType *STy = dyn_cast<StructType>(EltTy)) 259 EltTy = STy->getElementType(IdxVal); 260 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 261 if (IdxVal >= ATy->getNumElements()) return nullptr; 262 EltTy = ATy->getElementType(); 263 } else { 264 return nullptr; // Unknown type. 265 } 266 267 LaterIndices.push_back(IdxVal); 268 } 269 270 enum { Overdefined = -3, Undefined = -2 }; 271 272 // Variables for our state machines. 273 274 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 275 // "i == 47 | i == 87", where 47 is the first index the condition is true for, 276 // and 87 is the second (and last) index. FirstTrueElement is -2 when 277 // undefined, otherwise set to the first true element. SecondTrueElement is 278 // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 279 int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 280 281 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 282 // form "i != 47 & i != 87". Same state transitions as for true elements. 283 int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 284 285 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 286 /// define a state machine that triggers for ranges of values that the index 287 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 288 /// This is -2 when undefined, -3 when overdefined, and otherwise the last 289 /// index in the range (inclusive). We use -2 for undefined here because we 290 /// use relative comparisons and don't want 0-1 to match -1. 291 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 292 293 // MagicBitvector - This is a magic bitvector where we set a bit if the 294 // comparison is true for element 'i'. If there are 64 elements or less in 295 // the array, this will fully represent all the comparison results. 296 uint64_t MagicBitvector = 0; 297 298 // Scan the array and see if one of our patterns matches. 299 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 300 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { 301 Constant *Elt = Init->getAggregateElement(i); 302 if (!Elt) return nullptr; 303 304 // If this is indexing an array of structures, get the structure element. 305 if (!LaterIndices.empty()) 306 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices); 307 308 // If the element is masked, handle it. 309 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 310 311 // Find out if the comparison would be true or false for the i'th element. 312 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 313 CompareRHS, DL, &TLI); 314 // If the result is undef for this element, ignore it. 315 if (isa<UndefValue>(C)) { 316 // Extend range state machines to cover this element in case there is an 317 // undef in the middle of the range. 318 if (TrueRangeEnd == (int)i-1) 319 TrueRangeEnd = i; 320 if (FalseRangeEnd == (int)i-1) 321 FalseRangeEnd = i; 322 continue; 323 } 324 325 // If we can't compute the result for any of the elements, we have to give 326 // up evaluating the entire conditional. 327 if (!isa<ConstantInt>(C)) return nullptr; 328 329 // Otherwise, we know if the comparison is true or false for this element, 330 // update our state machines. 331 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 332 333 // State machine for single/double/range index comparison. 334 if (IsTrueForElt) { 335 // Update the TrueElement state machine. 336 if (FirstTrueElement == Undefined) 337 FirstTrueElement = TrueRangeEnd = i; // First true element. 338 else { 339 // Update double-compare state machine. 340 if (SecondTrueElement == Undefined) 341 SecondTrueElement = i; 342 else 343 SecondTrueElement = Overdefined; 344 345 // Update range state machine. 346 if (TrueRangeEnd == (int)i-1) 347 TrueRangeEnd = i; 348 else 349 TrueRangeEnd = Overdefined; 350 } 351 } else { 352 // Update the FalseElement state machine. 353 if (FirstFalseElement == Undefined) 354 FirstFalseElement = FalseRangeEnd = i; // First false element. 355 else { 356 // Update double-compare state machine. 357 if (SecondFalseElement == Undefined) 358 SecondFalseElement = i; 359 else 360 SecondFalseElement = Overdefined; 361 362 // Update range state machine. 363 if (FalseRangeEnd == (int)i-1) 364 FalseRangeEnd = i; 365 else 366 FalseRangeEnd = Overdefined; 367 } 368 } 369 370 // If this element is in range, update our magic bitvector. 371 if (i < 64 && IsTrueForElt) 372 MagicBitvector |= 1ULL << i; 373 374 // If all of our states become overdefined, bail out early. Since the 375 // predicate is expensive, only check it every 8 elements. This is only 376 // really useful for really huge arrays. 377 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 378 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 379 FalseRangeEnd == Overdefined) 380 return nullptr; 381 } 382 383 // Now that we've scanned the entire array, emit our new comparison(s). We 384 // order the state machines in complexity of the generated code. 385 Value *Idx = GEP->getOperand(2); 386 387 // If the index is larger than the pointer size of the target, truncate the 388 // index down like the GEP would do implicitly. We don't have to do this for 389 // an inbounds GEP because the index can't be out of range. 390 if (!GEP->isInBounds()) { 391 Type *IntPtrTy = DL.getIntPtrType(GEP->getType()); 392 unsigned PtrSize = IntPtrTy->getIntegerBitWidth(); 393 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize) 394 Idx = Builder->CreateTrunc(Idx, IntPtrTy); 395 } 396 397 // If the comparison is only true for one or two elements, emit direct 398 // comparisons. 399 if (SecondTrueElement != Overdefined) { 400 // None true -> false. 401 if (FirstTrueElement == Undefined) 402 return replaceInstUsesWith(ICI, Builder->getFalse()); 403 404 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 405 406 // True for one element -> 'i == 47'. 407 if (SecondTrueElement == Undefined) 408 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 409 410 // True for two elements -> 'i == 47 | i == 72'. 411 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx); 412 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 413 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx); 414 return BinaryOperator::CreateOr(C1, C2); 415 } 416 417 // If the comparison is only false for one or two elements, emit direct 418 // comparisons. 419 if (SecondFalseElement != Overdefined) { 420 // None false -> true. 421 if (FirstFalseElement == Undefined) 422 return replaceInstUsesWith(ICI, Builder->getTrue()); 423 424 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 425 426 // False for one element -> 'i != 47'. 427 if (SecondFalseElement == Undefined) 428 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 429 430 // False for two elements -> 'i != 47 & i != 72'. 431 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx); 432 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 433 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx); 434 return BinaryOperator::CreateAnd(C1, C2); 435 } 436 437 // If the comparison can be replaced with a range comparison for the elements 438 // where it is true, emit the range check. 439 if (TrueRangeEnd != Overdefined) { 440 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 441 442 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 443 if (FirstTrueElement) { 444 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 445 Idx = Builder->CreateAdd(Idx, Offs); 446 } 447 448 Value *End = ConstantInt::get(Idx->getType(), 449 TrueRangeEnd-FirstTrueElement+1); 450 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 451 } 452 453 // False range check. 454 if (FalseRangeEnd != Overdefined) { 455 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 456 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 457 if (FirstFalseElement) { 458 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 459 Idx = Builder->CreateAdd(Idx, Offs); 460 } 461 462 Value *End = ConstantInt::get(Idx->getType(), 463 FalseRangeEnd-FirstFalseElement); 464 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 465 } 466 467 // If a magic bitvector captures the entire comparison state 468 // of this load, replace it with computation that does: 469 // ((magic_cst >> i) & 1) != 0 470 { 471 Type *Ty = nullptr; 472 473 // Look for an appropriate type: 474 // - The type of Idx if the magic fits 475 // - The smallest fitting legal type if we have a DataLayout 476 // - Default to i32 477 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) 478 Ty = Idx->getType(); 479 else 480 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount); 481 482 if (Ty) { 483 Value *V = Builder->CreateIntCast(Idx, Ty, false); 484 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 485 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V); 486 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 487 } 488 } 489 490 return nullptr; 491 } 492 493 /// Return a value that can be used to compare the *offset* implied by a GEP to 494 /// zero. For example, if we have &A[i], we want to return 'i' for 495 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales 496 /// are involved. The above expression would also be legal to codegen as 497 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32). 498 /// This latter 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 const DataLayout &DL) { 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 = GTI.getStructTypeOrNull()) { 521 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 522 } else { 523 uint64_t Size = DL.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 nullptr; 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 = DL.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 nullptr; 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 = GTI.getStructTypeOrNull()) { 551 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 552 } else { 553 uint64_t Size = DL.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 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType()); 562 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth(); 563 if (Offset == 0) { 564 // Cast to intptrty in case a truncation occurs. If an extension is needed, 565 // we don't need to bother extending: the extension won't affect where the 566 // computation crosses zero. 567 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) { 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 nullptr; 587 588 // Okay, we can do this evaluation. Start by converting the index to intptr. 589 if (VariableIdx->getType() != IntPtrTy) 590 VariableIdx = IC.Builder->CreateIntCast(VariableIdx, IntPtrTy, 591 true /*Signed*/); 592 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 593 return IC.Builder->CreateAdd(VariableIdx, OffsetVal, "offset"); 594 } 595 596 /// Returns true if we can rewrite Start as a GEP with pointer Base 597 /// and some integer offset. The nodes that need to be re-written 598 /// for this transformation will be added to Explored. 599 static bool canRewriteGEPAsOffset(Value *Start, Value *Base, 600 const DataLayout &DL, 601 SetVector<Value *> &Explored) { 602 SmallVector<Value *, 16> WorkList(1, Start); 603 Explored.insert(Base); 604 605 // The following traversal gives us an order which can be used 606 // when doing the final transformation. Since in the final 607 // transformation we create the PHI replacement instructions first, 608 // we don't have to get them in any particular order. 609 // 610 // However, for other instructions we will have to traverse the 611 // operands of an instruction first, which means that we have to 612 // do a post-order traversal. 613 while (!WorkList.empty()) { 614 SetVector<PHINode *> PHIs; 615 616 while (!WorkList.empty()) { 617 if (Explored.size() >= 100) 618 return false; 619 620 Value *V = WorkList.back(); 621 622 if (Explored.count(V) != 0) { 623 WorkList.pop_back(); 624 continue; 625 } 626 627 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) && 628 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V)) 629 // We've found some value that we can't explore which is different from 630 // the base. Therefore we can't do this transformation. 631 return false; 632 633 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) { 634 auto *CI = dyn_cast<CastInst>(V); 635 if (!CI->isNoopCast(DL)) 636 return false; 637 638 if (Explored.count(CI->getOperand(0)) == 0) 639 WorkList.push_back(CI->getOperand(0)); 640 } 641 642 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 643 // We're limiting the GEP to having one index. This will preserve 644 // the original pointer type. We could handle more cases in the 645 // future. 646 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() || 647 GEP->getType() != Start->getType()) 648 return false; 649 650 if (Explored.count(GEP->getOperand(0)) == 0) 651 WorkList.push_back(GEP->getOperand(0)); 652 } 653 654 if (WorkList.back() == V) { 655 WorkList.pop_back(); 656 // We've finished visiting this node, mark it as such. 657 Explored.insert(V); 658 } 659 660 if (auto *PN = dyn_cast<PHINode>(V)) { 661 // We cannot transform PHIs on unsplittable basic blocks. 662 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator())) 663 return false; 664 Explored.insert(PN); 665 PHIs.insert(PN); 666 } 667 } 668 669 // Explore the PHI nodes further. 670 for (auto *PN : PHIs) 671 for (Value *Op : PN->incoming_values()) 672 if (Explored.count(Op) == 0) 673 WorkList.push_back(Op); 674 } 675 676 // Make sure that we can do this. Since we can't insert GEPs in a basic 677 // block before a PHI node, we can't easily do this transformation if 678 // we have PHI node users of transformed instructions. 679 for (Value *Val : Explored) { 680 for (Value *Use : Val->uses()) { 681 682 auto *PHI = dyn_cast<PHINode>(Use); 683 auto *Inst = dyn_cast<Instruction>(Val); 684 685 if (Inst == Base || Inst == PHI || !Inst || !PHI || 686 Explored.count(PHI) == 0) 687 continue; 688 689 if (PHI->getParent() == Inst->getParent()) 690 return false; 691 } 692 } 693 return true; 694 } 695 696 // Sets the appropriate insert point on Builder where we can add 697 // a replacement Instruction for V (if that is possible). 698 static void setInsertionPoint(IRBuilder<> &Builder, Value *V, 699 bool Before = true) { 700 if (auto *PHI = dyn_cast<PHINode>(V)) { 701 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt()); 702 return; 703 } 704 if (auto *I = dyn_cast<Instruction>(V)) { 705 if (!Before) 706 I = &*std::next(I->getIterator()); 707 Builder.SetInsertPoint(I); 708 return; 709 } 710 if (auto *A = dyn_cast<Argument>(V)) { 711 // Set the insertion point in the entry block. 712 BasicBlock &Entry = A->getParent()->getEntryBlock(); 713 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt()); 714 return; 715 } 716 // Otherwise, this is a constant and we don't need to set a new 717 // insertion point. 718 assert(isa<Constant>(V) && "Setting insertion point for unknown value!"); 719 } 720 721 /// Returns a re-written value of Start as an indexed GEP using Base as a 722 /// pointer. 723 static Value *rewriteGEPAsOffset(Value *Start, Value *Base, 724 const DataLayout &DL, 725 SetVector<Value *> &Explored) { 726 // Perform all the substitutions. This is a bit tricky because we can 727 // have cycles in our use-def chains. 728 // 1. Create the PHI nodes without any incoming values. 729 // 2. Create all the other values. 730 // 3. Add the edges for the PHI nodes. 731 // 4. Emit GEPs to get the original pointers. 732 // 5. Remove the original instructions. 733 Type *IndexType = IntegerType::get( 734 Base->getContext(), DL.getPointerTypeSizeInBits(Start->getType())); 735 736 DenseMap<Value *, Value *> NewInsts; 737 NewInsts[Base] = ConstantInt::getNullValue(IndexType); 738 739 // Create the new PHI nodes, without adding any incoming values. 740 for (Value *Val : Explored) { 741 if (Val == Base) 742 continue; 743 // Create empty phi nodes. This avoids cyclic dependencies when creating 744 // the remaining instructions. 745 if (auto *PHI = dyn_cast<PHINode>(Val)) 746 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(), 747 PHI->getName() + ".idx", PHI); 748 } 749 IRBuilder<> Builder(Base->getContext()); 750 751 // Create all the other instructions. 752 for (Value *Val : Explored) { 753 754 if (NewInsts.find(Val) != NewInsts.end()) 755 continue; 756 757 if (auto *CI = dyn_cast<CastInst>(Val)) { 758 NewInsts[CI] = NewInsts[CI->getOperand(0)]; 759 continue; 760 } 761 if (auto *GEP = dyn_cast<GEPOperator>(Val)) { 762 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)] 763 : GEP->getOperand(1); 764 setInsertionPoint(Builder, GEP); 765 // Indices might need to be sign extended. GEPs will magically do 766 // this, but we need to do it ourselves here. 767 if (Index->getType()->getScalarSizeInBits() != 768 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) { 769 Index = Builder.CreateSExtOrTrunc( 770 Index, NewInsts[GEP->getOperand(0)]->getType(), 771 GEP->getOperand(0)->getName() + ".sext"); 772 } 773 774 auto *Op = NewInsts[GEP->getOperand(0)]; 775 if (isa<ConstantInt>(Op) && dyn_cast<ConstantInt>(Op)->isZero()) 776 NewInsts[GEP] = Index; 777 else 778 NewInsts[GEP] = Builder.CreateNSWAdd( 779 Op, Index, GEP->getOperand(0)->getName() + ".add"); 780 continue; 781 } 782 if (isa<PHINode>(Val)) 783 continue; 784 785 llvm_unreachable("Unexpected instruction type"); 786 } 787 788 // Add the incoming values to the PHI nodes. 789 for (Value *Val : Explored) { 790 if (Val == Base) 791 continue; 792 // All the instructions have been created, we can now add edges to the 793 // phi nodes. 794 if (auto *PHI = dyn_cast<PHINode>(Val)) { 795 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]); 796 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) { 797 Value *NewIncoming = PHI->getIncomingValue(I); 798 799 if (NewInsts.find(NewIncoming) != NewInsts.end()) 800 NewIncoming = NewInsts[NewIncoming]; 801 802 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I)); 803 } 804 } 805 } 806 807 for (Value *Val : Explored) { 808 if (Val == Base) 809 continue; 810 811 // Depending on the type, for external users we have to emit 812 // a GEP or a GEP + ptrtoint. 813 setInsertionPoint(Builder, Val, false); 814 815 // If required, create an inttoptr instruction for Base. 816 Value *NewBase = Base; 817 if (!Base->getType()->isPointerTy()) 818 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(), 819 Start->getName() + "to.ptr"); 820 821 Value *GEP = Builder.CreateInBoundsGEP( 822 Start->getType()->getPointerElementType(), NewBase, 823 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr"); 824 825 if (!Val->getType()->isPointerTy()) { 826 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(), 827 Val->getName() + ".conv"); 828 GEP = Cast; 829 } 830 Val->replaceAllUsesWith(GEP); 831 } 832 833 return NewInsts[Start]; 834 } 835 836 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express 837 /// the input Value as a constant indexed GEP. Returns a pair containing 838 /// the GEPs Pointer and Index. 839 static std::pair<Value *, Value *> 840 getAsConstantIndexedAddress(Value *V, const DataLayout &DL) { 841 Type *IndexType = IntegerType::get(V->getContext(), 842 DL.getPointerTypeSizeInBits(V->getType())); 843 844 Constant *Index = ConstantInt::getNullValue(IndexType); 845 while (true) { 846 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 847 // We accept only inbouds GEPs here to exclude the possibility of 848 // overflow. 849 if (!GEP->isInBounds()) 850 break; 851 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 && 852 GEP->getType() == V->getType()) { 853 V = GEP->getOperand(0); 854 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1)); 855 Index = ConstantExpr::getAdd( 856 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType)); 857 continue; 858 } 859 break; 860 } 861 if (auto *CI = dyn_cast<IntToPtrInst>(V)) { 862 if (!CI->isNoopCast(DL)) 863 break; 864 V = CI->getOperand(0); 865 continue; 866 } 867 if (auto *CI = dyn_cast<PtrToIntInst>(V)) { 868 if (!CI->isNoopCast(DL)) 869 break; 870 V = CI->getOperand(0); 871 continue; 872 } 873 break; 874 } 875 return {V, Index}; 876 } 877 878 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant. 879 /// We can look through PHIs, GEPs and casts in order to determine a common base 880 /// between GEPLHS and RHS. 881 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, 882 ICmpInst::Predicate Cond, 883 const DataLayout &DL) { 884 if (!GEPLHS->hasAllConstantIndices()) 885 return nullptr; 886 887 Value *PtrBase, *Index; 888 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL); 889 890 // The set of nodes that will take part in this transformation. 891 SetVector<Value *> Nodes; 892 893 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes)) 894 return nullptr; 895 896 // We know we can re-write this as 897 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) 898 // Since we've only looked through inbouds GEPs we know that we 899 // can't have overflow on either side. We can therefore re-write 900 // this as: 901 // OFFSET1 cmp OFFSET2 902 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes); 903 904 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written 905 // GEP having PtrBase as the pointer base, and has returned in NewRHS the 906 // offset. Since Index is the offset of LHS to the base pointer, we will now 907 // compare the offsets instead of comparing the pointers. 908 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS); 909 } 910 911 /// Fold comparisons between a GEP instruction and something else. At this point 912 /// we know that the GEP is on the LHS of the comparison. 913 Instruction *InstCombiner::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 914 ICmpInst::Predicate Cond, 915 Instruction &I) { 916 // Don't transform signed compares of GEPs into index compares. Even if the 917 // GEP is inbounds, the final add of the base pointer can have signed overflow 918 // and would change the result of the icmp. 919 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be 920 // the maximum signed value for the pointer type. 921 if (ICmpInst::isSigned(Cond)) 922 return nullptr; 923 924 // Look through bitcasts and addrspacecasts. We do not however want to remove 925 // 0 GEPs. 926 if (!isa<GetElementPtrInst>(RHS)) 927 RHS = RHS->stripPointerCasts(); 928 929 Value *PtrBase = GEPLHS->getOperand(0); 930 if (PtrBase == RHS && GEPLHS->isInBounds()) { 931 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 932 // This transformation (ignoring the base and scales) is valid because we 933 // know pointers can't overflow since the gep is inbounds. See if we can 934 // output an optimized form. 935 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL); 936 937 // If not, synthesize the offset the hard way. 938 if (!Offset) 939 Offset = EmitGEPOffset(GEPLHS); 940 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 941 Constant::getNullValue(Offset->getType())); 942 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 943 // If the base pointers are different, but the indices are the same, just 944 // compare the base pointer. 945 if (PtrBase != GEPRHS->getOperand(0)) { 946 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); 947 IndicesTheSame &= GEPLHS->getOperand(0)->getType() == 948 GEPRHS->getOperand(0)->getType(); 949 if (IndicesTheSame) 950 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 951 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 952 IndicesTheSame = false; 953 break; 954 } 955 956 // If all indices are the same, just compare the base pointers. 957 if (IndicesTheSame) 958 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 959 960 // If we're comparing GEPs with two base pointers that only differ in type 961 // and both GEPs have only constant indices or just one use, then fold 962 // the compare with the adjusted indices. 963 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() && 964 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && 965 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && 966 PtrBase->stripPointerCasts() == 967 GEPRHS->getOperand(0)->stripPointerCasts()) { 968 Value *LOffset = EmitGEPOffset(GEPLHS); 969 Value *ROffset = EmitGEPOffset(GEPRHS); 970 971 // If we looked through an addrspacecast between different sized address 972 // spaces, the LHS and RHS pointers are different sized 973 // integers. Truncate to the smaller one. 974 Type *LHSIndexTy = LOffset->getType(); 975 Type *RHSIndexTy = ROffset->getType(); 976 if (LHSIndexTy != RHSIndexTy) { 977 if (LHSIndexTy->getPrimitiveSizeInBits() < 978 RHSIndexTy->getPrimitiveSizeInBits()) { 979 ROffset = Builder->CreateTrunc(ROffset, LHSIndexTy); 980 } else 981 LOffset = Builder->CreateTrunc(LOffset, RHSIndexTy); 982 } 983 984 Value *Cmp = Builder->CreateICmp(ICmpInst::getSignedPredicate(Cond), 985 LOffset, ROffset); 986 return replaceInstUsesWith(I, Cmp); 987 } 988 989 // Otherwise, the base pointers are different and the indices are 990 // different. Try convert this to an indexed compare by looking through 991 // PHIs/casts. 992 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 993 } 994 995 // If one of the GEPs has all zero indices, recurse. 996 if (GEPLHS->hasAllZeroIndices()) 997 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 998 ICmpInst::getSwappedPredicate(Cond), I); 999 1000 // If the other GEP has all zero indices, recurse. 1001 if (GEPRHS->hasAllZeroIndices()) 1002 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 1003 1004 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); 1005 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { 1006 // If the GEPs only differ by one index, compare it. 1007 unsigned NumDifferences = 0; // Keep track of # differences. 1008 unsigned DiffOperand = 0; // The operand that differs. 1009 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 1010 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 1011 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() != 1012 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) { 1013 // Irreconcilable differences. 1014 NumDifferences = 2; 1015 break; 1016 } else { 1017 if (NumDifferences++) break; 1018 DiffOperand = i; 1019 } 1020 } 1021 1022 if (NumDifferences == 0) // SAME GEP? 1023 return replaceInstUsesWith(I, // No comparison is needed here. 1024 Builder->getInt1(ICmpInst::isTrueWhenEqual(Cond))); 1025 1026 else if (NumDifferences == 1 && GEPsInBounds) { 1027 Value *LHSV = GEPLHS->getOperand(DiffOperand); 1028 Value *RHSV = GEPRHS->getOperand(DiffOperand); 1029 // Make sure we do a signed comparison here. 1030 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 1031 } 1032 } 1033 1034 // Only lower this if the icmp is the only user of the GEP or if we expect 1035 // the result to fold to a constant! 1036 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 1037 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 1038 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 1039 Value *L = EmitGEPOffset(GEPLHS); 1040 Value *R = EmitGEPOffset(GEPRHS); 1041 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 1042 } 1043 } 1044 1045 // Try convert this to an indexed compare by looking through PHIs/casts as a 1046 // last resort. 1047 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 1048 } 1049 1050 Instruction *InstCombiner::foldAllocaCmp(ICmpInst &ICI, 1051 const AllocaInst *Alloca, 1052 const Value *Other) { 1053 assert(ICI.isEquality() && "Cannot fold non-equality comparison."); 1054 1055 // It would be tempting to fold away comparisons between allocas and any 1056 // pointer not based on that alloca (e.g. an argument). However, even 1057 // though such pointers cannot alias, they can still compare equal. 1058 // 1059 // But LLVM doesn't specify where allocas get their memory, so if the alloca 1060 // doesn't escape we can argue that it's impossible to guess its value, and we 1061 // can therefore act as if any such guesses are wrong. 1062 // 1063 // The code below checks that the alloca doesn't escape, and that it's only 1064 // used in a comparison once (the current instruction). The 1065 // single-comparison-use condition ensures that we're trivially folding all 1066 // comparisons against the alloca consistently, and avoids the risk of 1067 // erroneously folding a comparison of the pointer with itself. 1068 1069 unsigned MaxIter = 32; // Break cycles and bound to constant-time. 1070 1071 SmallVector<const Use *, 32> Worklist; 1072 for (const Use &U : Alloca->uses()) { 1073 if (Worklist.size() >= MaxIter) 1074 return nullptr; 1075 Worklist.push_back(&U); 1076 } 1077 1078 unsigned NumCmps = 0; 1079 while (!Worklist.empty()) { 1080 assert(Worklist.size() <= MaxIter); 1081 const Use *U = Worklist.pop_back_val(); 1082 const Value *V = U->getUser(); 1083 --MaxIter; 1084 1085 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) || 1086 isa<SelectInst>(V)) { 1087 // Track the uses. 1088 } else if (isa<LoadInst>(V)) { 1089 // Loading from the pointer doesn't escape it. 1090 continue; 1091 } else if (const auto *SI = dyn_cast<StoreInst>(V)) { 1092 // Storing *to* the pointer is fine, but storing the pointer escapes it. 1093 if (SI->getValueOperand() == U->get()) 1094 return nullptr; 1095 continue; 1096 } else if (isa<ICmpInst>(V)) { 1097 if (NumCmps++) 1098 return nullptr; // Found more than one cmp. 1099 continue; 1100 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) { 1101 switch (Intrin->getIntrinsicID()) { 1102 // These intrinsics don't escape or compare the pointer. Memset is safe 1103 // because we don't allow ptrtoint. Memcpy and memmove are safe because 1104 // we don't allow stores, so src cannot point to V. 1105 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: 1106 case Intrinsic::dbg_declare: case Intrinsic::dbg_value: 1107 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: 1108 continue; 1109 default: 1110 return nullptr; 1111 } 1112 } else { 1113 return nullptr; 1114 } 1115 for (const Use &U : V->uses()) { 1116 if (Worklist.size() >= MaxIter) 1117 return nullptr; 1118 Worklist.push_back(&U); 1119 } 1120 } 1121 1122 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType()); 1123 return replaceInstUsesWith( 1124 ICI, 1125 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate()))); 1126 } 1127 1128 /// Fold "icmp pred (X+CI), X". 1129 Instruction *InstCombiner::foldICmpAddOpConst(Instruction &ICI, 1130 Value *X, ConstantInt *CI, 1131 ICmpInst::Predicate Pred) { 1132 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 1133 // so the values can never be equal. Similarly for all other "or equals" 1134 // operators. 1135 1136 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 1137 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 1138 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 1139 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 1140 Value *R = 1141 ConstantExpr::getSub(ConstantInt::getAllOnesValue(CI->getType()), CI); 1142 return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 1143 } 1144 1145 // (X+1) >u X --> X <u (0-1) --> X != 255 1146 // (X+2) >u X --> X <u (0-2) --> X <u 254 1147 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 1148 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) 1149 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI)); 1150 1151 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits(); 1152 ConstantInt *SMax = ConstantInt::get(X->getContext(), 1153 APInt::getSignedMaxValue(BitWidth)); 1154 1155 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 1156 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 1157 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 1158 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 1159 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 1160 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 1161 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1162 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI)); 1163 1164 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 1165 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 1166 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 1167 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 1168 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 1169 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 1170 1171 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 1172 Constant *C = Builder->getInt(CI->getValue()-1); 1173 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C)); 1174 } 1175 1176 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> 1177 /// (icmp eq/ne A, Log2(AP2/AP1)) -> 1178 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)). 1179 Instruction *InstCombiner::foldICmpShrConstConst(ICmpInst &I, Value *A, 1180 const APInt &AP1, 1181 const APInt &AP2) { 1182 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1183 1184 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1185 if (I.getPredicate() == I.ICMP_NE) 1186 Pred = CmpInst::getInversePredicate(Pred); 1187 return new ICmpInst(Pred, LHS, RHS); 1188 }; 1189 1190 // Don't bother doing any work for cases which InstSimplify handles. 1191 if (AP2 == 0) 1192 return nullptr; 1193 1194 bool IsAShr = isa<AShrOperator>(I.getOperand(0)); 1195 if (IsAShr) { 1196 if (AP2.isAllOnesValue()) 1197 return nullptr; 1198 if (AP2.isNegative() != AP1.isNegative()) 1199 return nullptr; 1200 if (AP2.sgt(AP1)) 1201 return nullptr; 1202 } 1203 1204 if (!AP1) 1205 // 'A' must be large enough to shift out the highest set bit. 1206 return getICmp(I.ICMP_UGT, A, 1207 ConstantInt::get(A->getType(), AP2.logBase2())); 1208 1209 if (AP1 == AP2) 1210 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1211 1212 int Shift; 1213 if (IsAShr && AP1.isNegative()) 1214 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes(); 1215 else 1216 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros(); 1217 1218 if (Shift > 0) { 1219 if (IsAShr && AP1 == AP2.ashr(Shift)) { 1220 // There are multiple solutions if we are comparing against -1 and the LHS 1221 // of the ashr is not a power of two. 1222 if (AP1.isAllOnesValue() && !AP2.isPowerOf2()) 1223 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift)); 1224 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1225 } else if (AP1 == AP2.lshr(Shift)) { 1226 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1227 } 1228 } 1229 1230 // Shifting const2 will never be equal to const1. 1231 // FIXME: This should always be handled by InstSimplify? 1232 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1233 return replaceInstUsesWith(I, TorF); 1234 } 1235 1236 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" -> 1237 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)). 1238 Instruction *InstCombiner::foldICmpShlConstConst(ICmpInst &I, Value *A, 1239 const APInt &AP1, 1240 const APInt &AP2) { 1241 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1242 1243 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1244 if (I.getPredicate() == I.ICMP_NE) 1245 Pred = CmpInst::getInversePredicate(Pred); 1246 return new ICmpInst(Pred, LHS, RHS); 1247 }; 1248 1249 // Don't bother doing any work for cases which InstSimplify handles. 1250 if (AP2 == 0) 1251 return nullptr; 1252 1253 unsigned AP2TrailingZeros = AP2.countTrailingZeros(); 1254 1255 if (!AP1 && AP2TrailingZeros != 0) 1256 return getICmp( 1257 I.ICMP_UGE, A, 1258 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros)); 1259 1260 if (AP1 == AP2) 1261 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1262 1263 // Get the distance between the lowest bits that are set. 1264 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros; 1265 1266 if (Shift > 0 && AP2.shl(Shift) == AP1) 1267 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1268 1269 // Shifting const2 will never be equal to const1. 1270 // FIXME: This should always be handled by InstSimplify? 1271 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1272 return replaceInstUsesWith(I, TorF); 1273 } 1274 1275 /// The caller has matched a pattern of the form: 1276 /// I = icmp ugt (add (add A, B), CI2), CI1 1277 /// If this is of the form: 1278 /// sum = a + b 1279 /// if (sum+128 >u 255) 1280 /// Then replace it with llvm.sadd.with.overflow.i8. 1281 /// 1282 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, 1283 ConstantInt *CI2, ConstantInt *CI1, 1284 InstCombiner &IC) { 1285 // The transformation we're trying to do here is to transform this into an 1286 // llvm.sadd.with.overflow. To do this, we have to replace the original add 1287 // with a narrower add, and discard the add-with-constant that is part of the 1288 // range check (if we can't eliminate it, this isn't profitable). 1289 1290 // In order to eliminate the add-with-constant, the compare can be its only 1291 // use. 1292 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); 1293 if (!AddWithCst->hasOneUse()) 1294 return nullptr; 1295 1296 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. 1297 if (!CI2->getValue().isPowerOf2()) 1298 return nullptr; 1299 unsigned NewWidth = CI2->getValue().countTrailingZeros(); 1300 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) 1301 return nullptr; 1302 1303 // The width of the new add formed is 1 more than the bias. 1304 ++NewWidth; 1305 1306 // Check to see that CI1 is an all-ones value with NewWidth bits. 1307 if (CI1->getBitWidth() == NewWidth || 1308 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) 1309 return nullptr; 1310 1311 // This is only really a signed overflow check if the inputs have been 1312 // sign-extended; check for that condition. For example, if CI2 is 2^31 and 1313 // the operands of the add are 64 bits wide, we need at least 33 sign bits. 1314 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1; 1315 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits || 1316 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits) 1317 return nullptr; 1318 1319 // In order to replace the original add with a narrower 1320 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant 1321 // and truncates that discard the high bits of the add. Verify that this is 1322 // the case. 1323 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); 1324 for (User *U : OrigAdd->users()) { 1325 if (U == AddWithCst) 1326 continue; 1327 1328 // Only accept truncates for now. We would really like a nice recursive 1329 // predicate like SimplifyDemandedBits, but which goes downwards the use-def 1330 // chain to see which bits of a value are actually demanded. If the 1331 // original add had another add which was then immediately truncated, we 1332 // could still do the transformation. 1333 TruncInst *TI = dyn_cast<TruncInst>(U); 1334 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth) 1335 return nullptr; 1336 } 1337 1338 // If the pattern matches, truncate the inputs to the narrower type and 1339 // use the sadd_with_overflow intrinsic to efficiently compute both the 1340 // result and the overflow bit. 1341 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); 1342 Value *F = Intrinsic::getDeclaration(I.getModule(), 1343 Intrinsic::sadd_with_overflow, NewType); 1344 1345 InstCombiner::BuilderTy *Builder = IC.Builder; 1346 1347 // Put the new code above the original add, in case there are any uses of the 1348 // add between the add and the compare. 1349 Builder->SetInsertPoint(OrigAdd); 1350 1351 Value *TruncA = Builder->CreateTrunc(A, NewType, A->getName() + ".trunc"); 1352 Value *TruncB = Builder->CreateTrunc(B, NewType, B->getName() + ".trunc"); 1353 CallInst *Call = Builder->CreateCall(F, {TruncA, TruncB}, "sadd"); 1354 Value *Add = Builder->CreateExtractValue(Call, 0, "sadd.result"); 1355 Value *ZExt = Builder->CreateZExt(Add, OrigAdd->getType()); 1356 1357 // The inner add was the result of the narrow add, zero extended to the 1358 // wider type. Replace it with the result computed by the intrinsic. 1359 IC.replaceInstUsesWith(*OrigAdd, ZExt); 1360 1361 // The original icmp gets replaced with the overflow value. 1362 return ExtractValueInst::Create(Call, 1, "sadd.overflow"); 1363 } 1364 1365 // Fold icmp Pred X, C. 1366 Instruction *InstCombiner::foldICmpWithConstant(ICmpInst &Cmp) { 1367 CmpInst::Predicate Pred = Cmp.getPredicate(); 1368 Value *X = Cmp.getOperand(0); 1369 1370 const APInt *C; 1371 if (!match(Cmp.getOperand(1), m_APInt(C))) 1372 return nullptr; 1373 1374 Value *A = nullptr, *B = nullptr; 1375 1376 // Match the following pattern, which is a common idiom when writing 1377 // overflow-safe integer arithmetic functions. The source performs an addition 1378 // in wider type and explicitly checks for overflow using comparisons against 1379 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic. 1380 // 1381 // TODO: This could probably be generalized to handle other overflow-safe 1382 // operations if we worked out the formulas to compute the appropriate magic 1383 // constants. 1384 // 1385 // sum = a + b 1386 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 1387 { 1388 ConstantInt *CI2; // I = icmp ugt (add (add A, B), CI2), CI 1389 if (Pred == ICmpInst::ICMP_UGT && 1390 match(X, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) 1391 if (Instruction *Res = processUGT_ADDCST_ADD( 1392 Cmp, A, B, CI2, cast<ConstantInt>(Cmp.getOperand(1)), *this)) 1393 return Res; 1394 } 1395 1396 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0) 1397 if (*C == 0 && Pred == ICmpInst::ICMP_SGT) { 1398 SelectPatternResult SPR = matchSelectPattern(X, A, B); 1399 if (SPR.Flavor == SPF_SMIN) { 1400 if (isKnownPositive(A, DL)) 1401 return new ICmpInst(Pred, B, Cmp.getOperand(1)); 1402 if (isKnownPositive(B, DL)) 1403 return new ICmpInst(Pred, A, Cmp.getOperand(1)); 1404 } 1405 } 1406 1407 // FIXME: Use m_APInt to allow folds for splat constants. 1408 ConstantInt *CI = dyn_cast<ConstantInt>(Cmp.getOperand(1)); 1409 if (!CI) 1410 return nullptr; 1411 1412 // Canonicalize icmp instructions based on dominating conditions. 1413 BasicBlock *Parent = Cmp.getParent(); 1414 BasicBlock *Dom = Parent->getSinglePredecessor(); 1415 auto *BI = Dom ? dyn_cast<BranchInst>(Dom->getTerminator()) : nullptr; 1416 ICmpInst::Predicate Pred2; 1417 BasicBlock *TrueBB, *FalseBB; 1418 ConstantInt *CI2; 1419 if (BI && match(BI, m_Br(m_ICmp(Pred2, m_Specific(X), m_ConstantInt(CI2)), 1420 TrueBB, FalseBB)) && 1421 TrueBB != FalseBB) { 1422 ConstantRange CR = 1423 ConstantRange::makeAllowedICmpRegion(Pred, CI->getValue()); 1424 ConstantRange DominatingCR = 1425 (Parent == TrueBB) 1426 ? ConstantRange::makeExactICmpRegion(Pred2, CI2->getValue()) 1427 : ConstantRange::makeExactICmpRegion( 1428 CmpInst::getInversePredicate(Pred2), CI2->getValue()); 1429 ConstantRange Intersection = DominatingCR.intersectWith(CR); 1430 ConstantRange Difference = DominatingCR.difference(CR); 1431 if (Intersection.isEmptySet()) 1432 return replaceInstUsesWith(Cmp, Builder->getFalse()); 1433 if (Difference.isEmptySet()) 1434 return replaceInstUsesWith(Cmp, Builder->getTrue()); 1435 1436 // If this is a normal comparison, it demands all bits. If it is a sign 1437 // bit comparison, it only demands the sign bit. 1438 bool UnusedBit; 1439 bool IsSignBit = isSignBitCheck(Pred, CI->getValue(), UnusedBit); 1440 1441 // Canonicalizing a sign bit comparison that gets used in a branch, 1442 // pessimizes codegen by generating branch on zero instruction instead 1443 // of a test and branch. So we avoid canonicalizing in such situations 1444 // because test and branch instruction has better branch displacement 1445 // than compare and branch instruction. 1446 if (!isBranchOnSignBitCheck(Cmp, IsSignBit) && !Cmp.isEquality()) { 1447 if (auto *AI = Intersection.getSingleElement()) 1448 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder->getInt(*AI)); 1449 if (auto *AD = Difference.getSingleElement()) 1450 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder->getInt(*AD)); 1451 } 1452 } 1453 1454 return nullptr; 1455 } 1456 1457 /// Fold icmp (trunc X, Y), C. 1458 Instruction *InstCombiner::foldICmpTruncConstant(ICmpInst &Cmp, 1459 Instruction *Trunc, 1460 const APInt *C) { 1461 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1462 Value *X = Trunc->getOperand(0); 1463 if (*C == 1 && C->getBitWidth() > 1) { 1464 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1 1465 Value *V = nullptr; 1466 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V)))) 1467 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1468 ConstantInt::get(V->getType(), 1)); 1469 } 1470 1471 if (Cmp.isEquality() && Trunc->hasOneUse()) { 1472 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 1473 // of the high bits truncated out of x are known. 1474 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(), 1475 SrcBits = X->getType()->getScalarSizeInBits(); 1476 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0); 1477 computeKnownBits(X, KnownZero, KnownOne, 0, &Cmp); 1478 1479 // If all the high bits are known, we can do this xform. 1480 if ((KnownZero | KnownOne).countLeadingOnes() >= SrcBits - DstBits) { 1481 // Pull in the high bits from known-ones set. 1482 APInt NewRHS = C->zext(SrcBits); 1483 NewRHS |= KnownOne & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits); 1484 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS)); 1485 } 1486 } 1487 1488 return nullptr; 1489 } 1490 1491 /// Fold icmp (xor X, Y), C. 1492 Instruction *InstCombiner::foldICmpXorConstant(ICmpInst &Cmp, 1493 BinaryOperator *Xor, 1494 const APInt *C) { 1495 Value *X = Xor->getOperand(0); 1496 Value *Y = Xor->getOperand(1); 1497 const APInt *XorC; 1498 if (!match(Y, m_APInt(XorC))) 1499 return nullptr; 1500 1501 // If this is a comparison that tests the signbit (X < 0) or (x > -1), 1502 // fold the xor. 1503 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1504 if ((Pred == ICmpInst::ICMP_SLT && *C == 0) || 1505 (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue())) { 1506 1507 // If the sign bit of the XorCst is not set, there is no change to 1508 // the operation, just stop using the Xor. 1509 if (!XorC->isNegative()) { 1510 Cmp.setOperand(0, X); 1511 Worklist.Add(Xor); 1512 return &Cmp; 1513 } 1514 1515 // Was the old condition true if the operand is positive? 1516 bool isTrueIfPositive = Pred == ICmpInst::ICMP_SGT; 1517 1518 // If so, the new one isn't. 1519 isTrueIfPositive ^= true; 1520 1521 Constant *CmpConstant = cast<Constant>(Cmp.getOperand(1)); 1522 if (isTrueIfPositive) 1523 return new ICmpInst(ICmpInst::ICMP_SGT, X, SubOne(CmpConstant)); 1524 else 1525 return new ICmpInst(ICmpInst::ICMP_SLT, X, AddOne(CmpConstant)); 1526 } 1527 1528 if (Xor->hasOneUse()) { 1529 // (icmp u/s (xor X SignBit), C) -> (icmp s/u X, (xor C SignBit)) 1530 if (!Cmp.isEquality() && XorC->isSignBit()) { 1531 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() 1532 : Cmp.getSignedPredicate(); 1533 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC)); 1534 } 1535 1536 // (icmp u/s (xor X ~SignBit), C) -> (icmp s/u X, (xor C ~SignBit)) 1537 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) { 1538 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() 1539 : Cmp.getSignedPredicate(); 1540 Pred = Cmp.getSwappedPredicate(Pred); 1541 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), *C ^ *XorC)); 1542 } 1543 } 1544 1545 // (icmp ugt (xor X, C), ~C) -> (icmp ult X, C) 1546 // iff -C is a power of 2 1547 if (Pred == ICmpInst::ICMP_UGT && *XorC == ~(*C) && (*C + 1).isPowerOf2()) 1548 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 1549 1550 // (icmp ult (xor X, C), -C) -> (icmp uge X, C) 1551 // iff -C is a power of 2 1552 if (Pred == ICmpInst::ICMP_ULT && *XorC == -(*C) && C->isPowerOf2()) 1553 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); 1554 1555 return nullptr; 1556 } 1557 1558 /// Fold icmp (and (sh X, Y), C2), C1. 1559 Instruction *InstCombiner::foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, 1560 const APInt *C1, const APInt *C2) { 1561 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0)); 1562 if (!Shift || !Shift->isShift()) 1563 return nullptr; 1564 1565 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could 1566 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in 1567 // code produced by the clang front-end, for bitfield access. 1568 // This seemingly simple opportunity to fold away a shift turns out to be 1569 // rather complicated. See PR17827 for details. 1570 unsigned ShiftOpcode = Shift->getOpcode(); 1571 bool IsShl = ShiftOpcode == Instruction::Shl; 1572 const APInt *C3; 1573 if (match(Shift->getOperand(1), m_APInt(C3))) { 1574 bool CanFold = false; 1575 if (ShiftOpcode == Instruction::AShr) { 1576 // There may be some constraints that make this possible, but nothing 1577 // simple has been discovered yet. 1578 CanFold = false; 1579 } else if (ShiftOpcode == Instruction::Shl) { 1580 // For a left shift, we can fold if the comparison is not signed. We can 1581 // also fold a signed comparison if the mask value and comparison value 1582 // are not negative. These constraints may not be obvious, but we can 1583 // prove that they are correct using an SMT solver. 1584 if (!Cmp.isSigned() || (!C2->isNegative() && !C1->isNegative())) 1585 CanFold = true; 1586 } else if (ShiftOpcode == Instruction::LShr) { 1587 // For a logical right shift, we can fold if the comparison is not signed. 1588 // We can also fold a signed comparison if the shifted mask value and the 1589 // shifted comparison value are not negative. These constraints may not be 1590 // obvious, but we can prove that they are correct using an SMT solver. 1591 if (!Cmp.isSigned() || 1592 (!C2->shl(*C3).isNegative() && !C1->shl(*C3).isNegative())) 1593 CanFold = true; 1594 } 1595 1596 if (CanFold) { 1597 APInt NewCst = IsShl ? C1->lshr(*C3) : C1->shl(*C3); 1598 APInt SameAsC1 = IsShl ? NewCst.shl(*C3) : NewCst.lshr(*C3); 1599 // Check to see if we are shifting out any of the bits being compared. 1600 if (SameAsC1 != *C1) { 1601 // If we shifted bits out, the fold is not going to work out. As a 1602 // special case, check to see if this means that the result is always 1603 // true or false now. 1604 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ) 1605 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType())); 1606 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1607 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType())); 1608 } else { 1609 Cmp.setOperand(1, ConstantInt::get(And->getType(), NewCst)); 1610 APInt NewAndCst = IsShl ? C2->lshr(*C3) : C2->shl(*C3); 1611 And->setOperand(1, ConstantInt::get(And->getType(), NewAndCst)); 1612 And->setOperand(0, Shift->getOperand(0)); 1613 Worklist.Add(Shift); // Shift is dead. 1614 return &Cmp; 1615 } 1616 } 1617 } 1618 1619 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is 1620 // preferable because it allows the C2 << Y expression to be hoisted out of a 1621 // loop if Y is invariant and X is not. 1622 if (Shift->hasOneUse() && *C1 == 0 && Cmp.isEquality() && 1623 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) { 1624 // Compute C2 << Y. 1625 Value *NewShift = 1626 IsShl ? Builder->CreateLShr(And->getOperand(1), Shift->getOperand(1)) 1627 : Builder->CreateShl(And->getOperand(1), Shift->getOperand(1)); 1628 1629 // Compute X & (C2 << Y). 1630 Value *NewAnd = Builder->CreateAnd(Shift->getOperand(0), NewShift); 1631 Cmp.setOperand(0, NewAnd); 1632 return &Cmp; 1633 } 1634 1635 return nullptr; 1636 } 1637 1638 /// Fold icmp (and X, C2), C1. 1639 Instruction *InstCombiner::foldICmpAndConstConst(ICmpInst &Cmp, 1640 BinaryOperator *And, 1641 const APInt *C1) { 1642 const APInt *C2; 1643 if (!match(And->getOperand(1), m_APInt(C2))) 1644 return nullptr; 1645 1646 if (!And->hasOneUse() || !And->getOperand(0)->hasOneUse()) 1647 return nullptr; 1648 1649 // If the LHS is an 'and' of a truncate and we can widen the and/compare to 1650 // the input width without changing the value produced, eliminate the cast: 1651 // 1652 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1' 1653 // 1654 // We can do this transformation if the constants do not have their sign bits 1655 // set or if it is an equality comparison. Extending a relational comparison 1656 // when we're checking the sign bit would not work. 1657 Value *W; 1658 if (match(And->getOperand(0), m_Trunc(m_Value(W))) && 1659 (Cmp.isEquality() || (!C1->isNegative() && !C2->isNegative()))) { 1660 // TODO: Is this a good transform for vectors? Wider types may reduce 1661 // throughput. Should this transform be limited (even for scalars) by using 1662 // ShouldChangeType()? 1663 if (!Cmp.getType()->isVectorTy()) { 1664 Type *WideType = W->getType(); 1665 unsigned WideScalarBits = WideType->getScalarSizeInBits(); 1666 Constant *ZextC1 = ConstantInt::get(WideType, C1->zext(WideScalarBits)); 1667 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits)); 1668 Value *NewAnd = Builder->CreateAnd(W, ZextC2, And->getName()); 1669 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1); 1670 } 1671 } 1672 1673 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2)) 1674 return I; 1675 1676 // (icmp pred (and (or (lshr A, B), A), 1), 0) --> 1677 // (icmp pred (and A, (or (shl 1, B), 1), 0)) 1678 // 1679 // iff pred isn't signed 1680 if (!Cmp.isSigned() && *C1 == 0 && match(And->getOperand(1), m_One())) { 1681 Constant *One = cast<Constant>(And->getOperand(1)); 1682 Value *Or = And->getOperand(0); 1683 Value *A, *B, *LShr; 1684 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) && 1685 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) { 1686 unsigned UsesRemoved = 0; 1687 if (And->hasOneUse()) 1688 ++UsesRemoved; 1689 if (Or->hasOneUse()) 1690 ++UsesRemoved; 1691 if (LShr->hasOneUse()) 1692 ++UsesRemoved; 1693 1694 // Compute A & ((1 << B) | 1) 1695 Value *NewOr = nullptr; 1696 if (auto *C = dyn_cast<Constant>(B)) { 1697 if (UsesRemoved >= 1) 1698 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One); 1699 } else { 1700 if (UsesRemoved >= 3) 1701 NewOr = Builder->CreateOr(Builder->CreateShl(One, B, LShr->getName(), 1702 /*HasNUW=*/true), 1703 One, Or->getName()); 1704 } 1705 if (NewOr) { 1706 Value *NewAnd = Builder->CreateAnd(A, NewOr, And->getName()); 1707 Cmp.setOperand(0, NewAnd); 1708 return &Cmp; 1709 } 1710 } 1711 } 1712 1713 // (X & C2) > C1 --> (X & C2) != 0, if any bit set in (X & C2) will produce a 1714 // result greater than C1. 1715 unsigned NumTZ = C2->countTrailingZeros(); 1716 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && NumTZ < C2->getBitWidth() && 1717 APInt::getOneBitSet(C2->getBitWidth(), NumTZ).ugt(*C1)) { 1718 Constant *Zero = Constant::getNullValue(And->getType()); 1719 return new ICmpInst(ICmpInst::ICMP_NE, And, Zero); 1720 } 1721 1722 return nullptr; 1723 } 1724 1725 /// Fold icmp (and X, Y), C. 1726 Instruction *InstCombiner::foldICmpAndConstant(ICmpInst &Cmp, 1727 BinaryOperator *And, 1728 const APInt *C) { 1729 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C)) 1730 return I; 1731 1732 // TODO: These all require that Y is constant too, so refactor with the above. 1733 1734 // Try to optimize things like "A[i] & 42 == 0" to index computations. 1735 Value *X = And->getOperand(0); 1736 Value *Y = And->getOperand(1); 1737 if (auto *LI = dyn_cast<LoadInst>(X)) 1738 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1739 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1740 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1741 !LI->isVolatile() && isa<ConstantInt>(Y)) { 1742 ConstantInt *C2 = cast<ConstantInt>(Y); 1743 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2)) 1744 return Res; 1745 } 1746 1747 if (!Cmp.isEquality()) 1748 return nullptr; 1749 1750 // X & -C == -C -> X > u ~C 1751 // X & -C != -C -> X <= u ~C 1752 // iff C is a power of 2 1753 if (Cmp.getOperand(1) == Y && (-(*C)).isPowerOf2()) { 1754 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT 1755 : CmpInst::ICMP_ULE; 1756 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1)))); 1757 } 1758 1759 // (X & C2) == 0 -> (trunc X) >= 0 1760 // (X & C2) != 0 -> (trunc X) < 0 1761 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type. 1762 const APInt *C2; 1763 if (And->hasOneUse() && *C == 0 && match(Y, m_APInt(C2))) { 1764 int32_t ExactLogBase2 = C2->exactLogBase2(); 1765 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) { 1766 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1); 1767 if (And->getType()->isVectorTy()) 1768 NTy = VectorType::get(NTy, And->getType()->getVectorNumElements()); 1769 Value *Trunc = Builder->CreateTrunc(X, NTy); 1770 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE 1771 : CmpInst::ICMP_SLT; 1772 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy)); 1773 } 1774 } 1775 1776 return nullptr; 1777 } 1778 1779 /// Fold icmp (or X, Y), C. 1780 Instruction *InstCombiner::foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, 1781 const APInt *C) { 1782 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1783 if (*C == 1) { 1784 // icmp slt signum(V) 1 --> icmp slt V, 1 1785 Value *V = nullptr; 1786 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V)))) 1787 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1788 ConstantInt::get(V->getType(), 1)); 1789 } 1790 1791 if (!Cmp.isEquality() || *C != 0 || !Or->hasOneUse()) 1792 return nullptr; 1793 1794 Value *P, *Q; 1795 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1796 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1797 // -> and (icmp eq P, null), (icmp eq Q, null). 1798 Value *CmpP = 1799 Builder->CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType())); 1800 Value *CmpQ = 1801 Builder->CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType())); 1802 auto LogicOpc = Pred == ICmpInst::Predicate::ICMP_EQ ? Instruction::And 1803 : Instruction::Or; 1804 return BinaryOperator::Create(LogicOpc, CmpP, CmpQ); 1805 } 1806 1807 return nullptr; 1808 } 1809 1810 /// Fold icmp (mul X, Y), C. 1811 Instruction *InstCombiner::foldICmpMulConstant(ICmpInst &Cmp, 1812 BinaryOperator *Mul, 1813 const APInt *C) { 1814 const APInt *MulC; 1815 if (!match(Mul->getOperand(1), m_APInt(MulC))) 1816 return nullptr; 1817 1818 // If this is a test of the sign bit and the multiply is sign-preserving with 1819 // a constant operand, use the multiply LHS operand instead. 1820 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1821 if (isSignTest(Pred, *C) && Mul->hasNoSignedWrap()) { 1822 if (MulC->isNegative()) 1823 Pred = ICmpInst::getSwappedPredicate(Pred); 1824 return new ICmpInst(Pred, Mul->getOperand(0), 1825 Constant::getNullValue(Mul->getType())); 1826 } 1827 1828 return nullptr; 1829 } 1830 1831 /// Fold icmp (shl 1, Y), C. 1832 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, 1833 const APInt *C) { 1834 Value *Y; 1835 if (!match(Shl, m_Shl(m_One(), m_Value(Y)))) 1836 return nullptr; 1837 1838 Type *ShiftType = Shl->getType(); 1839 uint32_t TypeBits = C->getBitWidth(); 1840 bool CIsPowerOf2 = C->isPowerOf2(); 1841 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1842 if (Cmp.isUnsigned()) { 1843 // (1 << Y) pred C -> Y pred Log2(C) 1844 if (!CIsPowerOf2) { 1845 // (1 << Y) < 30 -> Y <= 4 1846 // (1 << Y) <= 30 -> Y <= 4 1847 // (1 << Y) >= 30 -> Y > 4 1848 // (1 << Y) > 30 -> Y > 4 1849 if (Pred == ICmpInst::ICMP_ULT) 1850 Pred = ICmpInst::ICMP_ULE; 1851 else if (Pred == ICmpInst::ICMP_UGE) 1852 Pred = ICmpInst::ICMP_UGT; 1853 } 1854 1855 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31 1856 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31 1857 unsigned CLog2 = C->logBase2(); 1858 if (CLog2 == TypeBits - 1) { 1859 if (Pred == ICmpInst::ICMP_UGE) 1860 Pred = ICmpInst::ICMP_EQ; 1861 else if (Pred == ICmpInst::ICMP_ULT) 1862 Pred = ICmpInst::ICMP_NE; 1863 } 1864 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2)); 1865 } else if (Cmp.isSigned()) { 1866 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1); 1867 if (C->isAllOnesValue()) { 1868 // (1 << Y) <= -1 -> Y == 31 1869 if (Pred == ICmpInst::ICMP_SLE) 1870 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 1871 1872 // (1 << Y) > -1 -> Y != 31 1873 if (Pred == ICmpInst::ICMP_SGT) 1874 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 1875 } else if (!(*C)) { 1876 // (1 << Y) < 0 -> Y == 31 1877 // (1 << Y) <= 0 -> Y == 31 1878 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1879 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 1880 1881 // (1 << Y) >= 0 -> Y != 31 1882 // (1 << Y) > 0 -> Y != 31 1883 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) 1884 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 1885 } 1886 } else if (Cmp.isEquality() && CIsPowerOf2) { 1887 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C->logBase2())); 1888 } 1889 1890 return nullptr; 1891 } 1892 1893 /// Fold icmp (shl X, Y), C. 1894 Instruction *InstCombiner::foldICmpShlConstant(ICmpInst &Cmp, 1895 BinaryOperator *Shl, 1896 const APInt *C) { 1897 const APInt *ShiftVal; 1898 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal))) 1899 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), *C, *ShiftVal); 1900 1901 const APInt *ShiftAmt; 1902 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt))) 1903 return foldICmpShlOne(Cmp, Shl, C); 1904 1905 // Check that the shift amount is in range. If not, don't perform undefined 1906 // shifts. When the shift is visited, it will be simplified. 1907 unsigned TypeBits = C->getBitWidth(); 1908 if (ShiftAmt->uge(TypeBits)) 1909 return nullptr; 1910 1911 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1912 Value *X = Shl->getOperand(0); 1913 Type *ShType = Shl->getType(); 1914 1915 // NSW guarantees that we are only shifting out sign bits from the high bits, 1916 // so we can ASHR the compare constant without needing a mask and eliminate 1917 // the shift. 1918 if (Shl->hasNoSignedWrap()) { 1919 if (Pred == ICmpInst::ICMP_SGT) { 1920 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt) 1921 APInt ShiftedC = C->ashr(*ShiftAmt); 1922 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1923 } 1924 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) { 1925 // This is the same code as the SGT case, but assert the pre-condition 1926 // that is needed for this to work with equality predicates. 1927 assert(C->ashr(*ShiftAmt).shl(*ShiftAmt) == *C && 1928 "Compare known true or false was not folded"); 1929 APInt ShiftedC = C->ashr(*ShiftAmt); 1930 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1931 } 1932 if (Pred == ICmpInst::ICMP_SLT) { 1933 // SLE is the same as above, but SLE is canonicalized to SLT, so convert: 1934 // (X << S) <=s C is equiv to X <=s (C >> S) for all C 1935 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX 1936 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN 1937 assert(!C->isMinSignedValue() && "Unexpected icmp slt"); 1938 APInt ShiftedC = (*C - 1).ashr(*ShiftAmt) + 1; 1939 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1940 } 1941 // If this is a signed comparison to 0 and the shift is sign preserving, 1942 // use the shift LHS operand instead; isSignTest may change 'Pred', so only 1943 // do that if we're sure to not continue on in this function. 1944 if (isSignTest(Pred, *C)) 1945 return new ICmpInst(Pred, X, Constant::getNullValue(ShType)); 1946 } 1947 1948 // NUW guarantees that we are only shifting out zero bits from the high bits, 1949 // so we can LSHR the compare constant without needing a mask and eliminate 1950 // the shift. 1951 if (Shl->hasNoUnsignedWrap()) { 1952 if (Pred == ICmpInst::ICMP_UGT) { 1953 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt) 1954 APInt ShiftedC = C->lshr(*ShiftAmt); 1955 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1956 } 1957 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) { 1958 // This is the same code as the UGT case, but assert the pre-condition 1959 // that is needed for this to work with equality predicates. 1960 assert(C->lshr(*ShiftAmt).shl(*ShiftAmt) == *C && 1961 "Compare known true or false was not folded"); 1962 APInt ShiftedC = C->lshr(*ShiftAmt); 1963 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1964 } 1965 if (Pred == ICmpInst::ICMP_ULT) { 1966 // ULE is the same as above, but ULE is canonicalized to ULT, so convert: 1967 // (X << S) <=u C is equiv to X <=u (C >> S) for all C 1968 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u 1969 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0 1970 assert(C->ugt(0) && "ult 0 should have been eliminated"); 1971 APInt ShiftedC = (*C - 1).lshr(*ShiftAmt) + 1; 1972 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 1973 } 1974 } 1975 1976 if (Cmp.isEquality() && Shl->hasOneUse()) { 1977 // Strength-reduce the shift into an 'and'. 1978 Constant *Mask = ConstantInt::get( 1979 ShType, 1980 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue())); 1981 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask"); 1982 Constant *LShrC = ConstantInt::get(ShType, C->lshr(*ShiftAmt)); 1983 return new ICmpInst(Pred, And, LShrC); 1984 } 1985 1986 // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 1987 bool TrueIfSigned = false; 1988 if (Shl->hasOneUse() && isSignBitCheck(Pred, *C, TrueIfSigned)) { 1989 // (X << 31) <s 0 --> (X & 1) != 0 1990 Constant *Mask = ConstantInt::get( 1991 ShType, 1992 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1)); 1993 Value *And = Builder->CreateAnd(X, Mask, Shl->getName() + ".mask"); 1994 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 1995 And, Constant::getNullValue(ShType)); 1996 } 1997 1998 // Transform (icmp pred iM (shl iM %v, N), C) 1999 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N)) 2000 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N. 2001 // This enables us to get rid of the shift in favor of a trunc that may be 2002 // free on the target. It has the additional benefit of comparing to a 2003 // smaller constant that may be more target-friendly. 2004 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1); 2005 if (Shl->hasOneUse() && Amt != 0 && C->countTrailingZeros() >= Amt && 2006 DL.isLegalInteger(TypeBits - Amt)) { 2007 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt); 2008 if (ShType->isVectorTy()) 2009 TruncTy = VectorType::get(TruncTy, ShType->getVectorNumElements()); 2010 Constant *NewC = 2011 ConstantInt::get(TruncTy, C->ashr(*ShiftAmt).trunc(TypeBits - Amt)); 2012 return new ICmpInst(Pred, Builder->CreateTrunc(X, TruncTy), NewC); 2013 } 2014 2015 return nullptr; 2016 } 2017 2018 /// Fold icmp ({al}shr X, Y), C. 2019 Instruction *InstCombiner::foldICmpShrConstant(ICmpInst &Cmp, 2020 BinaryOperator *Shr, 2021 const APInt *C) { 2022 // An exact shr only shifts out zero bits, so: 2023 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0 2024 Value *X = Shr->getOperand(0); 2025 CmpInst::Predicate Pred = Cmp.getPredicate(); 2026 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && *C == 0) 2027 return new ICmpInst(Pred, X, Cmp.getOperand(1)); 2028 2029 const APInt *ShiftVal; 2030 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal))) 2031 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), *C, *ShiftVal); 2032 2033 const APInt *ShiftAmt; 2034 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt))) 2035 return nullptr; 2036 2037 // Check that the shift amount is in range. If not, don't perform undefined 2038 // shifts. When the shift is visited it will be simplified. 2039 unsigned TypeBits = C->getBitWidth(); 2040 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits); 2041 if (ShAmtVal >= TypeBits || ShAmtVal == 0) 2042 return nullptr; 2043 2044 bool IsAShr = Shr->getOpcode() == Instruction::AShr; 2045 if (!Cmp.isEquality()) { 2046 // If we have an unsigned comparison and an ashr, we can't simplify this. 2047 // Similarly for signed comparisons with lshr. 2048 if (Cmp.isSigned() != IsAShr) 2049 return nullptr; 2050 2051 // Otherwise, all lshr and most exact ashr's are equivalent to a udiv/sdiv 2052 // by a power of 2. Since we already have logic to simplify these, 2053 // transform to div and then simplify the resultant comparison. 2054 if (IsAShr && (!Shr->isExact() || ShAmtVal == TypeBits - 1)) 2055 return nullptr; 2056 2057 // Revisit the shift (to delete it). 2058 Worklist.Add(Shr); 2059 2060 Constant *DivCst = ConstantInt::get( 2061 Shr->getType(), APInt::getOneBitSet(TypeBits, ShAmtVal)); 2062 2063 Value *Tmp = IsAShr ? Builder->CreateSDiv(X, DivCst, "", Shr->isExact()) 2064 : Builder->CreateUDiv(X, DivCst, "", Shr->isExact()); 2065 2066 Cmp.setOperand(0, Tmp); 2067 2068 // If the builder folded the binop, just return it. 2069 BinaryOperator *TheDiv = dyn_cast<BinaryOperator>(Tmp); 2070 if (!TheDiv) 2071 return &Cmp; 2072 2073 // Otherwise, fold this div/compare. 2074 assert(TheDiv->getOpcode() == Instruction::SDiv || 2075 TheDiv->getOpcode() == Instruction::UDiv); 2076 2077 Instruction *Res = foldICmpDivConstant(Cmp, TheDiv, C); 2078 assert(Res && "This div/cst should have folded!"); 2079 return Res; 2080 } 2081 2082 // Handle equality comparisons of shift-by-constant. 2083 2084 // If the comparison constant changes with the shift, the comparison cannot 2085 // succeed (bits of the comparison constant cannot match the shifted value). 2086 // This should be known by InstSimplify and already be folded to true/false. 2087 assert(((IsAShr && C->shl(ShAmtVal).ashr(ShAmtVal) == *C) || 2088 (!IsAShr && C->shl(ShAmtVal).lshr(ShAmtVal) == *C)) && 2089 "Expected icmp+shr simplify did not occur."); 2090 2091 // Check if the bits shifted out are known to be zero. If so, we can compare 2092 // against the unshifted value: 2093 // (X & 4) >> 1 == 2 --> (X & 4) == 4. 2094 Constant *ShiftedCmpRHS = ConstantInt::get(Shr->getType(), *C << ShAmtVal); 2095 if (Shr->hasOneUse()) { 2096 if (Shr->isExact()) 2097 return new ICmpInst(Pred, X, ShiftedCmpRHS); 2098 2099 // Otherwise strength reduce the shift into an 'and'. 2100 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 2101 Constant *Mask = ConstantInt::get(Shr->getType(), Val); 2102 Value *And = Builder->CreateAnd(X, Mask, Shr->getName() + ".mask"); 2103 return new ICmpInst(Pred, And, ShiftedCmpRHS); 2104 } 2105 2106 return nullptr; 2107 } 2108 2109 /// Fold icmp (udiv X, Y), C. 2110 Instruction *InstCombiner::foldICmpUDivConstant(ICmpInst &Cmp, 2111 BinaryOperator *UDiv, 2112 const APInt *C) { 2113 const APInt *C2; 2114 if (!match(UDiv->getOperand(0), m_APInt(C2))) 2115 return nullptr; 2116 2117 assert(C2 != 0 && "udiv 0, X should have been simplified already."); 2118 2119 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1)) 2120 Value *Y = UDiv->getOperand(1); 2121 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) { 2122 assert(!C->isMaxValue() && 2123 "icmp ugt X, UINT_MAX should have been simplified already."); 2124 return new ICmpInst(ICmpInst::ICMP_ULE, Y, 2125 ConstantInt::get(Y->getType(), C2->udiv(*C + 1))); 2126 } 2127 2128 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C) 2129 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) { 2130 assert(C != 0 && "icmp ult X, 0 should have been simplified already."); 2131 return new ICmpInst(ICmpInst::ICMP_UGT, Y, 2132 ConstantInt::get(Y->getType(), C2->udiv(*C))); 2133 } 2134 2135 return nullptr; 2136 } 2137 2138 /// Fold icmp ({su}div X, Y), C. 2139 Instruction *InstCombiner::foldICmpDivConstant(ICmpInst &Cmp, 2140 BinaryOperator *Div, 2141 const APInt *C) { 2142 // Fold: icmp pred ([us]div X, C2), C -> range test 2143 // Fold this div into the comparison, producing a range check. 2144 // Determine, based on the divide type, what the range is being 2145 // checked. If there is an overflow on the low or high side, remember 2146 // it, otherwise compute the range [low, hi) bounding the new value. 2147 // See: InsertRangeTest above for the kinds of replacements possible. 2148 const APInt *C2; 2149 if (!match(Div->getOperand(1), m_APInt(C2))) 2150 return nullptr; 2151 2152 // FIXME: If the operand types don't match the type of the divide 2153 // then don't attempt this transform. The code below doesn't have the 2154 // logic to deal with a signed divide and an unsigned compare (and 2155 // vice versa). This is because (x /s C2) <s C produces different 2156 // results than (x /s C2) <u C or (x /u C2) <s C or even 2157 // (x /u C2) <u C. Simply casting the operands and result won't 2158 // work. :( The if statement below tests that condition and bails 2159 // if it finds it. 2160 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv; 2161 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) 2162 return nullptr; 2163 2164 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with 2165 // INT_MIN will also fail if the divisor is 1. Although folds of all these 2166 // division-by-constant cases should be present, we can not assert that they 2167 // have happened before we reach this icmp instruction. 2168 if (*C2 == 0 || *C2 == 1 || (DivIsSigned && C2->isAllOnesValue())) 2169 return nullptr; 2170 2171 // TODO: We could do all of the computations below using APInt. 2172 Constant *CmpRHS = cast<Constant>(Cmp.getOperand(1)); 2173 Constant *DivRHS = cast<Constant>(Div->getOperand(1)); 2174 2175 // Compute Prod = CmpRHS * DivRHS. We are essentially solving an equation of 2176 // form X / C2 = C. We solve for X by multiplying C2 (DivRHS) and C (CmpRHS). 2177 // By solving for X, we can turn this into a range check instead of computing 2178 // a divide. 2179 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS); 2180 2181 // Determine if the product overflows by seeing if the product is not equal to 2182 // the divide. Make sure we do the same kind of divide as in the LHS 2183 // instruction that we're folding. 2184 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) 2185 : ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS; 2186 2187 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2188 2189 // If the division is known to be exact, then there is no remainder from the 2190 // divide, so the covered range size is unit, otherwise it is the divisor. 2191 Constant *RangeSize = 2192 Div->isExact() ? ConstantInt::get(Div->getType(), 1) : DivRHS; 2193 2194 // Figure out the interval that is being checked. For example, a comparison 2195 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 2196 // Compute this interval based on the constants involved and the signedness of 2197 // the compare/divide. This computes a half-open interval, keeping track of 2198 // whether either value in the interval overflows. After analysis each 2199 // overflow variable is set to 0 if it's corresponding bound variable is valid 2200 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 2201 int LoOverflow = 0, HiOverflow = 0; 2202 Constant *LoBound = nullptr, *HiBound = nullptr; 2203 2204 if (!DivIsSigned) { // udiv 2205 // e.g. X/5 op 3 --> [15, 20) 2206 LoBound = Prod; 2207 HiOverflow = LoOverflow = ProdOV; 2208 if (!HiOverflow) { 2209 // If this is not an exact divide, then many values in the range collapse 2210 // to the same result value. 2211 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false); 2212 } 2213 } else if (C2->isStrictlyPositive()) { // Divisor is > 0. 2214 if (*C == 0) { // (X / pos) op 0 2215 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 2216 LoBound = ConstantExpr::getNeg(SubOne(RangeSize)); 2217 HiBound = RangeSize; 2218 } else if (C->isStrictlyPositive()) { // (X / pos) op pos 2219 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 2220 HiOverflow = LoOverflow = ProdOV; 2221 if (!HiOverflow) 2222 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true); 2223 } else { // (X / pos) op neg 2224 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 2225 HiBound = AddOne(Prod); 2226 LoOverflow = HiOverflow = ProdOV ? -1 : 0; 2227 if (!LoOverflow) { 2228 Constant *DivNeg = ConstantExpr::getNeg(RangeSize); 2229 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 2230 } 2231 } 2232 } else if (C2->isNegative()) { // Divisor is < 0. 2233 if (Div->isExact()) 2234 RangeSize = ConstantExpr::getNeg(RangeSize); 2235 if (*C == 0) { // (X / neg) op 0 2236 // e.g. X/-5 op 0 --> [-4, 5) 2237 LoBound = AddOne(RangeSize); 2238 HiBound = ConstantExpr::getNeg(RangeSize); 2239 if (HiBound == DivRHS) { // -INTMIN = INTMIN 2240 HiOverflow = 1; // [INTMIN+1, overflow) 2241 HiBound = nullptr; // e.g. X/INTMIN = 0 --> X > INTMIN 2242 } 2243 } else if (C->isStrictlyPositive()) { // (X / neg) op pos 2244 // e.g. X/-5 op 3 --> [-19, -14) 2245 HiBound = AddOne(Prod); 2246 HiOverflow = LoOverflow = ProdOV ? -1 : 0; 2247 if (!LoOverflow) 2248 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; 2249 } else { // (X / neg) op neg 2250 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 2251 LoOverflow = HiOverflow = ProdOV; 2252 if (!HiOverflow) 2253 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true); 2254 } 2255 2256 // Dividing by a negative swaps the condition. LT <-> GT 2257 Pred = ICmpInst::getSwappedPredicate(Pred); 2258 } 2259 2260 Value *X = Div->getOperand(0); 2261 switch (Pred) { 2262 default: llvm_unreachable("Unhandled icmp opcode!"); 2263 case ICmpInst::ICMP_EQ: 2264 if (LoOverflow && HiOverflow) 2265 return replaceInstUsesWith(Cmp, Builder->getFalse()); 2266 if (HiOverflow) 2267 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 2268 ICmpInst::ICMP_UGE, X, LoBound); 2269 if (LoOverflow) 2270 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 2271 ICmpInst::ICMP_ULT, X, HiBound); 2272 return replaceInstUsesWith( 2273 Cmp, insertRangeTest(X, LoBound->getUniqueInteger(), 2274 HiBound->getUniqueInteger(), DivIsSigned, true)); 2275 case ICmpInst::ICMP_NE: 2276 if (LoOverflow && HiOverflow) 2277 return replaceInstUsesWith(Cmp, Builder->getTrue()); 2278 if (HiOverflow) 2279 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 2280 ICmpInst::ICMP_ULT, X, LoBound); 2281 if (LoOverflow) 2282 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 2283 ICmpInst::ICMP_UGE, X, HiBound); 2284 return replaceInstUsesWith(Cmp, 2285 insertRangeTest(X, LoBound->getUniqueInteger(), 2286 HiBound->getUniqueInteger(), 2287 DivIsSigned, false)); 2288 case ICmpInst::ICMP_ULT: 2289 case ICmpInst::ICMP_SLT: 2290 if (LoOverflow == +1) // Low bound is greater than input range. 2291 return replaceInstUsesWith(Cmp, Builder->getTrue()); 2292 if (LoOverflow == -1) // Low bound is less than input range. 2293 return replaceInstUsesWith(Cmp, Builder->getFalse()); 2294 return new ICmpInst(Pred, X, LoBound); 2295 case ICmpInst::ICMP_UGT: 2296 case ICmpInst::ICMP_SGT: 2297 if (HiOverflow == +1) // High bound greater than input range. 2298 return replaceInstUsesWith(Cmp, Builder->getFalse()); 2299 if (HiOverflow == -1) // High bound less than input range. 2300 return replaceInstUsesWith(Cmp, Builder->getTrue()); 2301 if (Pred == ICmpInst::ICMP_UGT) 2302 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound); 2303 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound); 2304 } 2305 2306 return nullptr; 2307 } 2308 2309 /// Fold icmp (sub X, Y), C. 2310 Instruction *InstCombiner::foldICmpSubConstant(ICmpInst &Cmp, 2311 BinaryOperator *Sub, 2312 const APInt *C) { 2313 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1); 2314 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2315 2316 // The following transforms are only worth it if the only user of the subtract 2317 // is the icmp. 2318 if (!Sub->hasOneUse()) 2319 return nullptr; 2320 2321 if (Sub->hasNoSignedWrap()) { 2322 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y) 2323 if (Pred == ICmpInst::ICMP_SGT && C->isAllOnesValue()) 2324 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 2325 2326 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y) 2327 if (Pred == ICmpInst::ICMP_SGT && *C == 0) 2328 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 2329 2330 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y) 2331 if (Pred == ICmpInst::ICMP_SLT && *C == 0) 2332 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 2333 2334 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y) 2335 if (Pred == ICmpInst::ICMP_SLT && *C == 1) 2336 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 2337 } 2338 2339 const APInt *C2; 2340 if (!match(X, m_APInt(C2))) 2341 return nullptr; 2342 2343 // C2 - Y <u C -> (Y | (C - 1)) == C2 2344 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2 2345 if (Pred == ICmpInst::ICMP_ULT && C->isPowerOf2() && 2346 (*C2 & (*C - 1)) == (*C - 1)) 2347 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateOr(Y, *C - 1), X); 2348 2349 // C2 - Y >u C -> (Y | C) != C2 2350 // iff C2 & C == C and C + 1 is a power of 2 2351 if (Pred == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && (*C2 & *C) == *C) 2352 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateOr(Y, *C), X); 2353 2354 return nullptr; 2355 } 2356 2357 /// Fold icmp (add X, Y), C. 2358 Instruction *InstCombiner::foldICmpAddConstant(ICmpInst &Cmp, 2359 BinaryOperator *Add, 2360 const APInt *C) { 2361 Value *Y = Add->getOperand(1); 2362 const APInt *C2; 2363 if (Cmp.isEquality() || !match(Y, m_APInt(C2))) 2364 return nullptr; 2365 2366 // Fold icmp pred (add X, C2), C. 2367 Value *X = Add->getOperand(0); 2368 Type *Ty = Add->getType(); 2369 auto CR = 2370 ConstantRange::makeExactICmpRegion(Cmp.getPredicate(), *C).subtract(*C2); 2371 const APInt &Upper = CR.getUpper(); 2372 const APInt &Lower = CR.getLower(); 2373 if (Cmp.isSigned()) { 2374 if (Lower.isSignBit()) 2375 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper)); 2376 if (Upper.isSignBit()) 2377 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower)); 2378 } else { 2379 if (Lower.isMinValue()) 2380 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper)); 2381 if (Upper.isMinValue()) 2382 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower)); 2383 } 2384 2385 if (!Add->hasOneUse()) 2386 return nullptr; 2387 2388 // X+C <u C2 -> (X & -C2) == C 2389 // iff C & (C2-1) == 0 2390 // C2 is a power of 2 2391 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && C->isPowerOf2() && 2392 (*C2 & (*C - 1)) == 0) 2393 return new ICmpInst(ICmpInst::ICMP_EQ, Builder->CreateAnd(X, -(*C)), 2394 ConstantExpr::getNeg(cast<Constant>(Y))); 2395 2396 // X+C >u C2 -> (X & ~C2) != C 2397 // iff C & C2 == 0 2398 // C2+1 is a power of 2 2399 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && (*C + 1).isPowerOf2() && 2400 (*C2 & *C) == 0) 2401 return new ICmpInst(ICmpInst::ICMP_NE, Builder->CreateAnd(X, ~(*C)), 2402 ConstantExpr::getNeg(cast<Constant>(Y))); 2403 2404 return nullptr; 2405 } 2406 2407 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C 2408 /// where X is some kind of instruction. 2409 Instruction *InstCombiner::foldICmpInstWithConstant(ICmpInst &Cmp) { 2410 const APInt *C; 2411 if (!match(Cmp.getOperand(1), m_APInt(C))) 2412 return nullptr; 2413 2414 BinaryOperator *BO; 2415 if (match(Cmp.getOperand(0), m_BinOp(BO))) { 2416 switch (BO->getOpcode()) { 2417 case Instruction::Xor: 2418 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C)) 2419 return I; 2420 break; 2421 case Instruction::And: 2422 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C)) 2423 return I; 2424 break; 2425 case Instruction::Or: 2426 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C)) 2427 return I; 2428 break; 2429 case Instruction::Mul: 2430 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C)) 2431 return I; 2432 break; 2433 case Instruction::Shl: 2434 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C)) 2435 return I; 2436 break; 2437 case Instruction::LShr: 2438 case Instruction::AShr: 2439 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C)) 2440 return I; 2441 break; 2442 case Instruction::UDiv: 2443 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C)) 2444 return I; 2445 LLVM_FALLTHROUGH; 2446 case Instruction::SDiv: 2447 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C)) 2448 return I; 2449 break; 2450 case Instruction::Sub: 2451 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C)) 2452 return I; 2453 break; 2454 case Instruction::Add: 2455 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C)) 2456 return I; 2457 break; 2458 default: 2459 break; 2460 } 2461 // TODO: These folds could be refactored to be part of the above calls. 2462 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C)) 2463 return I; 2464 } 2465 2466 Instruction *LHSI; 2467 if (match(Cmp.getOperand(0), m_Instruction(LHSI)) && 2468 LHSI->getOpcode() == Instruction::Trunc) 2469 if (Instruction *I = foldICmpTruncConstant(Cmp, LHSI, C)) 2470 return I; 2471 2472 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, C)) 2473 return I; 2474 2475 return nullptr; 2476 } 2477 2478 /// Fold an icmp equality instruction with binary operator LHS and constant RHS: 2479 /// icmp eq/ne BO, C. 2480 Instruction *InstCombiner::foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, 2481 BinaryOperator *BO, 2482 const APInt *C) { 2483 // TODO: Some of these folds could work with arbitrary constants, but this 2484 // function is limited to scalar and vector splat constants. 2485 if (!Cmp.isEquality()) 2486 return nullptr; 2487 2488 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2489 bool isICMP_NE = Pred == ICmpInst::ICMP_NE; 2490 Constant *RHS = cast<Constant>(Cmp.getOperand(1)); 2491 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 2492 2493 switch (BO->getOpcode()) { 2494 case Instruction::SRem: 2495 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 2496 if (*C == 0 && BO->hasOneUse()) { 2497 const APInt *BOC; 2498 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) { 2499 Value *NewRem = Builder->CreateURem(BOp0, BOp1, BO->getName()); 2500 return new ICmpInst(Pred, NewRem, 2501 Constant::getNullValue(BO->getType())); 2502 } 2503 } 2504 break; 2505 case Instruction::Add: { 2506 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 2507 const APInt *BOC; 2508 if (match(BOp1, m_APInt(BOC))) { 2509 if (BO->hasOneUse()) { 2510 Constant *SubC = ConstantExpr::getSub(RHS, cast<Constant>(BOp1)); 2511 return new ICmpInst(Pred, BOp0, SubC); 2512 } 2513 } else if (*C == 0) { 2514 // Replace ((add A, B) != 0) with (A != -B) if A or B is 2515 // efficiently invertible, or if the add has just this one use. 2516 if (Value *NegVal = dyn_castNegVal(BOp1)) 2517 return new ICmpInst(Pred, BOp0, NegVal); 2518 if (Value *NegVal = dyn_castNegVal(BOp0)) 2519 return new ICmpInst(Pred, NegVal, BOp1); 2520 if (BO->hasOneUse()) { 2521 Value *Neg = Builder->CreateNeg(BOp1); 2522 Neg->takeName(BO); 2523 return new ICmpInst(Pred, BOp0, Neg); 2524 } 2525 } 2526 break; 2527 } 2528 case Instruction::Xor: 2529 if (BO->hasOneUse()) { 2530 if (Constant *BOC = dyn_cast<Constant>(BOp1)) { 2531 // For the xor case, we can xor two constants together, eliminating 2532 // the explicit xor. 2533 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC)); 2534 } else if (*C == 0) { 2535 // Replace ((xor A, B) != 0) with (A != B) 2536 return new ICmpInst(Pred, BOp0, BOp1); 2537 } 2538 } 2539 break; 2540 case Instruction::Sub: 2541 if (BO->hasOneUse()) { 2542 const APInt *BOC; 2543 if (match(BOp0, m_APInt(BOC))) { 2544 // Replace ((sub BOC, B) != C) with (B != BOC-C). 2545 Constant *SubC = ConstantExpr::getSub(cast<Constant>(BOp0), RHS); 2546 return new ICmpInst(Pred, BOp1, SubC); 2547 } else if (*C == 0) { 2548 // Replace ((sub A, B) != 0) with (A != B). 2549 return new ICmpInst(Pred, BOp0, BOp1); 2550 } 2551 } 2552 break; 2553 case Instruction::Or: { 2554 const APInt *BOC; 2555 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) { 2556 // Comparing if all bits outside of a constant mask are set? 2557 // Replace (X | C) == -1 with (X & ~C) == ~C. 2558 // This removes the -1 constant. 2559 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1)); 2560 Value *And = Builder->CreateAnd(BOp0, NotBOC); 2561 return new ICmpInst(Pred, And, NotBOC); 2562 } 2563 break; 2564 } 2565 case Instruction::And: { 2566 const APInt *BOC; 2567 if (match(BOp1, m_APInt(BOC))) { 2568 // If we have ((X & C) == C), turn it into ((X & C) != 0). 2569 if (C == BOC && C->isPowerOf2()) 2570 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, 2571 BO, Constant::getNullValue(RHS->getType())); 2572 2573 // Don't perform the following transforms if the AND has multiple uses 2574 if (!BO->hasOneUse()) 2575 break; 2576 2577 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0 2578 if (BOC->isSignBit()) { 2579 Constant *Zero = Constant::getNullValue(BOp0->getType()); 2580 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 2581 return new ICmpInst(NewPred, BOp0, Zero); 2582 } 2583 2584 // ((X & ~7) == 0) --> X < 8 2585 if (*C == 0 && (~(*BOC) + 1).isPowerOf2()) { 2586 Constant *NegBOC = ConstantExpr::getNeg(cast<Constant>(BOp1)); 2587 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 2588 return new ICmpInst(NewPred, BOp0, NegBOC); 2589 } 2590 } 2591 break; 2592 } 2593 case Instruction::Mul: 2594 if (*C == 0 && BO->hasNoSignedWrap()) { 2595 const APInt *BOC; 2596 if (match(BOp1, m_APInt(BOC)) && *BOC != 0) { 2597 // The trivial case (mul X, 0) is handled by InstSimplify. 2598 // General case : (mul X, C) != 0 iff X != 0 2599 // (mul X, C) == 0 iff X == 0 2600 return new ICmpInst(Pred, BOp0, Constant::getNullValue(RHS->getType())); 2601 } 2602 } 2603 break; 2604 case Instruction::UDiv: 2605 if (*C == 0) { 2606 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A) 2607 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; 2608 return new ICmpInst(NewPred, BOp1, BOp0); 2609 } 2610 break; 2611 default: 2612 break; 2613 } 2614 return nullptr; 2615 } 2616 2617 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C. 2618 Instruction *InstCombiner::foldICmpIntrinsicWithConstant(ICmpInst &Cmp, 2619 const APInt *C) { 2620 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)); 2621 if (!II || !Cmp.isEquality()) 2622 return nullptr; 2623 2624 // Handle icmp {eq|ne} <intrinsic>, intcst. 2625 switch (II->getIntrinsicID()) { 2626 case Intrinsic::bswap: 2627 Worklist.Add(II); 2628 Cmp.setOperand(0, II->getArgOperand(0)); 2629 Cmp.setOperand(1, Builder->getInt(C->byteSwap())); 2630 return &Cmp; 2631 case Intrinsic::ctlz: 2632 case Intrinsic::cttz: 2633 // ctz(A) == bitwidth(A) -> A == 0 and likewise for != 2634 if (*C == C->getBitWidth()) { 2635 Worklist.Add(II); 2636 Cmp.setOperand(0, II->getArgOperand(0)); 2637 Cmp.setOperand(1, ConstantInt::getNullValue(II->getType())); 2638 return &Cmp; 2639 } 2640 break; 2641 case Intrinsic::ctpop: { 2642 // popcount(A) == 0 -> A == 0 and likewise for != 2643 // popcount(A) == bitwidth(A) -> A == -1 and likewise for != 2644 bool IsZero = *C == 0; 2645 if (IsZero || *C == C->getBitWidth()) { 2646 Worklist.Add(II); 2647 Cmp.setOperand(0, II->getArgOperand(0)); 2648 auto *NewOp = IsZero ? Constant::getNullValue(II->getType()) 2649 : Constant::getAllOnesValue(II->getType()); 2650 Cmp.setOperand(1, NewOp); 2651 return &Cmp; 2652 } 2653 break; 2654 } 2655 default: 2656 break; 2657 } 2658 return nullptr; 2659 } 2660 2661 /// Handle icmp with constant (but not simple integer constant) RHS. 2662 Instruction *InstCombiner::foldICmpInstWithConstantNotInt(ICmpInst &I) { 2663 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2664 Constant *RHSC = dyn_cast<Constant>(Op1); 2665 Instruction *LHSI = dyn_cast<Instruction>(Op0); 2666 if (!RHSC || !LHSI) 2667 return nullptr; 2668 2669 switch (LHSI->getOpcode()) { 2670 case Instruction::GetElementPtr: 2671 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 2672 if (RHSC->isNullValue() && 2673 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 2674 return new ICmpInst( 2675 I.getPredicate(), LHSI->getOperand(0), 2676 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2677 break; 2678 case Instruction::PHI: 2679 // Only fold icmp into the PHI if the phi and icmp are in the same 2680 // block. If in the same block, we're encouraging jump threading. If 2681 // not, we are just pessimizing the code by making an i1 phi. 2682 if (LHSI->getParent() == I.getParent()) 2683 if (Instruction *NV = FoldOpIntoPhi(I)) 2684 return NV; 2685 break; 2686 case Instruction::Select: { 2687 // If either operand of the select is a constant, we can fold the 2688 // comparison into the select arms, which will cause one to be 2689 // constant folded and the select turned into a bitwise or. 2690 Value *Op1 = nullptr, *Op2 = nullptr; 2691 ConstantInt *CI = nullptr; 2692 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { 2693 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2694 CI = dyn_cast<ConstantInt>(Op1); 2695 } 2696 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { 2697 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 2698 CI = dyn_cast<ConstantInt>(Op2); 2699 } 2700 2701 // We only want to perform this transformation if it will not lead to 2702 // additional code. This is true if either both sides of the select 2703 // fold to a constant (in which case the icmp is replaced with a select 2704 // which will usually simplify) or this is the only user of the 2705 // select (in which case we are trading a select+icmp for a simpler 2706 // select+icmp) or all uses of the select can be replaced based on 2707 // dominance information ("Global cases"). 2708 bool Transform = false; 2709 if (Op1 && Op2) 2710 Transform = true; 2711 else if (Op1 || Op2) { 2712 // Local case 2713 if (LHSI->hasOneUse()) 2714 Transform = true; 2715 // Global cases 2716 else if (CI && !CI->isZero()) 2717 // When Op1 is constant try replacing select with second operand. 2718 // Otherwise Op2 is constant and try replacing select with first 2719 // operand. 2720 Transform = 2721 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1); 2722 } 2723 if (Transform) { 2724 if (!Op1) 2725 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC, 2726 I.getName()); 2727 if (!Op2) 2728 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC, 2729 I.getName()); 2730 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 2731 } 2732 break; 2733 } 2734 case Instruction::IntToPtr: 2735 // icmp pred inttoptr(X), null -> icmp pred X, 0 2736 if (RHSC->isNullValue() && 2737 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType()) 2738 return new ICmpInst( 2739 I.getPredicate(), LHSI->getOperand(0), 2740 Constant::getNullValue(LHSI->getOperand(0)->getType())); 2741 break; 2742 2743 case Instruction::Load: 2744 // Try to optimize things like "A[i] > 4" to index computations. 2745 if (GetElementPtrInst *GEP = 2746 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 2747 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 2748 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 2749 !cast<LoadInst>(LHSI)->isVolatile()) 2750 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) 2751 return Res; 2752 } 2753 break; 2754 } 2755 2756 return nullptr; 2757 } 2758 2759 /// Try to fold icmp (binop), X or icmp X, (binop). 2760 Instruction *InstCombiner::foldICmpBinOp(ICmpInst &I) { 2761 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2762 2763 // Special logic for binary operators. 2764 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0); 2765 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1); 2766 if (!BO0 && !BO1) 2767 return nullptr; 2768 2769 CmpInst::Predicate Pred = I.getPredicate(); 2770 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; 2771 if (BO0 && isa<OverflowingBinaryOperator>(BO0)) 2772 NoOp0WrapProblem = 2773 ICmpInst::isEquality(Pred) || 2774 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) || 2775 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap()); 2776 if (BO1 && isa<OverflowingBinaryOperator>(BO1)) 2777 NoOp1WrapProblem = 2778 ICmpInst::isEquality(Pred) || 2779 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) || 2780 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap()); 2781 2782 // Analyze the case when either Op0 or Op1 is an add instruction. 2783 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null). 2784 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 2785 if (BO0 && BO0->getOpcode() == Instruction::Add) { 2786 A = BO0->getOperand(0); 2787 B = BO0->getOperand(1); 2788 } 2789 if (BO1 && BO1->getOpcode() == Instruction::Add) { 2790 C = BO1->getOperand(0); 2791 D = BO1->getOperand(1); 2792 } 2793 2794 // icmp (X+cst) < 0 --> X < -cst 2795 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred) && match(Op1, m_Zero())) 2796 if (ConstantInt *RHSC = dyn_cast_or_null<ConstantInt>(B)) 2797 if (!RHSC->isMinValue(/*isSigned=*/true)) 2798 return new ICmpInst(Pred, A, ConstantExpr::getNeg(RHSC)); 2799 2800 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 2801 if ((A == Op1 || B == Op1) && NoOp0WrapProblem) 2802 return new ICmpInst(Pred, A == Op1 ? B : A, 2803 Constant::getNullValue(Op1->getType())); 2804 2805 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 2806 if ((C == Op0 || D == Op0) && NoOp1WrapProblem) 2807 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()), 2808 C == Op0 ? D : C); 2809 2810 // icmp (X+Y), (X+Z) -> icmp Y, Z for equalities or if there is no overflow. 2811 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem && 2812 NoOp1WrapProblem && 2813 // Try not to increase register pressure. 2814 BO0->hasOneUse() && BO1->hasOneUse()) { 2815 // Determine Y and Z in the form icmp (X+Y), (X+Z). 2816 Value *Y, *Z; 2817 if (A == C) { 2818 // C + B == C + D -> B == D 2819 Y = B; 2820 Z = D; 2821 } else if (A == D) { 2822 // D + B == C + D -> B == C 2823 Y = B; 2824 Z = C; 2825 } else if (B == C) { 2826 // A + C == C + D -> A == D 2827 Y = A; 2828 Z = D; 2829 } else { 2830 assert(B == D); 2831 // A + D == C + D -> A == C 2832 Y = A; 2833 Z = C; 2834 } 2835 return new ICmpInst(Pred, Y, Z); 2836 } 2837 2838 // icmp slt (X + -1), Y -> icmp sle X, Y 2839 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT && 2840 match(B, m_AllOnes())) 2841 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1); 2842 2843 // icmp sge (X + -1), Y -> icmp sgt X, Y 2844 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE && 2845 match(B, m_AllOnes())) 2846 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1); 2847 2848 // icmp sle (X + 1), Y -> icmp slt X, Y 2849 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One())) 2850 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1); 2851 2852 // icmp sgt (X + 1), Y -> icmp sge X, Y 2853 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One())) 2854 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1); 2855 2856 // icmp sgt X, (Y + -1) -> icmp sge X, Y 2857 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT && 2858 match(D, m_AllOnes())) 2859 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C); 2860 2861 // icmp sle X, (Y + -1) -> icmp slt X, Y 2862 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE && 2863 match(D, m_AllOnes())) 2864 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C); 2865 2866 // icmp sge X, (Y + 1) -> icmp sgt X, Y 2867 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One())) 2868 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C); 2869 2870 // icmp slt X, (Y + 1) -> icmp sle X, Y 2871 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One())) 2872 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C); 2873 2874 // TODO: The subtraction-related identities shown below also hold, but 2875 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations 2876 // wouldn't happen even if they were implemented. 2877 // 2878 // icmp ult (X - 1), Y -> icmp ule X, Y 2879 // icmp uge (X - 1), Y -> icmp ugt X, Y 2880 // icmp ugt X, (Y - 1) -> icmp uge X, Y 2881 // icmp ule X, (Y - 1) -> icmp ult X, Y 2882 2883 // icmp ule (X + 1), Y -> icmp ult X, Y 2884 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One())) 2885 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1); 2886 2887 // icmp ugt (X + 1), Y -> icmp uge X, Y 2888 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One())) 2889 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1); 2890 2891 // icmp uge X, (Y + 1) -> icmp ugt X, Y 2892 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One())) 2893 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C); 2894 2895 // icmp ult X, (Y + 1) -> icmp ule X, Y 2896 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One())) 2897 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C); 2898 2899 // if C1 has greater magnitude than C2: 2900 // icmp (X + C1), (Y + C2) -> icmp (X + C3), Y 2901 // s.t. C3 = C1 - C2 2902 // 2903 // if C2 has greater magnitude than C1: 2904 // icmp (X + C1), (Y + C2) -> icmp X, (Y + C3) 2905 // s.t. C3 = C2 - C1 2906 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem && 2907 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) 2908 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B)) 2909 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) { 2910 const APInt &AP1 = C1->getValue(); 2911 const APInt &AP2 = C2->getValue(); 2912 if (AP1.isNegative() == AP2.isNegative()) { 2913 APInt AP1Abs = C1->getValue().abs(); 2914 APInt AP2Abs = C2->getValue().abs(); 2915 if (AP1Abs.uge(AP2Abs)) { 2916 ConstantInt *C3 = Builder->getInt(AP1 - AP2); 2917 Value *NewAdd = Builder->CreateNSWAdd(A, C3); 2918 return new ICmpInst(Pred, NewAdd, C); 2919 } else { 2920 ConstantInt *C3 = Builder->getInt(AP2 - AP1); 2921 Value *NewAdd = Builder->CreateNSWAdd(C, C3); 2922 return new ICmpInst(Pred, A, NewAdd); 2923 } 2924 } 2925 } 2926 2927 // Analyze the case when either Op0 or Op1 is a sub instruction. 2928 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null). 2929 A = nullptr; 2930 B = nullptr; 2931 C = nullptr; 2932 D = nullptr; 2933 if (BO0 && BO0->getOpcode() == Instruction::Sub) { 2934 A = BO0->getOperand(0); 2935 B = BO0->getOperand(1); 2936 } 2937 if (BO1 && BO1->getOpcode() == Instruction::Sub) { 2938 C = BO1->getOperand(0); 2939 D = BO1->getOperand(1); 2940 } 2941 2942 // icmp (X-Y), X -> icmp 0, Y for equalities or if there is no overflow. 2943 if (A == Op1 && NoOp0WrapProblem) 2944 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B); 2945 2946 // icmp X, (X-Y) -> icmp Y, 0 for equalities or if there is no overflow. 2947 if (C == Op0 && NoOp1WrapProblem) 2948 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType())); 2949 2950 // icmp (Y-X), (Z-X) -> icmp Y, Z for equalities or if there is no overflow. 2951 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem && 2952 // Try not to increase register pressure. 2953 BO0->hasOneUse() && BO1->hasOneUse()) 2954 return new ICmpInst(Pred, A, C); 2955 2956 // icmp (X-Y), (X-Z) -> icmp Z, Y for equalities or if there is no overflow. 2957 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem && 2958 // Try not to increase register pressure. 2959 BO0->hasOneUse() && BO1->hasOneUse()) 2960 return new ICmpInst(Pred, D, B); 2961 2962 // icmp (0-X) < cst --> x > -cst 2963 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) { 2964 Value *X; 2965 if (match(BO0, m_Neg(m_Value(X)))) 2966 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) 2967 if (!RHSC->isMinValue(/*isSigned=*/true)) 2968 return new ICmpInst(I.getSwappedPredicate(), X, 2969 ConstantExpr::getNeg(RHSC)); 2970 } 2971 2972 BinaryOperator *SRem = nullptr; 2973 // icmp (srem X, Y), Y 2974 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1)) 2975 SRem = BO0; 2976 // icmp Y, (srem X, Y) 2977 else if (BO1 && BO1->getOpcode() == Instruction::SRem && 2978 Op0 == BO1->getOperand(1)) 2979 SRem = BO1; 2980 if (SRem) { 2981 // We don't check hasOneUse to avoid increasing register pressure because 2982 // the value we use is the same value this instruction was already using. 2983 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) { 2984 default: 2985 break; 2986 case ICmpInst::ICMP_EQ: 2987 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 2988 case ICmpInst::ICMP_NE: 2989 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 2990 case ICmpInst::ICMP_SGT: 2991 case ICmpInst::ICMP_SGE: 2992 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1), 2993 Constant::getAllOnesValue(SRem->getType())); 2994 case ICmpInst::ICMP_SLT: 2995 case ICmpInst::ICMP_SLE: 2996 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1), 2997 Constant::getNullValue(SRem->getType())); 2998 } 2999 } 3000 3001 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() && 3002 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) { 3003 switch (BO0->getOpcode()) { 3004 default: 3005 break; 3006 case Instruction::Add: 3007 case Instruction::Sub: 3008 case Instruction::Xor: 3009 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 3010 return new ICmpInst(I.getPredicate(), BO0->getOperand(0), 3011 BO1->getOperand(0)); 3012 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b 3013 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { 3014 if (CI->getValue().isSignBit()) { 3015 ICmpInst::Predicate Pred = 3016 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); 3017 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3018 } 3019 3020 if (BO0->getOpcode() == Instruction::Xor && CI->isMaxValue(true)) { 3021 ICmpInst::Predicate Pred = 3022 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); 3023 Pred = I.getSwappedPredicate(Pred); 3024 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 3025 } 3026 } 3027 break; 3028 case Instruction::Mul: 3029 if (!I.isEquality()) 3030 break; 3031 3032 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO0->getOperand(1))) { 3033 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask 3034 // Mask = -1 >> count-trailing-zeros(Cst). 3035 if (!CI->isZero() && !CI->isOne()) { 3036 const APInt &AP = CI->getValue(); 3037 ConstantInt *Mask = ConstantInt::get( 3038 I.getContext(), 3039 APInt::getLowBitsSet(AP.getBitWidth(), 3040 AP.getBitWidth() - AP.countTrailingZeros())); 3041 Value *And1 = Builder->CreateAnd(BO0->getOperand(0), Mask); 3042 Value *And2 = Builder->CreateAnd(BO1->getOperand(0), Mask); 3043 return new ICmpInst(I.getPredicate(), And1, And2); 3044 } 3045 } 3046 break; 3047 case Instruction::UDiv: 3048 case Instruction::LShr: 3049 if (I.isSigned()) 3050 break; 3051 LLVM_FALLTHROUGH; 3052 case Instruction::SDiv: 3053 case Instruction::AShr: 3054 if (!BO0->isExact() || !BO1->isExact()) 3055 break; 3056 return new ICmpInst(I.getPredicate(), BO0->getOperand(0), 3057 BO1->getOperand(0)); 3058 case Instruction::Shl: { 3059 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); 3060 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); 3061 if (!NUW && !NSW) 3062 break; 3063 if (!NSW && I.isSigned()) 3064 break; 3065 return new ICmpInst(I.getPredicate(), BO0->getOperand(0), 3066 BO1->getOperand(0)); 3067 } 3068 } 3069 } 3070 3071 if (BO0) { 3072 // Transform A & (L - 1) `ult` L --> L != 0 3073 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes()); 3074 auto BitwiseAnd = 3075 m_CombineOr(m_And(m_Value(), LSubOne), m_And(LSubOne, m_Value())); 3076 3077 if (match(BO0, BitwiseAnd) && I.getPredicate() == ICmpInst::ICMP_ULT) { 3078 auto *Zero = Constant::getNullValue(BO0->getType()); 3079 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero); 3080 } 3081 } 3082 3083 return nullptr; 3084 } 3085 3086 /// Fold icmp Pred min|max(X, Y), X. 3087 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) { 3088 ICmpInst::Predicate Pred = Cmp.getPredicate(); 3089 Value *Op0 = Cmp.getOperand(0); 3090 Value *X = Cmp.getOperand(1); 3091 3092 // Canonicalize minimum or maximum operand to LHS of the icmp. 3093 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) || 3094 match(X, m_c_SMax(m_Specific(Op0), m_Value())) || 3095 match(X, m_c_UMin(m_Specific(Op0), m_Value())) || 3096 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) { 3097 std::swap(Op0, X); 3098 Pred = Cmp.getSwappedPredicate(); 3099 } 3100 3101 Value *Y; 3102 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) { 3103 // smin(X, Y) == X --> X s<= Y 3104 // smin(X, Y) s>= X --> X s<= Y 3105 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE) 3106 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 3107 3108 // smin(X, Y) != X --> X s> Y 3109 // smin(X, Y) s< X --> X s> Y 3110 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT) 3111 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 3112 3113 // These cases should be handled in InstSimplify: 3114 // smin(X, Y) s<= X --> true 3115 // smin(X, Y) s> X --> false 3116 return nullptr; 3117 } 3118 3119 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) { 3120 // smax(X, Y) == X --> X s>= Y 3121 // smax(X, Y) s<= X --> X s>= Y 3122 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE) 3123 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 3124 3125 // smax(X, Y) != X --> X s< Y 3126 // smax(X, Y) s> X --> X s< Y 3127 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT) 3128 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 3129 3130 // These cases should be handled in InstSimplify: 3131 // smax(X, Y) s>= X --> true 3132 // smax(X, Y) s< X --> false 3133 return nullptr; 3134 } 3135 3136 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) { 3137 // umin(X, Y) == X --> X u<= Y 3138 // umin(X, Y) u>= X --> X u<= Y 3139 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE) 3140 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y); 3141 3142 // umin(X, Y) != X --> X u> Y 3143 // umin(X, Y) u< X --> X u> Y 3144 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT) 3145 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 3146 3147 // These cases should be handled in InstSimplify: 3148 // umin(X, Y) u<= X --> true 3149 // umin(X, Y) u> X --> false 3150 return nullptr; 3151 } 3152 3153 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) { 3154 // umax(X, Y) == X --> X u>= Y 3155 // umax(X, Y) u<= X --> X u>= Y 3156 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE) 3157 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); 3158 3159 // umax(X, Y) != X --> X u< Y 3160 // umax(X, Y) u> X --> X u< Y 3161 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT) 3162 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 3163 3164 // These cases should be handled in InstSimplify: 3165 // umax(X, Y) u>= X --> true 3166 // umax(X, Y) u< X --> false 3167 return nullptr; 3168 } 3169 3170 return nullptr; 3171 } 3172 3173 Instruction *InstCombiner::foldICmpEquality(ICmpInst &I) { 3174 if (!I.isEquality()) 3175 return nullptr; 3176 3177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3178 Value *A, *B, *C, *D; 3179 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 3180 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 3181 Value *OtherVal = A == Op1 ? B : A; 3182 return new ICmpInst(I.getPredicate(), OtherVal, 3183 Constant::getNullValue(A->getType())); 3184 } 3185 3186 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 3187 // A^c1 == C^c2 --> A == C^(c1^c2) 3188 ConstantInt *C1, *C2; 3189 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) && 3190 Op1->hasOneUse()) { 3191 Constant *NC = Builder->getInt(C1->getValue() ^ C2->getValue()); 3192 Value *Xor = Builder->CreateXor(C, NC); 3193 return new ICmpInst(I.getPredicate(), A, Xor); 3194 } 3195 3196 // A^B == A^D -> B == D 3197 if (A == C) 3198 return new ICmpInst(I.getPredicate(), B, D); 3199 if (A == D) 3200 return new ICmpInst(I.getPredicate(), B, C); 3201 if (B == C) 3202 return new ICmpInst(I.getPredicate(), A, D); 3203 if (B == D) 3204 return new ICmpInst(I.getPredicate(), A, C); 3205 } 3206 } 3207 3208 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) { 3209 // A == (A^B) -> B == 0 3210 Value *OtherVal = A == Op0 ? B : A; 3211 return new ICmpInst(I.getPredicate(), OtherVal, 3212 Constant::getNullValue(A->getType())); 3213 } 3214 3215 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 3216 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && 3217 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) { 3218 Value *X = nullptr, *Y = nullptr, *Z = nullptr; 3219 3220 if (A == C) { 3221 X = B; 3222 Y = D; 3223 Z = A; 3224 } else if (A == D) { 3225 X = B; 3226 Y = C; 3227 Z = A; 3228 } else if (B == C) { 3229 X = A; 3230 Y = D; 3231 Z = B; 3232 } else if (B == D) { 3233 X = A; 3234 Y = C; 3235 Z = B; 3236 } 3237 3238 if (X) { // Build (X^Y) & Z 3239 Op1 = Builder->CreateXor(X, Y); 3240 Op1 = Builder->CreateAnd(Op1, Z); 3241 I.setOperand(0, Op1); 3242 I.setOperand(1, Constant::getNullValue(Op1->getType())); 3243 return &I; 3244 } 3245 } 3246 3247 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B) 3248 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B) 3249 ConstantInt *Cst1; 3250 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) && 3251 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) || 3252 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) && 3253 match(Op1, m_ZExt(m_Value(A))))) { 3254 APInt Pow2 = Cst1->getValue() + 1; 3255 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) && 3256 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth()) 3257 return new ICmpInst(I.getPredicate(), A, 3258 Builder->CreateTrunc(B, A->getType())); 3259 } 3260 3261 // (A >> C) == (B >> C) --> (A^B) u< (1 << C) 3262 // For lshr and ashr pairs. 3263 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) && 3264 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) || 3265 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) && 3266 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) { 3267 unsigned TypeBits = Cst1->getBitWidth(); 3268 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 3269 if (ShAmt < TypeBits && ShAmt != 0) { 3270 ICmpInst::Predicate Pred = I.getPredicate() == ICmpInst::ICMP_NE 3271 ? ICmpInst::ICMP_UGE 3272 : ICmpInst::ICMP_ULT; 3273 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted"); 3274 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt); 3275 return new ICmpInst(Pred, Xor, Builder->getInt(CmpVal)); 3276 } 3277 } 3278 3279 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0 3280 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) && 3281 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) { 3282 unsigned TypeBits = Cst1->getBitWidth(); 3283 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 3284 if (ShAmt < TypeBits && ShAmt != 0) { 3285 Value *Xor = Builder->CreateXor(A, B, I.getName() + ".unshifted"); 3286 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt); 3287 Value *And = Builder->CreateAnd(Xor, Builder->getInt(AndVal), 3288 I.getName() + ".mask"); 3289 return new ICmpInst(I.getPredicate(), And, 3290 Constant::getNullValue(Cst1->getType())); 3291 } 3292 } 3293 3294 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to 3295 // "icmp (and X, mask), cst" 3296 uint64_t ShAmt = 0; 3297 if (Op0->hasOneUse() && 3298 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) && 3299 match(Op1, m_ConstantInt(Cst1)) && 3300 // Only do this when A has multiple uses. This is most important to do 3301 // when it exposes other optimizations. 3302 !A->hasOneUse()) { 3303 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits(); 3304 3305 if (ShAmt < ASize) { 3306 APInt MaskV = 3307 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits()); 3308 MaskV <<= ShAmt; 3309 3310 APInt CmpV = Cst1->getValue().zext(ASize); 3311 CmpV <<= ShAmt; 3312 3313 Value *Mask = Builder->CreateAnd(A, Builder->getInt(MaskV)); 3314 return new ICmpInst(I.getPredicate(), Mask, Builder->getInt(CmpV)); 3315 } 3316 } 3317 3318 return nullptr; 3319 } 3320 3321 /// Handle icmp (cast x to y), (cast/cst). We only handle extending casts so 3322 /// far. 3323 Instruction *InstCombiner::foldICmpWithCastAndCast(ICmpInst &ICmp) { 3324 const CastInst *LHSCI = cast<CastInst>(ICmp.getOperand(0)); 3325 Value *LHSCIOp = LHSCI->getOperand(0); 3326 Type *SrcTy = LHSCIOp->getType(); 3327 Type *DestTy = LHSCI->getType(); 3328 Value *RHSCIOp; 3329 3330 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 3331 // integer type is the same size as the pointer type. 3332 if (LHSCI->getOpcode() == Instruction::PtrToInt && 3333 DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth()) { 3334 Value *RHSOp = nullptr; 3335 if (auto *RHSC = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) { 3336 Value *RHSCIOp = RHSC->getOperand(0); 3337 if (RHSCIOp->getType()->getPointerAddressSpace() == 3338 LHSCIOp->getType()->getPointerAddressSpace()) { 3339 RHSOp = RHSC->getOperand(0); 3340 // If the pointer types don't match, insert a bitcast. 3341 if (LHSCIOp->getType() != RHSOp->getType()) 3342 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType()); 3343 } 3344 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) { 3345 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy); 3346 } 3347 3348 if (RHSOp) 3349 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSOp); 3350 } 3351 3352 // The code below only handles extension cast instructions, so far. 3353 // Enforce this. 3354 if (LHSCI->getOpcode() != Instruction::ZExt && 3355 LHSCI->getOpcode() != Instruction::SExt) 3356 return nullptr; 3357 3358 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt; 3359 bool isSignedCmp = ICmp.isSigned(); 3360 3361 if (auto *CI = dyn_cast<CastInst>(ICmp.getOperand(1))) { 3362 // Not an extension from the same type? 3363 RHSCIOp = CI->getOperand(0); 3364 if (RHSCIOp->getType() != LHSCIOp->getType()) 3365 return nullptr; 3366 3367 // If the signedness of the two casts doesn't agree (i.e. one is a sext 3368 // and the other is a zext), then we can't handle this. 3369 if (CI->getOpcode() != LHSCI->getOpcode()) 3370 return nullptr; 3371 3372 // Deal with equality cases early. 3373 if (ICmp.isEquality()) 3374 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); 3375 3376 // A signed comparison of sign extended values simplifies into a 3377 // signed comparison. 3378 if (isSignedCmp && isSignedExt) 3379 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, RHSCIOp); 3380 3381 // The other three cases all fold into an unsigned comparison. 3382 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, RHSCIOp); 3383 } 3384 3385 // If we aren't dealing with a constant on the RHS, exit early. 3386 auto *C = dyn_cast<Constant>(ICmp.getOperand(1)); 3387 if (!C) 3388 return nullptr; 3389 3390 // Compute the constant that would happen if we truncated to SrcTy then 3391 // re-extended to DestTy. 3392 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy); 3393 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy); 3394 3395 // If the re-extended constant didn't change... 3396 if (Res2 == C) { 3397 // Deal with equality cases early. 3398 if (ICmp.isEquality()) 3399 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); 3400 3401 // A signed comparison of sign extended values simplifies into a 3402 // signed comparison. 3403 if (isSignedExt && isSignedCmp) 3404 return new ICmpInst(ICmp.getPredicate(), LHSCIOp, Res1); 3405 3406 // The other three cases all fold into an unsigned comparison. 3407 return new ICmpInst(ICmp.getUnsignedPredicate(), LHSCIOp, Res1); 3408 } 3409 3410 // The re-extended constant changed, partly changed (in the case of a vector), 3411 // or could not be determined to be equal (in the case of a constant 3412 // expression), so the constant cannot be represented in the shorter type. 3413 // Consequently, we cannot emit a simple comparison. 3414 // All the cases that fold to true or false will have already been handled 3415 // by SimplifyICmpInst, so only deal with the tricky case. 3416 3417 if (isSignedCmp || !isSignedExt || !isa<ConstantInt>(C)) 3418 return nullptr; 3419 3420 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases 3421 // should have been folded away previously and not enter in here. 3422 3423 // We're performing an unsigned comp with a sign extended value. 3424 // This is true if the input is >= 0. [aka >s -1] 3425 Constant *NegOne = Constant::getAllOnesValue(SrcTy); 3426 Value *Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICmp.getName()); 3427 3428 // Finally, return the value computed. 3429 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT) 3430 return replaceInstUsesWith(ICmp, Result); 3431 3432 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); 3433 return BinaryOperator::CreateNot(Result); 3434 } 3435 3436 bool InstCombiner::OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, 3437 Value *RHS, Instruction &OrigI, 3438 Value *&Result, Constant *&Overflow) { 3439 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS)) 3440 std::swap(LHS, RHS); 3441 3442 auto SetResult = [&](Value *OpResult, Constant *OverflowVal, bool ReuseName) { 3443 Result = OpResult; 3444 Overflow = OverflowVal; 3445 if (ReuseName) 3446 Result->takeName(&OrigI); 3447 return true; 3448 }; 3449 3450 // If the overflow check was an add followed by a compare, the insertion point 3451 // may be pointing to the compare. We want to insert the new instructions 3452 // before the add in case there are uses of the add between the add and the 3453 // compare. 3454 Builder->SetInsertPoint(&OrigI); 3455 3456 switch (OCF) { 3457 case OCF_INVALID: 3458 llvm_unreachable("bad overflow check kind!"); 3459 3460 case OCF_UNSIGNED_ADD: { 3461 OverflowResult OR = computeOverflowForUnsignedAdd(LHS, RHS, &OrigI); 3462 if (OR == OverflowResult::NeverOverflows) 3463 return SetResult(Builder->CreateNUWAdd(LHS, RHS), Builder->getFalse(), 3464 true); 3465 3466 if (OR == OverflowResult::AlwaysOverflows) 3467 return SetResult(Builder->CreateAdd(LHS, RHS), Builder->getTrue(), true); 3468 3469 // Fall through uadd into sadd 3470 LLVM_FALLTHROUGH; 3471 } 3472 case OCF_SIGNED_ADD: { 3473 // X + 0 -> {X, false} 3474 if (match(RHS, m_Zero())) 3475 return SetResult(LHS, Builder->getFalse(), false); 3476 3477 // We can strength reduce this signed add into a regular add if we can prove 3478 // that it will never overflow. 3479 if (OCF == OCF_SIGNED_ADD) 3480 if (WillNotOverflowSignedAdd(LHS, RHS, OrigI)) 3481 return SetResult(Builder->CreateNSWAdd(LHS, RHS), Builder->getFalse(), 3482 true); 3483 break; 3484 } 3485 3486 case OCF_UNSIGNED_SUB: 3487 case OCF_SIGNED_SUB: { 3488 // X - 0 -> {X, false} 3489 if (match(RHS, m_Zero())) 3490 return SetResult(LHS, Builder->getFalse(), false); 3491 3492 if (OCF == OCF_SIGNED_SUB) { 3493 if (WillNotOverflowSignedSub(LHS, RHS, OrigI)) 3494 return SetResult(Builder->CreateNSWSub(LHS, RHS), Builder->getFalse(), 3495 true); 3496 } else { 3497 if (WillNotOverflowUnsignedSub(LHS, RHS, OrigI)) 3498 return SetResult(Builder->CreateNUWSub(LHS, RHS), Builder->getFalse(), 3499 true); 3500 } 3501 break; 3502 } 3503 3504 case OCF_UNSIGNED_MUL: { 3505 OverflowResult OR = computeOverflowForUnsignedMul(LHS, RHS, &OrigI); 3506 if (OR == OverflowResult::NeverOverflows) 3507 return SetResult(Builder->CreateNUWMul(LHS, RHS), Builder->getFalse(), 3508 true); 3509 if (OR == OverflowResult::AlwaysOverflows) 3510 return SetResult(Builder->CreateMul(LHS, RHS), Builder->getTrue(), true); 3511 LLVM_FALLTHROUGH; 3512 } 3513 case OCF_SIGNED_MUL: 3514 // X * undef -> undef 3515 if (isa<UndefValue>(RHS)) 3516 return SetResult(RHS, UndefValue::get(Builder->getInt1Ty()), false); 3517 3518 // X * 0 -> {0, false} 3519 if (match(RHS, m_Zero())) 3520 return SetResult(RHS, Builder->getFalse(), false); 3521 3522 // X * 1 -> {X, false} 3523 if (match(RHS, m_One())) 3524 return SetResult(LHS, Builder->getFalse(), false); 3525 3526 if (OCF == OCF_SIGNED_MUL) 3527 if (WillNotOverflowSignedMul(LHS, RHS, OrigI)) 3528 return SetResult(Builder->CreateNSWMul(LHS, RHS), Builder->getFalse(), 3529 true); 3530 break; 3531 } 3532 3533 return false; 3534 } 3535 3536 /// \brief Recognize and process idiom involving test for multiplication 3537 /// overflow. 3538 /// 3539 /// The caller has matched a pattern of the form: 3540 /// I = cmp u (mul(zext A, zext B), V 3541 /// The function checks if this is a test for overflow and if so replaces 3542 /// multiplication with call to 'mul.with.overflow' intrinsic. 3543 /// 3544 /// \param I Compare instruction. 3545 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of 3546 /// the compare instruction. Must be of integer type. 3547 /// \param OtherVal The other argument of compare instruction. 3548 /// \returns Instruction which must replace the compare instruction, NULL if no 3549 /// replacement required. 3550 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal, 3551 Value *OtherVal, InstCombiner &IC) { 3552 // Don't bother doing this transformation for pointers, don't do it for 3553 // vectors. 3554 if (!isa<IntegerType>(MulVal->getType())) 3555 return nullptr; 3556 3557 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal); 3558 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal); 3559 auto *MulInstr = dyn_cast<Instruction>(MulVal); 3560 if (!MulInstr) 3561 return nullptr; 3562 assert(MulInstr->getOpcode() == Instruction::Mul); 3563 3564 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)), 3565 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1)); 3566 assert(LHS->getOpcode() == Instruction::ZExt); 3567 assert(RHS->getOpcode() == Instruction::ZExt); 3568 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0); 3569 3570 // Calculate type and width of the result produced by mul.with.overflow. 3571 Type *TyA = A->getType(), *TyB = B->getType(); 3572 unsigned WidthA = TyA->getPrimitiveSizeInBits(), 3573 WidthB = TyB->getPrimitiveSizeInBits(); 3574 unsigned MulWidth; 3575 Type *MulType; 3576 if (WidthB > WidthA) { 3577 MulWidth = WidthB; 3578 MulType = TyB; 3579 } else { 3580 MulWidth = WidthA; 3581 MulType = TyA; 3582 } 3583 3584 // In order to replace the original mul with a narrower mul.with.overflow, 3585 // all uses must ignore upper bits of the product. The number of used low 3586 // bits must be not greater than the width of mul.with.overflow. 3587 if (MulVal->hasNUsesOrMore(2)) 3588 for (User *U : MulVal->users()) { 3589 if (U == &I) 3590 continue; 3591 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 3592 // Check if truncation ignores bits above MulWidth. 3593 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits(); 3594 if (TruncWidth > MulWidth) 3595 return nullptr; 3596 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 3597 // Check if AND ignores bits above MulWidth. 3598 if (BO->getOpcode() != Instruction::And) 3599 return nullptr; 3600 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 3601 const APInt &CVal = CI->getValue(); 3602 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth) 3603 return nullptr; 3604 } 3605 } else { 3606 // Other uses prohibit this transformation. 3607 return nullptr; 3608 } 3609 } 3610 3611 // Recognize patterns 3612 switch (I.getPredicate()) { 3613 case ICmpInst::ICMP_EQ: 3614 case ICmpInst::ICMP_NE: 3615 // Recognize pattern: 3616 // mulval = mul(zext A, zext B) 3617 // cmp eq/neq mulval, zext trunc mulval 3618 if (ZExtInst *Zext = dyn_cast<ZExtInst>(OtherVal)) 3619 if (Zext->hasOneUse()) { 3620 Value *ZextArg = Zext->getOperand(0); 3621 if (TruncInst *Trunc = dyn_cast<TruncInst>(ZextArg)) 3622 if (Trunc->getType()->getPrimitiveSizeInBits() == MulWidth) 3623 break; //Recognized 3624 } 3625 3626 // Recognize pattern: 3627 // mulval = mul(zext A, zext B) 3628 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits. 3629 ConstantInt *CI; 3630 Value *ValToMask; 3631 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) { 3632 if (ValToMask != MulVal) 3633 return nullptr; 3634 const APInt &CVal = CI->getValue() + 1; 3635 if (CVal.isPowerOf2()) { 3636 unsigned MaskWidth = CVal.logBase2(); 3637 if (MaskWidth == MulWidth) 3638 break; // Recognized 3639 } 3640 } 3641 return nullptr; 3642 3643 case ICmpInst::ICMP_UGT: 3644 // Recognize pattern: 3645 // mulval = mul(zext A, zext B) 3646 // cmp ugt mulval, max 3647 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 3648 APInt MaxVal = APInt::getMaxValue(MulWidth); 3649 MaxVal = MaxVal.zext(CI->getBitWidth()); 3650 if (MaxVal.eq(CI->getValue())) 3651 break; // Recognized 3652 } 3653 return nullptr; 3654 3655 case ICmpInst::ICMP_UGE: 3656 // Recognize pattern: 3657 // mulval = mul(zext A, zext B) 3658 // cmp uge mulval, max+1 3659 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 3660 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 3661 if (MaxVal.eq(CI->getValue())) 3662 break; // Recognized 3663 } 3664 return nullptr; 3665 3666 case ICmpInst::ICMP_ULE: 3667 // Recognize pattern: 3668 // mulval = mul(zext A, zext B) 3669 // cmp ule mulval, max 3670 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 3671 APInt MaxVal = APInt::getMaxValue(MulWidth); 3672 MaxVal = MaxVal.zext(CI->getBitWidth()); 3673 if (MaxVal.eq(CI->getValue())) 3674 break; // Recognized 3675 } 3676 return nullptr; 3677 3678 case ICmpInst::ICMP_ULT: 3679 // Recognize pattern: 3680 // mulval = mul(zext A, zext B) 3681 // cmp ule mulval, max + 1 3682 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 3683 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 3684 if (MaxVal.eq(CI->getValue())) 3685 break; // Recognized 3686 } 3687 return nullptr; 3688 3689 default: 3690 return nullptr; 3691 } 3692 3693 InstCombiner::BuilderTy *Builder = IC.Builder; 3694 Builder->SetInsertPoint(MulInstr); 3695 3696 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B) 3697 Value *MulA = A, *MulB = B; 3698 if (WidthA < MulWidth) 3699 MulA = Builder->CreateZExt(A, MulType); 3700 if (WidthB < MulWidth) 3701 MulB = Builder->CreateZExt(B, MulType); 3702 Value *F = Intrinsic::getDeclaration(I.getModule(), 3703 Intrinsic::umul_with_overflow, MulType); 3704 CallInst *Call = Builder->CreateCall(F, {MulA, MulB}, "umul"); 3705 IC.Worklist.Add(MulInstr); 3706 3707 // If there are uses of mul result other than the comparison, we know that 3708 // they are truncation or binary AND. Change them to use result of 3709 // mul.with.overflow and adjust properly mask/size. 3710 if (MulVal->hasNUsesOrMore(2)) { 3711 Value *Mul = Builder->CreateExtractValue(Call, 0, "umul.value"); 3712 for (User *U : MulVal->users()) { 3713 if (U == &I || U == OtherVal) 3714 continue; 3715 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 3716 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth) 3717 IC.replaceInstUsesWith(*TI, Mul); 3718 else 3719 TI->setOperand(0, Mul); 3720 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 3721 assert(BO->getOpcode() == Instruction::And); 3722 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask) 3723 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1)); 3724 APInt ShortMask = CI->getValue().trunc(MulWidth); 3725 Value *ShortAnd = Builder->CreateAnd(Mul, ShortMask); 3726 Instruction *Zext = 3727 cast<Instruction>(Builder->CreateZExt(ShortAnd, BO->getType())); 3728 IC.Worklist.Add(Zext); 3729 IC.replaceInstUsesWith(*BO, Zext); 3730 } else { 3731 llvm_unreachable("Unexpected Binary operation"); 3732 } 3733 IC.Worklist.Add(cast<Instruction>(U)); 3734 } 3735 } 3736 if (isa<Instruction>(OtherVal)) 3737 IC.Worklist.Add(cast<Instruction>(OtherVal)); 3738 3739 // The original icmp gets replaced with the overflow value, maybe inverted 3740 // depending on predicate. 3741 bool Inverse = false; 3742 switch (I.getPredicate()) { 3743 case ICmpInst::ICMP_NE: 3744 break; 3745 case ICmpInst::ICMP_EQ: 3746 Inverse = true; 3747 break; 3748 case ICmpInst::ICMP_UGT: 3749 case ICmpInst::ICMP_UGE: 3750 if (I.getOperand(0) == MulVal) 3751 break; 3752 Inverse = true; 3753 break; 3754 case ICmpInst::ICMP_ULT: 3755 case ICmpInst::ICMP_ULE: 3756 if (I.getOperand(1) == MulVal) 3757 break; 3758 Inverse = true; 3759 break; 3760 default: 3761 llvm_unreachable("Unexpected predicate"); 3762 } 3763 if (Inverse) { 3764 Value *Res = Builder->CreateExtractValue(Call, 1); 3765 return BinaryOperator::CreateNot(Res); 3766 } 3767 3768 return ExtractValueInst::Create(Call, 1); 3769 } 3770 3771 /// When performing a comparison against a constant, it is possible that not all 3772 /// the bits in the LHS are demanded. This helper method computes the mask that 3773 /// IS demanded. 3774 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth, 3775 bool isSignCheck) { 3776 if (isSignCheck) 3777 return APInt::getSignBit(BitWidth); 3778 3779 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1)); 3780 if (!CI) return APInt::getAllOnesValue(BitWidth); 3781 const APInt &RHS = CI->getValue(); 3782 3783 switch (I.getPredicate()) { 3784 // For a UGT comparison, we don't care about any bits that 3785 // correspond to the trailing ones of the comparand. The value of these 3786 // bits doesn't impact the outcome of the comparison, because any value 3787 // greater than the RHS must differ in a bit higher than these due to carry. 3788 case ICmpInst::ICMP_UGT: { 3789 unsigned trailingOnes = RHS.countTrailingOnes(); 3790 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingOnes); 3791 return ~lowBitsSet; 3792 } 3793 3794 // Similarly, for a ULT comparison, we don't care about the trailing zeros. 3795 // Any value less than the RHS must differ in a higher bit because of carries. 3796 case ICmpInst::ICMP_ULT: { 3797 unsigned trailingZeros = RHS.countTrailingZeros(); 3798 APInt lowBitsSet = APInt::getLowBitsSet(BitWidth, trailingZeros); 3799 return ~lowBitsSet; 3800 } 3801 3802 default: 3803 return APInt::getAllOnesValue(BitWidth); 3804 } 3805 } 3806 3807 /// \brief Check if the order of \p Op0 and \p Op1 as operand in an ICmpInst 3808 /// should be swapped. 3809 /// The decision is based on how many times these two operands are reused 3810 /// as subtract operands and their positions in those instructions. 3811 /// The rational is that several architectures use the same instruction for 3812 /// both subtract and cmp, thus it is better if the order of those operands 3813 /// match. 3814 /// \return true if Op0 and Op1 should be swapped. 3815 static bool swapMayExposeCSEOpportunities(const Value * Op0, 3816 const Value * Op1) { 3817 // Filter out pointer value as those cannot appears directly in subtract. 3818 // FIXME: we may want to go through inttoptrs or bitcasts. 3819 if (Op0->getType()->isPointerTy()) 3820 return false; 3821 // Count every uses of both Op0 and Op1 in a subtract. 3822 // Each time Op0 is the first operand, count -1: swapping is bad, the 3823 // subtract has already the same layout as the compare. 3824 // Each time Op0 is the second operand, count +1: swapping is good, the 3825 // subtract has a different layout as the compare. 3826 // At the end, if the benefit is greater than 0, Op0 should come second to 3827 // expose more CSE opportunities. 3828 int GlobalSwapBenefits = 0; 3829 for (const User *U : Op0->users()) { 3830 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(U); 3831 if (!BinOp || BinOp->getOpcode() != Instruction::Sub) 3832 continue; 3833 // If Op0 is the first argument, this is not beneficial to swap the 3834 // arguments. 3835 int LocalSwapBenefits = -1; 3836 unsigned Op1Idx = 1; 3837 if (BinOp->getOperand(Op1Idx) == Op0) { 3838 Op1Idx = 0; 3839 LocalSwapBenefits = 1; 3840 } 3841 if (BinOp->getOperand(Op1Idx) != Op1) 3842 continue; 3843 GlobalSwapBenefits += LocalSwapBenefits; 3844 } 3845 return GlobalSwapBenefits > 0; 3846 } 3847 3848 /// \brief Check that one use is in the same block as the definition and all 3849 /// other uses are in blocks dominated by a given block. 3850 /// 3851 /// \param DI Definition 3852 /// \param UI Use 3853 /// \param DB Block that must dominate all uses of \p DI outside 3854 /// the parent block 3855 /// \return true when \p UI is the only use of \p DI in the parent block 3856 /// and all other uses of \p DI are in blocks dominated by \p DB. 3857 /// 3858 bool InstCombiner::dominatesAllUses(const Instruction *DI, 3859 const Instruction *UI, 3860 const BasicBlock *DB) const { 3861 assert(DI && UI && "Instruction not defined\n"); 3862 // Ignore incomplete definitions. 3863 if (!DI->getParent()) 3864 return false; 3865 // DI and UI must be in the same block. 3866 if (DI->getParent() != UI->getParent()) 3867 return false; 3868 // Protect from self-referencing blocks. 3869 if (DI->getParent() == DB) 3870 return false; 3871 for (const User *U : DI->users()) { 3872 auto *Usr = cast<Instruction>(U); 3873 if (Usr != UI && !DT.dominates(DB, Usr->getParent())) 3874 return false; 3875 } 3876 return true; 3877 } 3878 3879 /// Return true when the instruction sequence within a block is select-cmp-br. 3880 static bool isChainSelectCmpBranch(const SelectInst *SI) { 3881 const BasicBlock *BB = SI->getParent(); 3882 if (!BB) 3883 return false; 3884 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator()); 3885 if (!BI || BI->getNumSuccessors() != 2) 3886 return false; 3887 auto *IC = dyn_cast<ICmpInst>(BI->getCondition()); 3888 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI)) 3889 return false; 3890 return true; 3891 } 3892 3893 /// \brief True when a select result is replaced by one of its operands 3894 /// in select-icmp sequence. This will eventually result in the elimination 3895 /// of the select. 3896 /// 3897 /// \param SI Select instruction 3898 /// \param Icmp Compare instruction 3899 /// \param SIOpd Operand that replaces the select 3900 /// 3901 /// Notes: 3902 /// - The replacement is global and requires dominator information 3903 /// - The caller is responsible for the actual replacement 3904 /// 3905 /// Example: 3906 /// 3907 /// entry: 3908 /// %4 = select i1 %3, %C* %0, %C* null 3909 /// %5 = icmp eq %C* %4, null 3910 /// br i1 %5, label %9, label %7 3911 /// ... 3912 /// ; <label>:7 ; preds = %entry 3913 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0 3914 /// ... 3915 /// 3916 /// can be transformed to 3917 /// 3918 /// %5 = icmp eq %C* %0, null 3919 /// %6 = select i1 %3, i1 %5, i1 true 3920 /// br i1 %6, label %9, label %7 3921 /// ... 3922 /// ; <label>:7 ; preds = %entry 3923 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0! 3924 /// 3925 /// Similar when the first operand of the select is a constant or/and 3926 /// the compare is for not equal rather than equal. 3927 /// 3928 /// NOTE: The function is only called when the select and compare constants 3929 /// are equal, the optimization can work only for EQ predicates. This is not a 3930 /// major restriction since a NE compare should be 'normalized' to an equal 3931 /// compare, which usually happens in the combiner and test case 3932 /// select-cmp-br.ll checks for it. 3933 bool InstCombiner::replacedSelectWithOperand(SelectInst *SI, 3934 const ICmpInst *Icmp, 3935 const unsigned SIOpd) { 3936 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!"); 3937 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) { 3938 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1); 3939 // The check for the unique predecessor is not the best that can be 3940 // done. But it protects efficiently against cases like when SI's 3941 // home block has two successors, Succ and Succ1, and Succ1 predecessor 3942 // of Succ. Then SI can't be replaced by SIOpd because the use that gets 3943 // replaced can be reached on either path. So the uniqueness check 3944 // guarantees that the path all uses of SI (outside SI's parent) are on 3945 // is disjoint from all other paths out of SI. But that information 3946 // is more expensive to compute, and the trade-off here is in favor 3947 // of compile-time. 3948 if (Succ->getUniquePredecessor() && dominatesAllUses(SI, Icmp, Succ)) { 3949 NumSel++; 3950 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent()); 3951 return true; 3952 } 3953 } 3954 return false; 3955 } 3956 3957 /// Try to fold the comparison based on range information we can get by checking 3958 /// whether bits are known to be zero or one in the inputs. 3959 Instruction *InstCombiner::foldICmpUsingKnownBits(ICmpInst &I) { 3960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3961 Type *Ty = Op0->getType(); 3962 ICmpInst::Predicate Pred = I.getPredicate(); 3963 3964 // Get scalar or pointer size. 3965 unsigned BitWidth = Ty->isIntOrIntVectorTy() 3966 ? Ty->getScalarSizeInBits() 3967 : DL.getTypeSizeInBits(Ty->getScalarType()); 3968 3969 if (!BitWidth) 3970 return nullptr; 3971 3972 // If this is a normal comparison, it demands all bits. If it is a sign bit 3973 // comparison, it only demands the sign bit. 3974 bool IsSignBit = false; 3975 const APInt *CmpC; 3976 if (match(Op1, m_APInt(CmpC))) { 3977 bool UnusedBit; 3978 IsSignBit = isSignBitCheck(Pred, *CmpC, UnusedBit); 3979 } 3980 3981 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0); 3982 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0); 3983 3984 if (SimplifyDemandedBits(I.getOperandUse(0), 3985 getDemandedBitsLHSMask(I, BitWidth, IsSignBit), 3986 Op0KnownZero, Op0KnownOne, 0)) 3987 return &I; 3988 3989 if (SimplifyDemandedBits(I.getOperandUse(1), APInt::getAllOnesValue(BitWidth), 3990 Op1KnownZero, Op1KnownOne, 0)) 3991 return &I; 3992 3993 // Given the known and unknown bits, compute a range that the LHS could be 3994 // in. Compute the Min, Max and RHS values based on the known bits. For the 3995 // EQ and NE we use unsigned values. 3996 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 3997 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 3998 if (I.isSigned()) { 3999 computeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min, 4000 Op0Max); 4001 computeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min, 4002 Op1Max); 4003 } else { 4004 computeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne, Op0Min, 4005 Op0Max); 4006 computeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne, Op1Min, 4007 Op1Max); 4008 } 4009 4010 // If Min and Max are known to be the same, then SimplifyDemandedBits 4011 // figured out that the LHS is a constant. Constant fold this now, so that 4012 // code below can assume that Min != Max. 4013 if (!isa<Constant>(Op0) && Op0Min == Op0Max) 4014 return new ICmpInst(Pred, ConstantInt::get(Op0->getType(), Op0Min), Op1); 4015 if (!isa<Constant>(Op1) && Op1Min == Op1Max) 4016 return new ICmpInst(Pred, Op0, ConstantInt::get(Op1->getType(), Op1Min)); 4017 4018 // Based on the range information we know about the LHS, see if we can 4019 // simplify this comparison. For example, (x&4) < 8 is always true. 4020 switch (Pred) { 4021 default: 4022 llvm_unreachable("Unknown icmp opcode!"); 4023 case ICmpInst::ICMP_EQ: 4024 case ICmpInst::ICMP_NE: { 4025 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) { 4026 return Pred == CmpInst::ICMP_EQ 4027 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())) 4028 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4029 } 4030 4031 // If all bits are known zero except for one, then we know at most one bit 4032 // is set. If the comparison is against zero, then this is a check to see if 4033 // *that* bit is set. 4034 APInt Op0KnownZeroInverted = ~Op0KnownZero; 4035 if (~Op1KnownZero == 0) { 4036 // If the LHS is an AND with the same constant, look through it. 4037 Value *LHS = nullptr; 4038 const APInt *LHSC; 4039 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) || 4040 *LHSC != Op0KnownZeroInverted) 4041 LHS = Op0; 4042 4043 Value *X; 4044 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 4045 APInt ValToCheck = Op0KnownZeroInverted; 4046 Type *XTy = X->getType(); 4047 if (ValToCheck.isPowerOf2()) { 4048 // ((1 << X) & 8) == 0 -> X != 3 4049 // ((1 << X) & 8) != 0 -> X == 3 4050 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); 4051 auto NewPred = ICmpInst::getInversePredicate(Pred); 4052 return new ICmpInst(NewPred, X, CmpC); 4053 } else if ((++ValToCheck).isPowerOf2()) { 4054 // ((1 << X) & 7) == 0 -> X >= 3 4055 // ((1 << X) & 7) != 0 -> X < 3 4056 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); 4057 auto NewPred = 4058 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT; 4059 return new ICmpInst(NewPred, X, CmpC); 4060 } 4061 } 4062 4063 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1. 4064 const APInt *CI; 4065 if (Op0KnownZeroInverted == 1 && 4066 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) { 4067 // ((8 >>u X) & 1) == 0 -> X != 3 4068 // ((8 >>u X) & 1) != 0 -> X == 3 4069 unsigned CmpVal = CI->countTrailingZeros(); 4070 auto NewPred = ICmpInst::getInversePredicate(Pred); 4071 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal)); 4072 } 4073 } 4074 break; 4075 } 4076 case ICmpInst::ICMP_ULT: { 4077 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 4078 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4079 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 4080 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4081 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 4082 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4083 4084 const APInt *CmpC; 4085 if (match(Op1, m_APInt(CmpC))) { 4086 // A <u C -> A == C-1 if min(A)+1 == C 4087 if (Op1Max == Op0Min + 1) { 4088 Constant *CMinus1 = ConstantInt::get(Op0->getType(), *CmpC - 1); 4089 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, CMinus1); 4090 } 4091 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear 4092 if (CmpC->isMinSignedValue()) { 4093 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType()); 4094 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes); 4095 } 4096 } 4097 break; 4098 } 4099 case ICmpInst::ICMP_UGT: { 4100 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 4101 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4102 4103 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 4104 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4105 4106 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 4107 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4108 4109 const APInt *CmpC; 4110 if (match(Op1, m_APInt(CmpC))) { 4111 // A >u C -> A == C+1 if max(a)-1 == C 4112 if (*CmpC == Op0Max - 1) 4113 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4114 ConstantInt::get(Op1->getType(), *CmpC + 1)); 4115 4116 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set 4117 if (CmpC->isMaxSignedValue()) 4118 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, 4119 Constant::getNullValue(Op0->getType())); 4120 } 4121 break; 4122 } 4123 case ICmpInst::ICMP_SLT: 4124 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 4125 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4126 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 4127 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4128 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 4129 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4130 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 4131 if (Op1Max == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C 4132 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4133 Builder->getInt(CI->getValue() - 1)); 4134 } 4135 break; 4136 case ICmpInst::ICMP_SGT: 4137 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 4138 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4139 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 4140 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4141 4142 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 4143 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 4144 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) { 4145 if (Op1Min == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C 4146 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 4147 Builder->getInt(CI->getValue() + 1)); 4148 } 4149 break; 4150 case ICmpInst::ICMP_SGE: 4151 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 4152 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 4153 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4154 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 4155 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4156 break; 4157 case ICmpInst::ICMP_SLE: 4158 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 4159 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 4160 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4161 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 4162 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4163 break; 4164 case ICmpInst::ICMP_UGE: 4165 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 4166 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 4167 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4168 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 4169 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4170 break; 4171 case ICmpInst::ICMP_ULE: 4172 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 4173 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 4174 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 4175 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 4176 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 4177 break; 4178 } 4179 4180 // Turn a signed comparison into an unsigned one if both operands are known to 4181 // have the same sign. 4182 if (I.isSigned() && 4183 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) || 4184 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative()))) 4185 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 4186 4187 return nullptr; 4188 } 4189 4190 /// If we have an icmp le or icmp ge instruction with a constant operand, turn 4191 /// it into the appropriate icmp lt or icmp gt instruction. This transform 4192 /// allows them to be folded in visitICmpInst. 4193 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) { 4194 ICmpInst::Predicate Pred = I.getPredicate(); 4195 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGE && 4196 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_UGE) 4197 return nullptr; 4198 4199 Value *Op0 = I.getOperand(0); 4200 Value *Op1 = I.getOperand(1); 4201 auto *Op1C = dyn_cast<Constant>(Op1); 4202 if (!Op1C) 4203 return nullptr; 4204 4205 // Check if the constant operand can be safely incremented/decremented without 4206 // overflowing/underflowing. For scalars, SimplifyICmpInst has already handled 4207 // the edge cases for us, so we just assert on them. For vectors, we must 4208 // handle the edge cases. 4209 Type *Op1Type = Op1->getType(); 4210 bool IsSigned = I.isSigned(); 4211 bool IsLE = (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE); 4212 auto *CI = dyn_cast<ConstantInt>(Op1C); 4213 if (CI) { 4214 // A <= MAX -> TRUE ; A >= MIN -> TRUE 4215 assert(IsLE ? !CI->isMaxValue(IsSigned) : !CI->isMinValue(IsSigned)); 4216 } else if (Op1Type->isVectorTy()) { 4217 // TODO? If the edge cases for vectors were guaranteed to be handled as they 4218 // are for scalar, we could remove the min/max checks. However, to do that, 4219 // we would have to use insertelement/shufflevector to replace edge values. 4220 unsigned NumElts = Op1Type->getVectorNumElements(); 4221 for (unsigned i = 0; i != NumElts; ++i) { 4222 Constant *Elt = Op1C->getAggregateElement(i); 4223 if (!Elt) 4224 return nullptr; 4225 4226 if (isa<UndefValue>(Elt)) 4227 continue; 4228 4229 // Bail out if we can't determine if this constant is min/max or if we 4230 // know that this constant is min/max. 4231 auto *CI = dyn_cast<ConstantInt>(Elt); 4232 if (!CI || (IsLE ? CI->isMaxValue(IsSigned) : CI->isMinValue(IsSigned))) 4233 return nullptr; 4234 } 4235 } else { 4236 // ConstantExpr? 4237 return nullptr; 4238 } 4239 4240 // Increment or decrement the constant and set the new comparison predicate: 4241 // ULE -> ULT ; UGE -> UGT ; SLE -> SLT ; SGE -> SGT 4242 Constant *OneOrNegOne = ConstantInt::get(Op1Type, IsLE ? 1 : -1, true); 4243 CmpInst::Predicate NewPred = IsLE ? ICmpInst::ICMP_ULT: ICmpInst::ICMP_UGT; 4244 NewPred = IsSigned ? ICmpInst::getSignedPredicate(NewPred) : NewPred; 4245 return new ICmpInst(NewPred, Op0, ConstantExpr::getAdd(Op1C, OneOrNegOne)); 4246 } 4247 4248 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) { 4249 bool Changed = false; 4250 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4251 unsigned Op0Cplxity = getComplexity(Op0); 4252 unsigned Op1Cplxity = getComplexity(Op1); 4253 4254 /// Orders the operands of the compare so that they are listed from most 4255 /// complex to least complex. This puts constants before unary operators, 4256 /// before binary operators. 4257 if (Op0Cplxity < Op1Cplxity || 4258 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) { 4259 I.swapOperands(); 4260 std::swap(Op0, Op1); 4261 Changed = true; 4262 } 4263 4264 if (Value *V = 4265 SimplifyICmpInst(I.getPredicate(), Op0, Op1, DL, &TLI, &DT, &AC, &I)) 4266 return replaceInstUsesWith(I, V); 4267 4268 // comparing -val or val with non-zero is the same as just comparing val 4269 // ie, abs(val) != 0 -> val != 0 4270 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) { 4271 Value *Cond, *SelectTrue, *SelectFalse; 4272 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue), 4273 m_Value(SelectFalse)))) { 4274 if (Value *V = dyn_castNegVal(SelectTrue)) { 4275 if (V == SelectFalse) 4276 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 4277 } 4278 else if (Value *V = dyn_castNegVal(SelectFalse)) { 4279 if (V == SelectTrue) 4280 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 4281 } 4282 } 4283 } 4284 4285 Type *Ty = Op0->getType(); 4286 4287 // icmp's with boolean values can always be turned into bitwise operations 4288 if (Ty->getScalarType()->isIntegerTy(1)) { 4289 switch (I.getPredicate()) { 4290 default: llvm_unreachable("Invalid icmp instruction!"); 4291 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B) 4292 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName() + "tmp"); 4293 return BinaryOperator::CreateNot(Xor); 4294 } 4295 case ICmpInst::ICMP_NE: // icmp ne i1 A, B -> A^B 4296 return BinaryOperator::CreateXor(Op0, Op1); 4297 4298 case ICmpInst::ICMP_UGT: 4299 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult 4300 LLVM_FALLTHROUGH; 4301 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B 4302 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp"); 4303 return BinaryOperator::CreateAnd(Not, Op1); 4304 } 4305 case ICmpInst::ICMP_SGT: 4306 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt 4307 LLVM_FALLTHROUGH; 4308 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B 4309 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp"); 4310 return BinaryOperator::CreateAnd(Not, Op0); 4311 } 4312 case ICmpInst::ICMP_UGE: 4313 std::swap(Op0, Op1); // Change icmp uge -> icmp ule 4314 LLVM_FALLTHROUGH; 4315 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B 4316 Value *Not = Builder->CreateNot(Op0, I.getName() + "tmp"); 4317 return BinaryOperator::CreateOr(Not, Op1); 4318 } 4319 case ICmpInst::ICMP_SGE: 4320 std::swap(Op0, Op1); // Change icmp sge -> icmp sle 4321 LLVM_FALLTHROUGH; 4322 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B 4323 Value *Not = Builder->CreateNot(Op1, I.getName() + "tmp"); 4324 return BinaryOperator::CreateOr(Not, Op0); 4325 } 4326 } 4327 } 4328 4329 if (ICmpInst *NewICmp = canonicalizeCmpWithConstant(I)) 4330 return NewICmp; 4331 4332 if (Instruction *Res = foldICmpWithConstant(I)) 4333 return Res; 4334 4335 if (Instruction *Res = foldICmpUsingKnownBits(I)) 4336 return Res; 4337 4338 // Test if the ICmpInst instruction is used exclusively by a select as 4339 // part of a minimum or maximum operation. If so, refrain from doing 4340 // any other folding. This helps out other analyses which understand 4341 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 4342 // and CodeGen. And in this case, at least one of the comparison 4343 // operands has at least one user besides the compare (the select), 4344 // which would often largely negate the benefit of folding anyway. 4345 if (I.hasOneUse()) 4346 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin())) 4347 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || 4348 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) 4349 return nullptr; 4350 4351 if (Instruction *Res = foldICmpInstWithConstant(I)) 4352 return Res; 4353 4354 if (Instruction *Res = foldICmpInstWithConstantNotInt(I)) 4355 return Res; 4356 4357 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. 4358 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) 4359 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I)) 4360 return NI; 4361 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) 4362 if (Instruction *NI = foldGEPICmp(GEP, Op0, 4363 ICmpInst::getSwappedPredicate(I.getPredicate()), I)) 4364 return NI; 4365 4366 // Try to optimize equality comparisons against alloca-based pointers. 4367 if (Op0->getType()->isPointerTy() && I.isEquality()) { 4368 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?"); 4369 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op0, DL))) 4370 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1)) 4371 return New; 4372 if (auto *Alloca = dyn_cast<AllocaInst>(GetUnderlyingObject(Op1, DL))) 4373 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0)) 4374 return New; 4375 } 4376 4377 // Test to see if the operands of the icmp are casted versions of other 4378 // values. If the ptr->ptr cast can be stripped off both arguments, we do so 4379 // now. 4380 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) { 4381 if (Op0->getType()->isPointerTy() && 4382 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 4383 // We keep moving the cast from the left operand over to the right 4384 // operand, where it can often be eliminated completely. 4385 Op0 = CI->getOperand(0); 4386 4387 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 4388 // so eliminate it as well. 4389 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1)) 4390 Op1 = CI2->getOperand(0); 4391 4392 // If Op1 is a constant, we can fold the cast into the constant. 4393 if (Op0->getType() != Op1->getType()) { 4394 if (Constant *Op1C = dyn_cast<Constant>(Op1)) { 4395 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType()); 4396 } else { 4397 // Otherwise, cast the RHS right before the icmp 4398 Op1 = Builder->CreateBitCast(Op1, Op0->getType()); 4399 } 4400 } 4401 return new ICmpInst(I.getPredicate(), Op0, Op1); 4402 } 4403 } 4404 4405 if (isa<CastInst>(Op0)) { 4406 // Handle the special case of: icmp (cast bool to X), <cst> 4407 // This comes up when you have code like 4408 // int X = A < B; 4409 // if (X) ... 4410 // For generality, we handle any zero-extension of any operand comparison 4411 // with a constant or another cast from the same type. 4412 if (isa<Constant>(Op1) || isa<CastInst>(Op1)) 4413 if (Instruction *R = foldICmpWithCastAndCast(I)) 4414 return R; 4415 } 4416 4417 if (Instruction *Res = foldICmpBinOp(I)) 4418 return Res; 4419 4420 if (Instruction *Res = foldICmpWithMinMax(I)) 4421 return Res; 4422 4423 { 4424 Value *A, *B; 4425 // Transform (A & ~B) == 0 --> (A & B) != 0 4426 // and (A & ~B) != 0 --> (A & B) == 0 4427 // if A is a power of 2. 4428 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) && 4429 match(Op1, m_Zero()) && 4430 isKnownToBeAPowerOfTwo(A, DL, false, 0, &AC, &I, &DT) && I.isEquality()) 4431 return new ICmpInst(I.getInversePredicate(), 4432 Builder->CreateAnd(A, B), 4433 Op1); 4434 4435 // ~x < ~y --> y < x 4436 // ~x < cst --> ~cst < x 4437 if (match(Op0, m_Not(m_Value(A)))) { 4438 if (match(Op1, m_Not(m_Value(B)))) 4439 return new ICmpInst(I.getPredicate(), B, A); 4440 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) 4441 return new ICmpInst(I.getPredicate(), ConstantExpr::getNot(RHSC), A); 4442 } 4443 4444 Instruction *AddI = nullptr; 4445 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B), 4446 m_Instruction(AddI))) && 4447 isa<IntegerType>(A->getType())) { 4448 Value *Result; 4449 Constant *Overflow; 4450 if (OptimizeOverflowCheck(OCF_UNSIGNED_ADD, A, B, *AddI, Result, 4451 Overflow)) { 4452 replaceInstUsesWith(*AddI, Result); 4453 return replaceInstUsesWith(I, Overflow); 4454 } 4455 } 4456 4457 // (zext a) * (zext b) --> llvm.umul.with.overflow. 4458 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 4459 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this)) 4460 return R; 4461 } 4462 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 4463 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this)) 4464 return R; 4465 } 4466 } 4467 4468 if (Instruction *Res = foldICmpEquality(I)) 4469 return Res; 4470 4471 // The 'cmpxchg' instruction returns an aggregate containing the old value and 4472 // an i1 which indicates whether or not we successfully did the swap. 4473 // 4474 // Replace comparisons between the old value and the expected value with the 4475 // indicator that 'cmpxchg' returns. 4476 // 4477 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to 4478 // spuriously fail. In those cases, the old value may equal the expected 4479 // value but it is possible for the swap to not occur. 4480 if (I.getPredicate() == ICmpInst::ICMP_EQ) 4481 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0)) 4482 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand())) 4483 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 && 4484 !ACXI->isWeak()) 4485 return ExtractValueInst::Create(ACXI, 1); 4486 4487 { 4488 Value *X; ConstantInt *Cst; 4489 // icmp X+Cst, X 4490 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X) 4491 return foldICmpAddOpConst(I, X, Cst, I.getPredicate()); 4492 4493 // icmp X, X+Cst 4494 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X) 4495 return foldICmpAddOpConst(I, X, Cst, I.getSwappedPredicate()); 4496 } 4497 return Changed ? &I : nullptr; 4498 } 4499 4500 /// Fold fcmp ([us]itofp x, cst) if possible. 4501 Instruction *InstCombiner::foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, 4502 Constant *RHSC) { 4503 if (!isa<ConstantFP>(RHSC)) return nullptr; 4504 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 4505 4506 // Get the width of the mantissa. We don't want to hack on conversions that 4507 // might lose information from the integer, e.g. "i64 -> float" 4508 int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 4509 if (MantissaWidth == -1) return nullptr; // Unknown. 4510 4511 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 4512 4513 bool LHSUnsigned = isa<UIToFPInst>(LHSI); 4514 4515 if (I.isEquality()) { 4516 FCmpInst::Predicate P = I.getPredicate(); 4517 bool IsExact = false; 4518 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned); 4519 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact); 4520 4521 // If the floating point constant isn't an integer value, we know if we will 4522 // ever compare equal / not equal to it. 4523 if (!IsExact) { 4524 // TODO: Can never be -0.0 and other non-representable values 4525 APFloat RHSRoundInt(RHS); 4526 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven); 4527 if (RHS.compare(RHSRoundInt) != APFloat::cmpEqual) { 4528 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ) 4529 return replaceInstUsesWith(I, Builder->getFalse()); 4530 4531 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE); 4532 return replaceInstUsesWith(I, Builder->getTrue()); 4533 } 4534 } 4535 4536 // TODO: If the constant is exactly representable, is it always OK to do 4537 // equality compares as integer? 4538 } 4539 4540 // Check to see that the input is converted from an integer type that is small 4541 // enough that preserves all bits. TODO: check here for "known" sign bits. 4542 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 4543 unsigned InputSize = IntTy->getScalarSizeInBits(); 4544 4545 // Following test does NOT adjust InputSize downwards for signed inputs, 4546 // because the most negative value still requires all the mantissa bits 4547 // to distinguish it from one less than that value. 4548 if ((int)InputSize > MantissaWidth) { 4549 // Conversion would lose accuracy. Check if loss can impact comparison. 4550 int Exp = ilogb(RHS); 4551 if (Exp == APFloat::IEK_Inf) { 4552 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics())); 4553 if (MaxExponent < (int)InputSize - !LHSUnsigned) 4554 // Conversion could create infinity. 4555 return nullptr; 4556 } else { 4557 // Note that if RHS is zero or NaN, then Exp is negative 4558 // and first condition is trivially false. 4559 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned) 4560 // Conversion could affect comparison. 4561 return nullptr; 4562 } 4563 } 4564 4565 // Otherwise, we can potentially simplify the comparison. We know that it 4566 // will always come through as an integer value and we know the constant is 4567 // not a NAN (it would have been previously simplified). 4568 assert(!RHS.isNaN() && "NaN comparison not already folded!"); 4569 4570 ICmpInst::Predicate Pred; 4571 switch (I.getPredicate()) { 4572 default: llvm_unreachable("Unexpected predicate!"); 4573 case FCmpInst::FCMP_UEQ: 4574 case FCmpInst::FCMP_OEQ: 4575 Pred = ICmpInst::ICMP_EQ; 4576 break; 4577 case FCmpInst::FCMP_UGT: 4578 case FCmpInst::FCMP_OGT: 4579 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 4580 break; 4581 case FCmpInst::FCMP_UGE: 4582 case FCmpInst::FCMP_OGE: 4583 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 4584 break; 4585 case FCmpInst::FCMP_ULT: 4586 case FCmpInst::FCMP_OLT: 4587 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 4588 break; 4589 case FCmpInst::FCMP_ULE: 4590 case FCmpInst::FCMP_OLE: 4591 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 4592 break; 4593 case FCmpInst::FCMP_UNE: 4594 case FCmpInst::FCMP_ONE: 4595 Pred = ICmpInst::ICMP_NE; 4596 break; 4597 case FCmpInst::FCMP_ORD: 4598 return replaceInstUsesWith(I, Builder->getTrue()); 4599 case FCmpInst::FCMP_UNO: 4600 return replaceInstUsesWith(I, Builder->getFalse()); 4601 } 4602 4603 // Now we know that the APFloat is a normal number, zero or inf. 4604 4605 // See if the FP constant is too large for the integer. For example, 4606 // comparing an i8 to 300.0. 4607 unsigned IntWidth = IntTy->getScalarSizeInBits(); 4608 4609 if (!LHSUnsigned) { 4610 // If the RHS value is > SignedMax, fold the comparison. This handles +INF 4611 // and large values. 4612 APFloat SMax(RHS.getSemantics()); 4613 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 4614 APFloat::rmNearestTiesToEven); 4615 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0 4616 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 4617 Pred == ICmpInst::ICMP_SLE) 4618 return replaceInstUsesWith(I, Builder->getTrue()); 4619 return replaceInstUsesWith(I, Builder->getFalse()); 4620 } 4621 } else { 4622 // If the RHS value is > UnsignedMax, fold the comparison. This handles 4623 // +INF and large values. 4624 APFloat UMax(RHS.getSemantics()); 4625 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 4626 APFloat::rmNearestTiesToEven); 4627 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0 4628 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 4629 Pred == ICmpInst::ICMP_ULE) 4630 return replaceInstUsesWith(I, Builder->getTrue()); 4631 return replaceInstUsesWith(I, Builder->getFalse()); 4632 } 4633 } 4634 4635 if (!LHSUnsigned) { 4636 // See if the RHS value is < SignedMin. 4637 APFloat SMin(RHS.getSemantics()); 4638 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 4639 APFloat::rmNearestTiesToEven); 4640 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0 4641 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 4642 Pred == ICmpInst::ICMP_SGE) 4643 return replaceInstUsesWith(I, Builder->getTrue()); 4644 return replaceInstUsesWith(I, Builder->getFalse()); 4645 } 4646 } else { 4647 // See if the RHS value is < UnsignedMin. 4648 APFloat SMin(RHS.getSemantics()); 4649 SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true, 4650 APFloat::rmNearestTiesToEven); 4651 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // umin > 12312.0 4652 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT || 4653 Pred == ICmpInst::ICMP_UGE) 4654 return replaceInstUsesWith(I, Builder->getTrue()); 4655 return replaceInstUsesWith(I, Builder->getFalse()); 4656 } 4657 } 4658 4659 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 4660 // [0, UMAX], but it may still be fractional. See if it is fractional by 4661 // casting the FP value to the integer value and back, checking for equality. 4662 // Don't do this for zero, because -0.0 is not fractional. 4663 Constant *RHSInt = LHSUnsigned 4664 ? ConstantExpr::getFPToUI(RHSC, IntTy) 4665 : ConstantExpr::getFPToSI(RHSC, IntTy); 4666 if (!RHS.isZero()) { 4667 bool Equal = LHSUnsigned 4668 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 4669 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 4670 if (!Equal) { 4671 // If we had a comparison against a fractional value, we have to adjust 4672 // the compare predicate and sometimes the value. RHSC is rounded towards 4673 // zero at this point. 4674 switch (Pred) { 4675 default: llvm_unreachable("Unexpected integer comparison!"); 4676 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 4677 return replaceInstUsesWith(I, Builder->getTrue()); 4678 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 4679 return replaceInstUsesWith(I, Builder->getFalse()); 4680 case ICmpInst::ICMP_ULE: 4681 // (float)int <= 4.4 --> int <= 4 4682 // (float)int <= -4.4 --> false 4683 if (RHS.isNegative()) 4684 return replaceInstUsesWith(I, Builder->getFalse()); 4685 break; 4686 case ICmpInst::ICMP_SLE: 4687 // (float)int <= 4.4 --> int <= 4 4688 // (float)int <= -4.4 --> int < -4 4689 if (RHS.isNegative()) 4690 Pred = ICmpInst::ICMP_SLT; 4691 break; 4692 case ICmpInst::ICMP_ULT: 4693 // (float)int < -4.4 --> false 4694 // (float)int < 4.4 --> int <= 4 4695 if (RHS.isNegative()) 4696 return replaceInstUsesWith(I, Builder->getFalse()); 4697 Pred = ICmpInst::ICMP_ULE; 4698 break; 4699 case ICmpInst::ICMP_SLT: 4700 // (float)int < -4.4 --> int < -4 4701 // (float)int < 4.4 --> int <= 4 4702 if (!RHS.isNegative()) 4703 Pred = ICmpInst::ICMP_SLE; 4704 break; 4705 case ICmpInst::ICMP_UGT: 4706 // (float)int > 4.4 --> int > 4 4707 // (float)int > -4.4 --> true 4708 if (RHS.isNegative()) 4709 return replaceInstUsesWith(I, Builder->getTrue()); 4710 break; 4711 case ICmpInst::ICMP_SGT: 4712 // (float)int > 4.4 --> int > 4 4713 // (float)int > -4.4 --> int >= -4 4714 if (RHS.isNegative()) 4715 Pred = ICmpInst::ICMP_SGE; 4716 break; 4717 case ICmpInst::ICMP_UGE: 4718 // (float)int >= -4.4 --> true 4719 // (float)int >= 4.4 --> int > 4 4720 if (RHS.isNegative()) 4721 return replaceInstUsesWith(I, Builder->getTrue()); 4722 Pred = ICmpInst::ICMP_UGT; 4723 break; 4724 case ICmpInst::ICMP_SGE: 4725 // (float)int >= -4.4 --> int >= -4 4726 // (float)int >= 4.4 --> int > 4 4727 if (!RHS.isNegative()) 4728 Pred = ICmpInst::ICMP_SGT; 4729 break; 4730 } 4731 } 4732 } 4733 4734 // Lower this FP comparison into an appropriate integer version of the 4735 // comparison. 4736 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 4737 } 4738 4739 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) { 4740 bool Changed = false; 4741 4742 /// Orders the operands of the compare so that they are listed from most 4743 /// complex to least complex. This puts constants before unary operators, 4744 /// before binary operators. 4745 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 4746 I.swapOperands(); 4747 Changed = true; 4748 } 4749 4750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4751 4752 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, 4753 I.getFastMathFlags(), DL, &TLI, &DT, &AC, &I)) 4754 return replaceInstUsesWith(I, V); 4755 4756 // Simplify 'fcmp pred X, X' 4757 if (Op0 == Op1) { 4758 switch (I.getPredicate()) { 4759 default: llvm_unreachable("Unknown predicate!"); 4760 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 4761 case FCmpInst::FCMP_ULT: // True if unordered or less than 4762 case FCmpInst::FCMP_UGT: // True if unordered or greater than 4763 case FCmpInst::FCMP_UNE: // True if unordered or not equal 4764 // Canonicalize these to be 'fcmp uno %X, 0.0'. 4765 I.setPredicate(FCmpInst::FCMP_UNO); 4766 I.setOperand(1, Constant::getNullValue(Op0->getType())); 4767 return &I; 4768 4769 case FCmpInst::FCMP_ORD: // True if ordered (no nans) 4770 case FCmpInst::FCMP_OEQ: // True if ordered and equal 4771 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 4772 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 4773 // Canonicalize these to be 'fcmp ord %X, 0.0'. 4774 I.setPredicate(FCmpInst::FCMP_ORD); 4775 I.setOperand(1, Constant::getNullValue(Op0->getType())); 4776 return &I; 4777 } 4778 } 4779 4780 // Test if the FCmpInst instruction is used exclusively by a select as 4781 // part of a minimum or maximum operation. If so, refrain from doing 4782 // any other folding. This helps out other analyses which understand 4783 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 4784 // and CodeGen. And in this case, at least one of the comparison 4785 // operands has at least one user besides the compare (the select), 4786 // which would often largely negate the benefit of folding anyway. 4787 if (I.hasOneUse()) 4788 if (SelectInst *SI = dyn_cast<SelectInst>(*I.user_begin())) 4789 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) || 4790 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1)) 4791 return nullptr; 4792 4793 // Handle fcmp with constant RHS 4794 if (Constant *RHSC = dyn_cast<Constant>(Op1)) { 4795 if (Instruction *LHSI = dyn_cast<Instruction>(Op0)) 4796 switch (LHSI->getOpcode()) { 4797 case Instruction::FPExt: { 4798 // fcmp (fpext x), C -> fcmp x, (fptrunc C) if fptrunc is lossless 4799 FPExtInst *LHSExt = cast<FPExtInst>(LHSI); 4800 ConstantFP *RHSF = dyn_cast<ConstantFP>(RHSC); 4801 if (!RHSF) 4802 break; 4803 4804 const fltSemantics *Sem; 4805 // FIXME: This shouldn't be here. 4806 if (LHSExt->getSrcTy()->isHalfTy()) 4807 Sem = &APFloat::IEEEhalf(); 4808 else if (LHSExt->getSrcTy()->isFloatTy()) 4809 Sem = &APFloat::IEEEsingle(); 4810 else if (LHSExt->getSrcTy()->isDoubleTy()) 4811 Sem = &APFloat::IEEEdouble(); 4812 else if (LHSExt->getSrcTy()->isFP128Ty()) 4813 Sem = &APFloat::IEEEquad(); 4814 else if (LHSExt->getSrcTy()->isX86_FP80Ty()) 4815 Sem = &APFloat::x87DoubleExtended(); 4816 else if (LHSExt->getSrcTy()->isPPC_FP128Ty()) 4817 Sem = &APFloat::PPCDoubleDouble(); 4818 else 4819 break; 4820 4821 bool Lossy; 4822 APFloat F = RHSF->getValueAPF(); 4823 F.convert(*Sem, APFloat::rmNearestTiesToEven, &Lossy); 4824 4825 // Avoid lossy conversions and denormals. Zero is a special case 4826 // that's OK to convert. 4827 APFloat Fabs = F; 4828 Fabs.clearSign(); 4829 if (!Lossy && 4830 ((Fabs.compare(APFloat::getSmallestNormalized(*Sem)) != 4831 APFloat::cmpLessThan) || Fabs.isZero())) 4832 4833 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0), 4834 ConstantFP::get(RHSC->getContext(), F)); 4835 break; 4836 } 4837 case Instruction::PHI: 4838 // Only fold fcmp into the PHI if the phi and fcmp are in the same 4839 // block. If in the same block, we're encouraging jump threading. If 4840 // not, we are just pessimizing the code by making an i1 phi. 4841 if (LHSI->getParent() == I.getParent()) 4842 if (Instruction *NV = FoldOpIntoPhi(I)) 4843 return NV; 4844 break; 4845 case Instruction::SIToFP: 4846 case Instruction::UIToFP: 4847 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC)) 4848 return NV; 4849 break; 4850 case Instruction::FSub: { 4851 // fcmp pred (fneg x), C -> fcmp swap(pred) x, -C 4852 Value *Op; 4853 if (match(LHSI, m_FNeg(m_Value(Op)))) 4854 return new FCmpInst(I.getSwappedPredicate(), Op, 4855 ConstantExpr::getFNeg(RHSC)); 4856 break; 4857 } 4858 case Instruction::Load: 4859 if (GetElementPtrInst *GEP = 4860 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 4861 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 4862 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 4863 !cast<LoadInst>(LHSI)->isVolatile()) 4864 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) 4865 return Res; 4866 } 4867 break; 4868 case Instruction::Call: { 4869 if (!RHSC->isNullValue()) 4870 break; 4871 4872 CallInst *CI = cast<CallInst>(LHSI); 4873 Intrinsic::ID IID = getIntrinsicForCallSite(CI, &TLI); 4874 if (IID != Intrinsic::fabs) 4875 break; 4876 4877 // Various optimization for fabs compared with zero. 4878 switch (I.getPredicate()) { 4879 default: 4880 break; 4881 // fabs(x) < 0 --> false 4882 case FCmpInst::FCMP_OLT: 4883 llvm_unreachable("handled by SimplifyFCmpInst"); 4884 // fabs(x) > 0 --> x != 0 4885 case FCmpInst::FCMP_OGT: 4886 return new FCmpInst(FCmpInst::FCMP_ONE, CI->getArgOperand(0), RHSC); 4887 // fabs(x) <= 0 --> x == 0 4888 case FCmpInst::FCMP_OLE: 4889 return new FCmpInst(FCmpInst::FCMP_OEQ, CI->getArgOperand(0), RHSC); 4890 // fabs(x) >= 0 --> !isnan(x) 4891 case FCmpInst::FCMP_OGE: 4892 return new FCmpInst(FCmpInst::FCMP_ORD, CI->getArgOperand(0), RHSC); 4893 // fabs(x) == 0 --> x == 0 4894 // fabs(x) != 0 --> x != 0 4895 case FCmpInst::FCMP_OEQ: 4896 case FCmpInst::FCMP_UEQ: 4897 case FCmpInst::FCMP_ONE: 4898 case FCmpInst::FCMP_UNE: 4899 return new FCmpInst(I.getPredicate(), CI->getArgOperand(0), RHSC); 4900 } 4901 } 4902 } 4903 } 4904 4905 // fcmp pred (fneg x), (fneg y) -> fcmp swap(pred) x, y 4906 Value *X, *Y; 4907 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 4908 return new FCmpInst(I.getSwappedPredicate(), X, Y); 4909 4910 // fcmp (fpext x), (fpext y) -> fcmp x, y 4911 if (FPExtInst *LHSExt = dyn_cast<FPExtInst>(Op0)) 4912 if (FPExtInst *RHSExt = dyn_cast<FPExtInst>(Op1)) 4913 if (LHSExt->getSrcTy() == RHSExt->getSrcTy()) 4914 return new FCmpInst(I.getPredicate(), LHSExt->getOperand(0), 4915 RHSExt->getOperand(0)); 4916 4917 return Changed ? &I : nullptr; 4918 } 4919