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