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