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