1 //===- InstCombineCompares.cpp --------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitICmp and visitFCmp functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/APSInt.h" 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/ConstantFolding.h" 18 #include "llvm/Analysis/InstructionSimplify.h" 19 #include "llvm/Analysis/TargetLibraryInfo.h" 20 #include "llvm/IR/ConstantRange.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/GetElementPtrTypeIterator.h" 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/IR/PatternMatch.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/KnownBits.h" 27 #include "llvm/Transforms/InstCombine/InstCombiner.h" 28 29 using namespace llvm; 30 using namespace PatternMatch; 31 32 #define DEBUG_TYPE "instcombine" 33 34 // How many times is a select replaced by one of its operands? 35 STATISTIC(NumSel, "Number of select opts"); 36 37 38 /// Compute Result = In1+In2, returning true if the result overflowed for this 39 /// type. 40 static bool addWithOverflow(APInt &Result, const APInt &In1, 41 const APInt &In2, bool IsSigned = false) { 42 bool Overflow; 43 if (IsSigned) 44 Result = In1.sadd_ov(In2, Overflow); 45 else 46 Result = In1.uadd_ov(In2, Overflow); 47 48 return Overflow; 49 } 50 51 /// Compute Result = In1-In2, returning true if the result overflowed for this 52 /// type. 53 static bool subWithOverflow(APInt &Result, const APInt &In1, 54 const APInt &In2, bool IsSigned = false) { 55 bool Overflow; 56 if (IsSigned) 57 Result = In1.ssub_ov(In2, Overflow); 58 else 59 Result = In1.usub_ov(In2, Overflow); 60 61 return Overflow; 62 } 63 64 /// Given an icmp instruction, return true if any use of this comparison is a 65 /// branch on sign bit comparison. 66 static bool hasBranchUse(ICmpInst &I) { 67 for (auto *U : I.users()) 68 if (isa<BranchInst>(U)) 69 return true; 70 return false; 71 } 72 73 /// Returns true if the exploded icmp can be expressed as a signed comparison 74 /// to zero and updates the predicate accordingly. 75 /// The signedness of the comparison is preserved. 76 /// TODO: Refactor with decomposeBitTestICmp()? 77 static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) { 78 if (!ICmpInst::isSigned(Pred)) 79 return false; 80 81 if (C.isNullValue()) 82 return ICmpInst::isRelational(Pred); 83 84 if (C.isOneValue()) { 85 if (Pred == ICmpInst::ICMP_SLT) { 86 Pred = ICmpInst::ICMP_SLE; 87 return true; 88 } 89 } else if (C.isAllOnesValue()) { 90 if (Pred == ICmpInst::ICMP_SGT) { 91 Pred = ICmpInst::ICMP_SGE; 92 return true; 93 } 94 } 95 96 return false; 97 } 98 99 /// Given a signed integer type and a set of known zero and one bits, compute 100 /// the maximum and minimum values that could have the specified known zero and 101 /// known one bits, returning them in Min/Max. 102 /// TODO: Move to method on KnownBits struct? 103 static void computeSignedMinMaxValuesFromKnownBits(const KnownBits &Known, 104 APInt &Min, APInt &Max) { 105 assert(Known.getBitWidth() == Min.getBitWidth() && 106 Known.getBitWidth() == Max.getBitWidth() && 107 "KnownZero, KnownOne and Min, Max must have equal bitwidth."); 108 APInt UnknownBits = ~(Known.Zero|Known.One); 109 110 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign 111 // bit if it is unknown. 112 Min = Known.One; 113 Max = Known.One|UnknownBits; 114 115 if (UnknownBits.isNegative()) { // Sign bit is unknown 116 Min.setSignBit(); 117 Max.clearSignBit(); 118 } 119 } 120 121 /// Given an unsigned integer type and a set of known zero and one bits, compute 122 /// the maximum and minimum values that could have the specified known zero and 123 /// known one bits, returning them in Min/Max. 124 /// TODO: Move to method on KnownBits struct? 125 static void computeUnsignedMinMaxValuesFromKnownBits(const KnownBits &Known, 126 APInt &Min, APInt &Max) { 127 assert(Known.getBitWidth() == Min.getBitWidth() && 128 Known.getBitWidth() == Max.getBitWidth() && 129 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth."); 130 APInt UnknownBits = ~(Known.Zero|Known.One); 131 132 // The minimum value is when the unknown bits are all zeros. 133 Min = Known.One; 134 // The maximum value is when the unknown bits are all ones. 135 Max = Known.One|UnknownBits; 136 } 137 138 /// This is called when we see this pattern: 139 /// cmp pred (load (gep GV, ...)), cmpcst 140 /// where GV is a global variable with a constant initializer. Try to simplify 141 /// this into some simple computation that does not need the load. For example 142 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3". 143 /// 144 /// If AndCst is non-null, then the loaded value is masked with that constant 145 /// before doing the comparison. This handles cases like "A[i]&4 == 0". 146 Instruction * 147 InstCombinerImpl::foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, 148 GlobalVariable *GV, CmpInst &ICI, 149 ConstantInt *AndCst) { 150 Constant *Init = GV->getInitializer(); 151 if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init)) 152 return nullptr; 153 154 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements(); 155 // Don't blow up on huge arrays. 156 if (ArrayElementCount > MaxArraySizeForCombine) 157 return nullptr; 158 159 // There are many forms of this optimization we can handle, for now, just do 160 // the simple index into a single-dimensional array. 161 // 162 // Require: GEP GV, 0, i {{, constant indices}} 163 if (GEP->getNumOperands() < 3 || 164 !isa<ConstantInt>(GEP->getOperand(1)) || 165 !cast<ConstantInt>(GEP->getOperand(1))->isZero() || 166 isa<Constant>(GEP->getOperand(2))) 167 return nullptr; 168 169 // Check that indices after the variable are constants and in-range for the 170 // type they index. Collect the indices. This is typically for arrays of 171 // structs. 172 SmallVector<unsigned, 4> LaterIndices; 173 174 Type *EltTy = Init->getType()->getArrayElementType(); 175 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) { 176 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i)); 177 if (!Idx) return nullptr; // Variable index. 178 179 uint64_t IdxVal = Idx->getZExtValue(); 180 if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index. 181 182 if (StructType *STy = dyn_cast<StructType>(EltTy)) 183 EltTy = STy->getElementType(IdxVal); 184 else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) { 185 if (IdxVal >= ATy->getNumElements()) return nullptr; 186 EltTy = ATy->getElementType(); 187 } else { 188 return nullptr; // Unknown type. 189 } 190 191 LaterIndices.push_back(IdxVal); 192 } 193 194 enum { Overdefined = -3, Undefined = -2 }; 195 196 // Variables for our state machines. 197 198 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form 199 // "i == 47 | i == 87", where 47 is the first index the condition is true for, 200 // and 87 is the second (and last) index. FirstTrueElement is -2 when 201 // undefined, otherwise set to the first true element. SecondTrueElement is 202 // -2 when undefined, -3 when overdefined and >= 0 when that index is true. 203 int FirstTrueElement = Undefined, SecondTrueElement = Undefined; 204 205 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the 206 // form "i != 47 & i != 87". Same state transitions as for true elements. 207 int FirstFalseElement = Undefined, SecondFalseElement = Undefined; 208 209 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these 210 /// define a state machine that triggers for ranges of values that the index 211 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'. 212 /// This is -2 when undefined, -3 when overdefined, and otherwise the last 213 /// index in the range (inclusive). We use -2 for undefined here because we 214 /// use relative comparisons and don't want 0-1 to match -1. 215 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined; 216 217 // MagicBitvector - This is a magic bitvector where we set a bit if the 218 // comparison is true for element 'i'. If there are 64 elements or less in 219 // the array, this will fully represent all the comparison results. 220 uint64_t MagicBitvector = 0; 221 222 // Scan the array and see if one of our patterns matches. 223 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1)); 224 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) { 225 Constant *Elt = Init->getAggregateElement(i); 226 if (!Elt) return nullptr; 227 228 // If this is indexing an array of structures, get the structure element. 229 if (!LaterIndices.empty()) 230 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices); 231 232 // If the element is masked, handle it. 233 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst); 234 235 // Find out if the comparison would be true or false for the i'th element. 236 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt, 237 CompareRHS, DL, &TLI); 238 // If the result is undef for this element, ignore it. 239 if (isa<UndefValue>(C)) { 240 // Extend range state machines to cover this element in case there is an 241 // undef in the middle of the range. 242 if (TrueRangeEnd == (int)i-1) 243 TrueRangeEnd = i; 244 if (FalseRangeEnd == (int)i-1) 245 FalseRangeEnd = i; 246 continue; 247 } 248 249 // If we can't compute the result for any of the elements, we have to give 250 // up evaluating the entire conditional. 251 if (!isa<ConstantInt>(C)) return nullptr; 252 253 // Otherwise, we know if the comparison is true or false for this element, 254 // update our state machines. 255 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero(); 256 257 // State machine for single/double/range index comparison. 258 if (IsTrueForElt) { 259 // Update the TrueElement state machine. 260 if (FirstTrueElement == Undefined) 261 FirstTrueElement = TrueRangeEnd = i; // First true element. 262 else { 263 // Update double-compare state machine. 264 if (SecondTrueElement == Undefined) 265 SecondTrueElement = i; 266 else 267 SecondTrueElement = Overdefined; 268 269 // Update range state machine. 270 if (TrueRangeEnd == (int)i-1) 271 TrueRangeEnd = i; 272 else 273 TrueRangeEnd = Overdefined; 274 } 275 } else { 276 // Update the FalseElement state machine. 277 if (FirstFalseElement == Undefined) 278 FirstFalseElement = FalseRangeEnd = i; // First false element. 279 else { 280 // Update double-compare state machine. 281 if (SecondFalseElement == Undefined) 282 SecondFalseElement = i; 283 else 284 SecondFalseElement = Overdefined; 285 286 // Update range state machine. 287 if (FalseRangeEnd == (int)i-1) 288 FalseRangeEnd = i; 289 else 290 FalseRangeEnd = Overdefined; 291 } 292 } 293 294 // If this element is in range, update our magic bitvector. 295 if (i < 64 && IsTrueForElt) 296 MagicBitvector |= 1ULL << i; 297 298 // If all of our states become overdefined, bail out early. Since the 299 // predicate is expensive, only check it every 8 elements. This is only 300 // really useful for really huge arrays. 301 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined && 302 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined && 303 FalseRangeEnd == Overdefined) 304 return nullptr; 305 } 306 307 // Now that we've scanned the entire array, emit our new comparison(s). We 308 // order the state machines in complexity of the generated code. 309 Value *Idx = GEP->getOperand(2); 310 311 // If the index is larger than the pointer size of the target, truncate the 312 // index down like the GEP would do implicitly. We don't have to do this for 313 // an inbounds GEP because the index can't be out of range. 314 if (!GEP->isInBounds()) { 315 Type *IntPtrTy = DL.getIntPtrType(GEP->getType()); 316 unsigned PtrSize = IntPtrTy->getIntegerBitWidth(); 317 if (Idx->getType()->getPrimitiveSizeInBits() > PtrSize) 318 Idx = Builder.CreateTrunc(Idx, IntPtrTy); 319 } 320 321 // If the comparison is only true for one or two elements, emit direct 322 // comparisons. 323 if (SecondTrueElement != Overdefined) { 324 // None true -> false. 325 if (FirstTrueElement == Undefined) 326 return replaceInstUsesWith(ICI, Builder.getFalse()); 327 328 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement); 329 330 // True for one element -> 'i == 47'. 331 if (SecondTrueElement == Undefined) 332 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx); 333 334 // True for two elements -> 'i == 47 | i == 72'. 335 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx); 336 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement); 337 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx); 338 return BinaryOperator::CreateOr(C1, C2); 339 } 340 341 // If the comparison is only false for one or two elements, emit direct 342 // comparisons. 343 if (SecondFalseElement != Overdefined) { 344 // None false -> true. 345 if (FirstFalseElement == Undefined) 346 return replaceInstUsesWith(ICI, Builder.getTrue()); 347 348 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement); 349 350 // False for one element -> 'i != 47'. 351 if (SecondFalseElement == Undefined) 352 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx); 353 354 // False for two elements -> 'i != 47 & i != 72'. 355 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx); 356 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement); 357 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx); 358 return BinaryOperator::CreateAnd(C1, C2); 359 } 360 361 // If the comparison can be replaced with a range comparison for the elements 362 // where it is true, emit the range check. 363 if (TrueRangeEnd != Overdefined) { 364 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare"); 365 366 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1). 367 if (FirstTrueElement) { 368 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement); 369 Idx = Builder.CreateAdd(Idx, Offs); 370 } 371 372 Value *End = ConstantInt::get(Idx->getType(), 373 TrueRangeEnd-FirstTrueElement+1); 374 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End); 375 } 376 377 // False range check. 378 if (FalseRangeEnd != Overdefined) { 379 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare"); 380 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse). 381 if (FirstFalseElement) { 382 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement); 383 Idx = Builder.CreateAdd(Idx, Offs); 384 } 385 386 Value *End = ConstantInt::get(Idx->getType(), 387 FalseRangeEnd-FirstFalseElement); 388 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End); 389 } 390 391 // If a magic bitvector captures the entire comparison state 392 // of this load, replace it with computation that does: 393 // ((magic_cst >> i) & 1) != 0 394 { 395 Type *Ty = nullptr; 396 397 // Look for an appropriate type: 398 // - The type of Idx if the magic fits 399 // - The smallest fitting legal type 400 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth()) 401 Ty = Idx->getType(); 402 else 403 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount); 404 405 if (Ty) { 406 Value *V = Builder.CreateIntCast(Idx, Ty, false); 407 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V); 408 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V); 409 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0)); 410 } 411 } 412 413 return nullptr; 414 } 415 416 /// Return a value that can be used to compare the *offset* implied by a GEP to 417 /// zero. For example, if we have &A[i], we want to return 'i' for 418 /// "icmp ne i, 0". Note that, in general, indices can be complex, and scales 419 /// are involved. The above expression would also be legal to codegen as 420 /// "icmp ne (i*4), 0" (assuming A is a pointer to i32). 421 /// This latter form is less amenable to optimization though, and we are allowed 422 /// to generate the first by knowing that pointer arithmetic doesn't overflow. 423 /// 424 /// If we can't emit an optimized form for this expression, this returns null. 425 /// 426 static Value *evaluateGEPOffsetExpression(User *GEP, InstCombinerImpl &IC, 427 const DataLayout &DL) { 428 gep_type_iterator GTI = gep_type_begin(GEP); 429 430 // Check to see if this gep only has a single variable index. If so, and if 431 // any constant indices are a multiple of its scale, then we can compute this 432 // in terms of the scale of the variable index. For example, if the GEP 433 // implies an offset of "12 + i*4", then we can codegen this as "3 + i", 434 // because the expression will cross zero at the same point. 435 unsigned i, e = GEP->getNumOperands(); 436 int64_t Offset = 0; 437 for (i = 1; i != e; ++i, ++GTI) { 438 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 439 // Compute the aggregate offset of constant indices. 440 if (CI->isZero()) continue; 441 442 // Handle a struct index, which adds its field offset to the pointer. 443 if (StructType *STy = GTI.getStructTypeOrNull()) { 444 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 445 } else { 446 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 447 Offset += Size*CI->getSExtValue(); 448 } 449 } else { 450 // Found our variable index. 451 break; 452 } 453 } 454 455 // If there are no variable indices, we must have a constant offset, just 456 // evaluate it the general way. 457 if (i == e) return nullptr; 458 459 Value *VariableIdx = GEP->getOperand(i); 460 // Determine the scale factor of the variable element. For example, this is 461 // 4 if the variable index is into an array of i32. 462 uint64_t VariableScale = DL.getTypeAllocSize(GTI.getIndexedType()); 463 464 // Verify that there are no other variable indices. If so, emit the hard way. 465 for (++i, ++GTI; i != e; ++i, ++GTI) { 466 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i)); 467 if (!CI) return nullptr; 468 469 // Compute the aggregate offset of constant indices. 470 if (CI->isZero()) continue; 471 472 // Handle a struct index, which adds its field offset to the pointer. 473 if (StructType *STy = GTI.getStructTypeOrNull()) { 474 Offset += DL.getStructLayout(STy)->getElementOffset(CI->getZExtValue()); 475 } else { 476 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); 477 Offset += Size*CI->getSExtValue(); 478 } 479 } 480 481 // Okay, we know we have a single variable index, which must be a 482 // pointer/array/vector index. If there is no offset, life is simple, return 483 // the index. 484 Type *IntPtrTy = DL.getIntPtrType(GEP->getOperand(0)->getType()); 485 unsigned IntPtrWidth = IntPtrTy->getIntegerBitWidth(); 486 if (Offset == 0) { 487 // Cast to intptrty in case a truncation occurs. If an extension is needed, 488 // we don't need to bother extending: the extension won't affect where the 489 // computation crosses zero. 490 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth) { 491 VariableIdx = IC.Builder.CreateTrunc(VariableIdx, IntPtrTy); 492 } 493 return VariableIdx; 494 } 495 496 // Otherwise, there is an index. The computation we will do will be modulo 497 // the pointer size. 498 Offset = SignExtend64(Offset, IntPtrWidth); 499 VariableScale = SignExtend64(VariableScale, IntPtrWidth); 500 501 // To do this transformation, any constant index must be a multiple of the 502 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i", 503 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a 504 // multiple of the variable scale. 505 int64_t NewOffs = Offset / (int64_t)VariableScale; 506 if (Offset != NewOffs*(int64_t)VariableScale) 507 return nullptr; 508 509 // Okay, we can do this evaluation. Start by converting the index to intptr. 510 if (VariableIdx->getType() != IntPtrTy) 511 VariableIdx = IC.Builder.CreateIntCast(VariableIdx, IntPtrTy, 512 true /*Signed*/); 513 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs); 514 return IC.Builder.CreateAdd(VariableIdx, OffsetVal, "offset"); 515 } 516 517 /// Returns true if we can rewrite Start as a GEP with pointer Base 518 /// and some integer offset. The nodes that need to be re-written 519 /// for this transformation will be added to Explored. 520 static bool canRewriteGEPAsOffset(Value *Start, Value *Base, 521 const DataLayout &DL, 522 SetVector<Value *> &Explored) { 523 SmallVector<Value *, 16> WorkList(1, Start); 524 Explored.insert(Base); 525 526 // The following traversal gives us an order which can be used 527 // when doing the final transformation. Since in the final 528 // transformation we create the PHI replacement instructions first, 529 // we don't have to get them in any particular order. 530 // 531 // However, for other instructions we will have to traverse the 532 // operands of an instruction first, which means that we have to 533 // do a post-order traversal. 534 while (!WorkList.empty()) { 535 SetVector<PHINode *> PHIs; 536 537 while (!WorkList.empty()) { 538 if (Explored.size() >= 100) 539 return false; 540 541 Value *V = WorkList.back(); 542 543 if (Explored.count(V) != 0) { 544 WorkList.pop_back(); 545 continue; 546 } 547 548 if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) && 549 !isa<GetElementPtrInst>(V) && !isa<PHINode>(V)) 550 // We've found some value that we can't explore which is different from 551 // the base. Therefore we can't do this transformation. 552 return false; 553 554 if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) { 555 auto *CI = dyn_cast<CastInst>(V); 556 if (!CI->isNoopCast(DL)) 557 return false; 558 559 if (Explored.count(CI->getOperand(0)) == 0) 560 WorkList.push_back(CI->getOperand(0)); 561 } 562 563 if (auto *GEP = dyn_cast<GEPOperator>(V)) { 564 // We're limiting the GEP to having one index. This will preserve 565 // the original pointer type. We could handle more cases in the 566 // future. 567 if (GEP->getNumIndices() != 1 || !GEP->isInBounds() || 568 GEP->getType() != Start->getType()) 569 return false; 570 571 if (Explored.count(GEP->getOperand(0)) == 0) 572 WorkList.push_back(GEP->getOperand(0)); 573 } 574 575 if (WorkList.back() == V) { 576 WorkList.pop_back(); 577 // We've finished visiting this node, mark it as such. 578 Explored.insert(V); 579 } 580 581 if (auto *PN = dyn_cast<PHINode>(V)) { 582 // We cannot transform PHIs on unsplittable basic blocks. 583 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator())) 584 return false; 585 Explored.insert(PN); 586 PHIs.insert(PN); 587 } 588 } 589 590 // Explore the PHI nodes further. 591 for (auto *PN : PHIs) 592 for (Value *Op : PN->incoming_values()) 593 if (Explored.count(Op) == 0) 594 WorkList.push_back(Op); 595 } 596 597 // Make sure that we can do this. Since we can't insert GEPs in a basic 598 // block before a PHI node, we can't easily do this transformation if 599 // we have PHI node users of transformed instructions. 600 for (Value *Val : Explored) { 601 for (Value *Use : Val->uses()) { 602 603 auto *PHI = dyn_cast<PHINode>(Use); 604 auto *Inst = dyn_cast<Instruction>(Val); 605 606 if (Inst == Base || Inst == PHI || !Inst || !PHI || 607 Explored.count(PHI) == 0) 608 continue; 609 610 if (PHI->getParent() == Inst->getParent()) 611 return false; 612 } 613 } 614 return true; 615 } 616 617 // Sets the appropriate insert point on Builder where we can add 618 // a replacement Instruction for V (if that is possible). 619 static void setInsertionPoint(IRBuilder<> &Builder, Value *V, 620 bool Before = true) { 621 if (auto *PHI = dyn_cast<PHINode>(V)) { 622 Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt()); 623 return; 624 } 625 if (auto *I = dyn_cast<Instruction>(V)) { 626 if (!Before) 627 I = &*std::next(I->getIterator()); 628 Builder.SetInsertPoint(I); 629 return; 630 } 631 if (auto *A = dyn_cast<Argument>(V)) { 632 // Set the insertion point in the entry block. 633 BasicBlock &Entry = A->getParent()->getEntryBlock(); 634 Builder.SetInsertPoint(&*Entry.getFirstInsertionPt()); 635 return; 636 } 637 // Otherwise, this is a constant and we don't need to set a new 638 // insertion point. 639 assert(isa<Constant>(V) && "Setting insertion point for unknown value!"); 640 } 641 642 /// Returns a re-written value of Start as an indexed GEP using Base as a 643 /// pointer. 644 static Value *rewriteGEPAsOffset(Value *Start, Value *Base, 645 const DataLayout &DL, 646 SetVector<Value *> &Explored) { 647 // Perform all the substitutions. This is a bit tricky because we can 648 // have cycles in our use-def chains. 649 // 1. Create the PHI nodes without any incoming values. 650 // 2. Create all the other values. 651 // 3. Add the edges for the PHI nodes. 652 // 4. Emit GEPs to get the original pointers. 653 // 5. Remove the original instructions. 654 Type *IndexType = IntegerType::get( 655 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType())); 656 657 DenseMap<Value *, Value *> NewInsts; 658 NewInsts[Base] = ConstantInt::getNullValue(IndexType); 659 660 // Create the new PHI nodes, without adding any incoming values. 661 for (Value *Val : Explored) { 662 if (Val == Base) 663 continue; 664 // Create empty phi nodes. This avoids cyclic dependencies when creating 665 // the remaining instructions. 666 if (auto *PHI = dyn_cast<PHINode>(Val)) 667 NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(), 668 PHI->getName() + ".idx", PHI); 669 } 670 IRBuilder<> Builder(Base->getContext()); 671 672 // Create all the other instructions. 673 for (Value *Val : Explored) { 674 675 if (NewInsts.find(Val) != NewInsts.end()) 676 continue; 677 678 if (auto *CI = dyn_cast<CastInst>(Val)) { 679 // Don't get rid of the intermediate variable here; the store can grow 680 // the map which will invalidate the reference to the input value. 681 Value *V = NewInsts[CI->getOperand(0)]; 682 NewInsts[CI] = V; 683 continue; 684 } 685 if (auto *GEP = dyn_cast<GEPOperator>(Val)) { 686 Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)] 687 : GEP->getOperand(1); 688 setInsertionPoint(Builder, GEP); 689 // Indices might need to be sign extended. GEPs will magically do 690 // this, but we need to do it ourselves here. 691 if (Index->getType()->getScalarSizeInBits() != 692 NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) { 693 Index = Builder.CreateSExtOrTrunc( 694 Index, NewInsts[GEP->getOperand(0)]->getType(), 695 GEP->getOperand(0)->getName() + ".sext"); 696 } 697 698 auto *Op = NewInsts[GEP->getOperand(0)]; 699 if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero()) 700 NewInsts[GEP] = Index; 701 else 702 NewInsts[GEP] = Builder.CreateNSWAdd( 703 Op, Index, GEP->getOperand(0)->getName() + ".add"); 704 continue; 705 } 706 if (isa<PHINode>(Val)) 707 continue; 708 709 llvm_unreachable("Unexpected instruction type"); 710 } 711 712 // Add the incoming values to the PHI nodes. 713 for (Value *Val : Explored) { 714 if (Val == Base) 715 continue; 716 // All the instructions have been created, we can now add edges to the 717 // phi nodes. 718 if (auto *PHI = dyn_cast<PHINode>(Val)) { 719 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]); 720 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) { 721 Value *NewIncoming = PHI->getIncomingValue(I); 722 723 if (NewInsts.find(NewIncoming) != NewInsts.end()) 724 NewIncoming = NewInsts[NewIncoming]; 725 726 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I)); 727 } 728 } 729 } 730 731 for (Value *Val : Explored) { 732 if (Val == Base) 733 continue; 734 735 // Depending on the type, for external users we have to emit 736 // a GEP or a GEP + ptrtoint. 737 setInsertionPoint(Builder, Val, false); 738 739 // If required, create an inttoptr instruction for Base. 740 Value *NewBase = Base; 741 if (!Base->getType()->isPointerTy()) 742 NewBase = Builder.CreateBitOrPointerCast(Base, Start->getType(), 743 Start->getName() + "to.ptr"); 744 745 Value *GEP = Builder.CreateInBoundsGEP( 746 Start->getType()->getPointerElementType(), NewBase, 747 makeArrayRef(NewInsts[Val]), Val->getName() + ".ptr"); 748 749 if (!Val->getType()->isPointerTy()) { 750 Value *Cast = Builder.CreatePointerCast(GEP, Val->getType(), 751 Val->getName() + ".conv"); 752 GEP = Cast; 753 } 754 Val->replaceAllUsesWith(GEP); 755 } 756 757 return NewInsts[Start]; 758 } 759 760 /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express 761 /// the input Value as a constant indexed GEP. Returns a pair containing 762 /// the GEPs Pointer and Index. 763 static std::pair<Value *, Value *> 764 getAsConstantIndexedAddress(Value *V, const DataLayout &DL) { 765 Type *IndexType = IntegerType::get(V->getContext(), 766 DL.getIndexTypeSizeInBits(V->getType())); 767 768 Constant *Index = ConstantInt::getNullValue(IndexType); 769 while (true) { 770 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 771 // We accept only inbouds GEPs here to exclude the possibility of 772 // overflow. 773 if (!GEP->isInBounds()) 774 break; 775 if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 && 776 GEP->getType() == V->getType()) { 777 V = GEP->getOperand(0); 778 Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1)); 779 Index = ConstantExpr::getAdd( 780 Index, ConstantExpr::getSExtOrBitCast(GEPIndex, IndexType)); 781 continue; 782 } 783 break; 784 } 785 if (auto *CI = dyn_cast<IntToPtrInst>(V)) { 786 if (!CI->isNoopCast(DL)) 787 break; 788 V = CI->getOperand(0); 789 continue; 790 } 791 if (auto *CI = dyn_cast<PtrToIntInst>(V)) { 792 if (!CI->isNoopCast(DL)) 793 break; 794 V = CI->getOperand(0); 795 continue; 796 } 797 break; 798 } 799 return {V, Index}; 800 } 801 802 /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant. 803 /// We can look through PHIs, GEPs and casts in order to determine a common base 804 /// between GEPLHS and RHS. 805 static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, 806 ICmpInst::Predicate Cond, 807 const DataLayout &DL) { 808 // FIXME: Support vector of pointers. 809 if (GEPLHS->getType()->isVectorTy()) 810 return nullptr; 811 812 if (!GEPLHS->hasAllConstantIndices()) 813 return nullptr; 814 815 // Make sure the pointers have the same type. 816 if (GEPLHS->getType() != RHS->getType()) 817 return nullptr; 818 819 Value *PtrBase, *Index; 820 std::tie(PtrBase, Index) = getAsConstantIndexedAddress(GEPLHS, DL); 821 822 // The set of nodes that will take part in this transformation. 823 SetVector<Value *> Nodes; 824 825 if (!canRewriteGEPAsOffset(RHS, PtrBase, DL, Nodes)) 826 return nullptr; 827 828 // We know we can re-write this as 829 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) 830 // Since we've only looked through inbouds GEPs we know that we 831 // can't have overflow on either side. We can therefore re-write 832 // this as: 833 // OFFSET1 cmp OFFSET2 834 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, DL, Nodes); 835 836 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written 837 // GEP having PtrBase as the pointer base, and has returned in NewRHS the 838 // offset. Since Index is the offset of LHS to the base pointer, we will now 839 // compare the offsets instead of comparing the pointers. 840 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS); 841 } 842 843 /// Fold comparisons between a GEP instruction and something else. At this point 844 /// we know that the GEP is on the LHS of the comparison. 845 Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, 846 ICmpInst::Predicate Cond, 847 Instruction &I) { 848 // Don't transform signed compares of GEPs into index compares. Even if the 849 // GEP is inbounds, the final add of the base pointer can have signed overflow 850 // and would change the result of the icmp. 851 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be 852 // the maximum signed value for the pointer type. 853 if (ICmpInst::isSigned(Cond)) 854 return nullptr; 855 856 // Look through bitcasts and addrspacecasts. We do not however want to remove 857 // 0 GEPs. 858 if (!isa<GetElementPtrInst>(RHS)) 859 RHS = RHS->stripPointerCasts(); 860 861 Value *PtrBase = GEPLHS->getOperand(0); 862 // FIXME: Support vector pointer GEPs. 863 if (PtrBase == RHS && GEPLHS->isInBounds() && 864 !GEPLHS->getType()->isVectorTy()) { 865 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0). 866 // This transformation (ignoring the base and scales) is valid because we 867 // know pointers can't overflow since the gep is inbounds. See if we can 868 // output an optimized form. 869 Value *Offset = evaluateGEPOffsetExpression(GEPLHS, *this, DL); 870 871 // If not, synthesize the offset the hard way. 872 if (!Offset) 873 Offset = EmitGEPOffset(GEPLHS); 874 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset, 875 Constant::getNullValue(Offset->getType())); 876 } 877 878 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) && 879 isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() && 880 !NullPointerIsDefined(I.getFunction(), 881 RHS->getType()->getPointerAddressSpace())) { 882 // For most address spaces, an allocation can't be placed at null, but null 883 // itself is treated as a 0 size allocation in the in bounds rules. Thus, 884 // the only valid inbounds address derived from null, is null itself. 885 // Thus, we have four cases to consider: 886 // 1) Base == nullptr, Offset == 0 -> inbounds, null 887 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds 888 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations) 889 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison) 890 // 891 // (Note if we're indexing a type of size 0, that simply collapses into one 892 // of the buckets above.) 893 // 894 // In general, we're allowed to make values less poison (i.e. remove 895 // sources of full UB), so in this case, we just select between the two 896 // non-poison cases (1 and 4 above). 897 // 898 // For vectors, we apply the same reasoning on a per-lane basis. 899 auto *Base = GEPLHS->getPointerOperand(); 900 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) { 901 int NumElts = cast<FixedVectorType>(GEPLHS->getType())->getNumElements(); 902 Base = Builder.CreateVectorSplat(NumElts, Base); 903 } 904 return new ICmpInst(Cond, Base, 905 ConstantExpr::getPointerBitCastOrAddrSpaceCast( 906 cast<Constant>(RHS), Base->getType())); 907 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) { 908 // If the base pointers are different, but the indices are the same, just 909 // compare the base pointer. 910 if (PtrBase != GEPRHS->getOperand(0)) { 911 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands(); 912 IndicesTheSame &= GEPLHS->getOperand(0)->getType() == 913 GEPRHS->getOperand(0)->getType(); 914 if (IndicesTheSame) 915 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) 916 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 917 IndicesTheSame = false; 918 break; 919 } 920 921 // If all indices are the same, just compare the base pointers. 922 Type *BaseType = GEPLHS->getOperand(0)->getType(); 923 if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType()) 924 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0)); 925 926 // If we're comparing GEPs with two base pointers that only differ in type 927 // and both GEPs have only constant indices or just one use, then fold 928 // the compare with the adjusted indices. 929 // FIXME: Support vector of pointers. 930 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() && 931 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) && 932 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) && 933 PtrBase->stripPointerCasts() == 934 GEPRHS->getOperand(0)->stripPointerCasts() && 935 !GEPLHS->getType()->isVectorTy()) { 936 Value *LOffset = EmitGEPOffset(GEPLHS); 937 Value *ROffset = EmitGEPOffset(GEPRHS); 938 939 // If we looked through an addrspacecast between different sized address 940 // spaces, the LHS and RHS pointers are different sized 941 // integers. Truncate to the smaller one. 942 Type *LHSIndexTy = LOffset->getType(); 943 Type *RHSIndexTy = ROffset->getType(); 944 if (LHSIndexTy != RHSIndexTy) { 945 if (LHSIndexTy->getPrimitiveSizeInBits() < 946 RHSIndexTy->getPrimitiveSizeInBits()) { 947 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy); 948 } else 949 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy); 950 } 951 952 Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond), 953 LOffset, ROffset); 954 return replaceInstUsesWith(I, Cmp); 955 } 956 957 // Otherwise, the base pointers are different and the indices are 958 // different. Try convert this to an indexed compare by looking through 959 // PHIs/casts. 960 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 961 } 962 963 // If one of the GEPs has all zero indices, recurse. 964 // FIXME: Handle vector of pointers. 965 if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices()) 966 return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0), 967 ICmpInst::getSwappedPredicate(Cond), I); 968 969 // If the other GEP has all zero indices, recurse. 970 // FIXME: Handle vector of pointers. 971 if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices()) 972 return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I); 973 974 bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds(); 975 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) { 976 // If the GEPs only differ by one index, compare it. 977 unsigned NumDifferences = 0; // Keep track of # differences. 978 unsigned DiffOperand = 0; // The operand that differs. 979 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i) 980 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) { 981 Type *LHSType = GEPLHS->getOperand(i)->getType(); 982 Type *RHSType = GEPRHS->getOperand(i)->getType(); 983 // FIXME: Better support for vector of pointers. 984 if (LHSType->getPrimitiveSizeInBits() != 985 RHSType->getPrimitiveSizeInBits() || 986 (GEPLHS->getType()->isVectorTy() && 987 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) { 988 // Irreconcilable differences. 989 NumDifferences = 2; 990 break; 991 } 992 993 if (NumDifferences++) break; 994 DiffOperand = i; 995 } 996 997 if (NumDifferences == 0) // SAME GEP? 998 return replaceInstUsesWith(I, // No comparison is needed here. 999 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond))); 1000 1001 else if (NumDifferences == 1 && GEPsInBounds) { 1002 Value *LHSV = GEPLHS->getOperand(DiffOperand); 1003 Value *RHSV = GEPRHS->getOperand(DiffOperand); 1004 // Make sure we do a signed comparison here. 1005 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV); 1006 } 1007 } 1008 1009 // Only lower this if the icmp is the only user of the GEP or if we expect 1010 // the result to fold to a constant! 1011 if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) && 1012 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) { 1013 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2) 1014 Value *L = EmitGEPOffset(GEPLHS); 1015 Value *R = EmitGEPOffset(GEPRHS); 1016 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R); 1017 } 1018 } 1019 1020 // Try convert this to an indexed compare by looking through PHIs/casts as a 1021 // last resort. 1022 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL); 1023 } 1024 1025 Instruction *InstCombinerImpl::foldAllocaCmp(ICmpInst &ICI, 1026 const AllocaInst *Alloca, 1027 const Value *Other) { 1028 assert(ICI.isEquality() && "Cannot fold non-equality comparison."); 1029 1030 // It would be tempting to fold away comparisons between allocas and any 1031 // pointer not based on that alloca (e.g. an argument). However, even 1032 // though such pointers cannot alias, they can still compare equal. 1033 // 1034 // But LLVM doesn't specify where allocas get their memory, so if the alloca 1035 // doesn't escape we can argue that it's impossible to guess its value, and we 1036 // can therefore act as if any such guesses are wrong. 1037 // 1038 // The code below checks that the alloca doesn't escape, and that it's only 1039 // used in a comparison once (the current instruction). The 1040 // single-comparison-use condition ensures that we're trivially folding all 1041 // comparisons against the alloca consistently, and avoids the risk of 1042 // erroneously folding a comparison of the pointer with itself. 1043 1044 unsigned MaxIter = 32; // Break cycles and bound to constant-time. 1045 1046 SmallVector<const Use *, 32> Worklist; 1047 for (const Use &U : Alloca->uses()) { 1048 if (Worklist.size() >= MaxIter) 1049 return nullptr; 1050 Worklist.push_back(&U); 1051 } 1052 1053 unsigned NumCmps = 0; 1054 while (!Worklist.empty()) { 1055 assert(Worklist.size() <= MaxIter); 1056 const Use *U = Worklist.pop_back_val(); 1057 const Value *V = U->getUser(); 1058 --MaxIter; 1059 1060 if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) || 1061 isa<SelectInst>(V)) { 1062 // Track the uses. 1063 } else if (isa<LoadInst>(V)) { 1064 // Loading from the pointer doesn't escape it. 1065 continue; 1066 } else if (const auto *SI = dyn_cast<StoreInst>(V)) { 1067 // Storing *to* the pointer is fine, but storing the pointer escapes it. 1068 if (SI->getValueOperand() == U->get()) 1069 return nullptr; 1070 continue; 1071 } else if (isa<ICmpInst>(V)) { 1072 if (NumCmps++) 1073 return nullptr; // Found more than one cmp. 1074 continue; 1075 } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) { 1076 switch (Intrin->getIntrinsicID()) { 1077 // These intrinsics don't escape or compare the pointer. Memset is safe 1078 // because we don't allow ptrtoint. Memcpy and memmove are safe because 1079 // we don't allow stores, so src cannot point to V. 1080 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: 1081 case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset: 1082 continue; 1083 default: 1084 return nullptr; 1085 } 1086 } else { 1087 return nullptr; 1088 } 1089 for (const Use &U : V->uses()) { 1090 if (Worklist.size() >= MaxIter) 1091 return nullptr; 1092 Worklist.push_back(&U); 1093 } 1094 } 1095 1096 Type *CmpTy = CmpInst::makeCmpResultType(Other->getType()); 1097 return replaceInstUsesWith( 1098 ICI, 1099 ConstantInt::get(CmpTy, !CmpInst::isTrueWhenEqual(ICI.getPredicate()))); 1100 } 1101 1102 /// Fold "icmp pred (X+C), X". 1103 Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C, 1104 ICmpInst::Predicate Pred) { 1105 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0, 1106 // so the values can never be equal. Similarly for all other "or equals" 1107 // operators. 1108 assert(!!C && "C should not be zero!"); 1109 1110 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255 1111 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253 1112 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0 1113 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) { 1114 Constant *R = ConstantInt::get(X->getType(), 1115 APInt::getMaxValue(C.getBitWidth()) - C); 1116 return new ICmpInst(ICmpInst::ICMP_UGT, X, R); 1117 } 1118 1119 // (X+1) >u X --> X <u (0-1) --> X != 255 1120 // (X+2) >u X --> X <u (0-2) --> X <u 254 1121 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0 1122 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) 1123 return new ICmpInst(ICmpInst::ICMP_ULT, X, 1124 ConstantInt::get(X->getType(), -C)); 1125 1126 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth()); 1127 1128 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127 1129 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125 1130 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0 1131 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1 1132 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126 1133 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127 1134 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 1135 return new ICmpInst(ICmpInst::ICMP_SGT, X, 1136 ConstantInt::get(X->getType(), SMax - C)); 1137 1138 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127 1139 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126 1140 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1 1141 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2 1142 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126 1143 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128 1144 1145 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE); 1146 return new ICmpInst(ICmpInst::ICMP_SLT, X, 1147 ConstantInt::get(X->getType(), SMax - (C - 1))); 1148 } 1149 1150 /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> 1151 /// (icmp eq/ne A, Log2(AP2/AP1)) -> 1152 /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)). 1153 Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A, 1154 const APInt &AP1, 1155 const APInt &AP2) { 1156 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1157 1158 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1159 if (I.getPredicate() == I.ICMP_NE) 1160 Pred = CmpInst::getInversePredicate(Pred); 1161 return new ICmpInst(Pred, LHS, RHS); 1162 }; 1163 1164 // Don't bother doing any work for cases which InstSimplify handles. 1165 if (AP2.isNullValue()) 1166 return nullptr; 1167 1168 bool IsAShr = isa<AShrOperator>(I.getOperand(0)); 1169 if (IsAShr) { 1170 if (AP2.isAllOnesValue()) 1171 return nullptr; 1172 if (AP2.isNegative() != AP1.isNegative()) 1173 return nullptr; 1174 if (AP2.sgt(AP1)) 1175 return nullptr; 1176 } 1177 1178 if (!AP1) 1179 // 'A' must be large enough to shift out the highest set bit. 1180 return getICmp(I.ICMP_UGT, A, 1181 ConstantInt::get(A->getType(), AP2.logBase2())); 1182 1183 if (AP1 == AP2) 1184 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1185 1186 int Shift; 1187 if (IsAShr && AP1.isNegative()) 1188 Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes(); 1189 else 1190 Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros(); 1191 1192 if (Shift > 0) { 1193 if (IsAShr && AP1 == AP2.ashr(Shift)) { 1194 // There are multiple solutions if we are comparing against -1 and the LHS 1195 // of the ashr is not a power of two. 1196 if (AP1.isAllOnesValue() && !AP2.isPowerOf2()) 1197 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift)); 1198 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1199 } else if (AP1 == AP2.lshr(Shift)) { 1200 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1201 } 1202 } 1203 1204 // Shifting const2 will never be equal to const1. 1205 // FIXME: This should always be handled by InstSimplify? 1206 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1207 return replaceInstUsesWith(I, TorF); 1208 } 1209 1210 /// Handle "(icmp eq/ne (shl AP2, A), AP1)" -> 1211 /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)). 1212 Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A, 1213 const APInt &AP1, 1214 const APInt &AP2) { 1215 assert(I.isEquality() && "Cannot fold icmp gt/lt"); 1216 1217 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) { 1218 if (I.getPredicate() == I.ICMP_NE) 1219 Pred = CmpInst::getInversePredicate(Pred); 1220 return new ICmpInst(Pred, LHS, RHS); 1221 }; 1222 1223 // Don't bother doing any work for cases which InstSimplify handles. 1224 if (AP2.isNullValue()) 1225 return nullptr; 1226 1227 unsigned AP2TrailingZeros = AP2.countTrailingZeros(); 1228 1229 if (!AP1 && AP2TrailingZeros != 0) 1230 return getICmp( 1231 I.ICMP_UGE, A, 1232 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros)); 1233 1234 if (AP1 == AP2) 1235 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType())); 1236 1237 // Get the distance between the lowest bits that are set. 1238 int Shift = AP1.countTrailingZeros() - AP2TrailingZeros; 1239 1240 if (Shift > 0 && AP2.shl(Shift) == AP1) 1241 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift)); 1242 1243 // Shifting const2 will never be equal to const1. 1244 // FIXME: This should always be handled by InstSimplify? 1245 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE); 1246 return replaceInstUsesWith(I, TorF); 1247 } 1248 1249 /// The caller has matched a pattern of the form: 1250 /// I = icmp ugt (add (add A, B), CI2), CI1 1251 /// If this is of the form: 1252 /// sum = a + b 1253 /// if (sum+128 >u 255) 1254 /// Then replace it with llvm.sadd.with.overflow.i8. 1255 /// 1256 static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, 1257 ConstantInt *CI2, ConstantInt *CI1, 1258 InstCombinerImpl &IC) { 1259 // The transformation we're trying to do here is to transform this into an 1260 // llvm.sadd.with.overflow. To do this, we have to replace the original add 1261 // with a narrower add, and discard the add-with-constant that is part of the 1262 // range check (if we can't eliminate it, this isn't profitable). 1263 1264 // In order to eliminate the add-with-constant, the compare can be its only 1265 // use. 1266 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0)); 1267 if (!AddWithCst->hasOneUse()) 1268 return nullptr; 1269 1270 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow. 1271 if (!CI2->getValue().isPowerOf2()) 1272 return nullptr; 1273 unsigned NewWidth = CI2->getValue().countTrailingZeros(); 1274 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31) 1275 return nullptr; 1276 1277 // The width of the new add formed is 1 more than the bias. 1278 ++NewWidth; 1279 1280 // Check to see that CI1 is an all-ones value with NewWidth bits. 1281 if (CI1->getBitWidth() == NewWidth || 1282 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth)) 1283 return nullptr; 1284 1285 // This is only really a signed overflow check if the inputs have been 1286 // sign-extended; check for that condition. For example, if CI2 is 2^31 and 1287 // the operands of the add are 64 bits wide, we need at least 33 sign bits. 1288 unsigned NeededSignBits = CI1->getBitWidth() - NewWidth + 1; 1289 if (IC.ComputeNumSignBits(A, 0, &I) < NeededSignBits || 1290 IC.ComputeNumSignBits(B, 0, &I) < NeededSignBits) 1291 return nullptr; 1292 1293 // In order to replace the original add with a narrower 1294 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant 1295 // and truncates that discard the high bits of the add. Verify that this is 1296 // the case. 1297 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0)); 1298 for (User *U : OrigAdd->users()) { 1299 if (U == AddWithCst) 1300 continue; 1301 1302 // Only accept truncates for now. We would really like a nice recursive 1303 // predicate like SimplifyDemandedBits, but which goes downwards the use-def 1304 // chain to see which bits of a value are actually demanded. If the 1305 // original add had another add which was then immediately truncated, we 1306 // could still do the transformation. 1307 TruncInst *TI = dyn_cast<TruncInst>(U); 1308 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth) 1309 return nullptr; 1310 } 1311 1312 // If the pattern matches, truncate the inputs to the narrower type and 1313 // use the sadd_with_overflow intrinsic to efficiently compute both the 1314 // result and the overflow bit. 1315 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth); 1316 Function *F = Intrinsic::getDeclaration( 1317 I.getModule(), Intrinsic::sadd_with_overflow, NewType); 1318 1319 InstCombiner::BuilderTy &Builder = IC.Builder; 1320 1321 // Put the new code above the original add, in case there are any uses of the 1322 // add between the add and the compare. 1323 Builder.SetInsertPoint(OrigAdd); 1324 1325 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc"); 1326 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc"); 1327 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd"); 1328 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result"); 1329 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType()); 1330 1331 // The inner add was the result of the narrow add, zero extended to the 1332 // wider type. Replace it with the result computed by the intrinsic. 1333 IC.replaceInstUsesWith(*OrigAdd, ZExt); 1334 IC.eraseInstFromFunction(*OrigAdd); 1335 1336 // The original icmp gets replaced with the overflow value. 1337 return ExtractValueInst::Create(Call, 1, "sadd.overflow"); 1338 } 1339 1340 /// If we have: 1341 /// icmp eq/ne (urem/srem %x, %y), 0 1342 /// iff %y is a power-of-two, we can replace this with a bit test: 1343 /// icmp eq/ne (and %x, (add %y, -1)), 0 1344 Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) { 1345 // This fold is only valid for equality predicates. 1346 if (!I.isEquality()) 1347 return nullptr; 1348 ICmpInst::Predicate Pred; 1349 Value *X, *Y, *Zero; 1350 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))), 1351 m_CombineAnd(m_Zero(), m_Value(Zero))))) 1352 return nullptr; 1353 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I)) 1354 return nullptr; 1355 // This may increase instruction count, we don't enforce that Y is a constant. 1356 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType())); 1357 Value *Masked = Builder.CreateAnd(X, Mask); 1358 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero); 1359 } 1360 1361 /// Fold equality-comparison between zero and any (maybe truncated) right-shift 1362 /// by one-less-than-bitwidth into a sign test on the original value. 1363 Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) { 1364 Instruction *Val; 1365 ICmpInst::Predicate Pred; 1366 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero()))) 1367 return nullptr; 1368 1369 Value *X; 1370 Type *XTy; 1371 1372 Constant *C; 1373 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) { 1374 XTy = X->getType(); 1375 unsigned XBitWidth = XTy->getScalarSizeInBits(); 1376 if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ, 1377 APInt(XBitWidth, XBitWidth - 1)))) 1378 return nullptr; 1379 } else if (isa<BinaryOperator>(Val) && 1380 (X = reassociateShiftAmtsOfTwoSameDirectionShifts( 1381 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val), 1382 /*AnalyzeForSignBitExtraction=*/true))) { 1383 XTy = X->getType(); 1384 } else 1385 return nullptr; 1386 1387 return ICmpInst::Create(Instruction::ICmp, 1388 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE 1389 : ICmpInst::ICMP_SLT, 1390 X, ConstantInt::getNullValue(XTy)); 1391 } 1392 1393 // Handle icmp pred X, 0 1394 Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) { 1395 CmpInst::Predicate Pred = Cmp.getPredicate(); 1396 if (!match(Cmp.getOperand(1), m_Zero())) 1397 return nullptr; 1398 1399 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0) 1400 if (Pred == ICmpInst::ICMP_SGT) { 1401 Value *A, *B; 1402 SelectPatternResult SPR = matchSelectPattern(Cmp.getOperand(0), A, B); 1403 if (SPR.Flavor == SPF_SMIN) { 1404 if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT)) 1405 return new ICmpInst(Pred, B, Cmp.getOperand(1)); 1406 if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT)) 1407 return new ICmpInst(Pred, A, Cmp.getOperand(1)); 1408 } 1409 } 1410 1411 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp)) 1412 return New; 1413 1414 // Given: 1415 // icmp eq/ne (urem %x, %y), 0 1416 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem': 1417 // icmp eq/ne %x, 0 1418 Value *X, *Y; 1419 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) && 1420 ICmpInst::isEquality(Pred)) { 1421 KnownBits XKnown = computeKnownBits(X, 0, &Cmp); 1422 KnownBits YKnown = computeKnownBits(Y, 0, &Cmp); 1423 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2) 1424 return new ICmpInst(Pred, X, Cmp.getOperand(1)); 1425 } 1426 1427 return nullptr; 1428 } 1429 1430 /// Fold icmp Pred X, C. 1431 /// TODO: This code structure does not make sense. The saturating add fold 1432 /// should be moved to some other helper and extended as noted below (it is also 1433 /// possible that code has been made unnecessary - do we canonicalize IR to 1434 /// overflow/saturating intrinsics or not?). 1435 Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) { 1436 // Match the following pattern, which is a common idiom when writing 1437 // overflow-safe integer arithmetic functions. The source performs an addition 1438 // in wider type and explicitly checks for overflow using comparisons against 1439 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic. 1440 // 1441 // TODO: This could probably be generalized to handle other overflow-safe 1442 // operations if we worked out the formulas to compute the appropriate magic 1443 // constants. 1444 // 1445 // sum = a + b 1446 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8 1447 CmpInst::Predicate Pred = Cmp.getPredicate(); 1448 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1); 1449 Value *A, *B; 1450 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI 1451 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) && 1452 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2)))) 1453 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this)) 1454 return Res; 1455 1456 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...). 1457 Constant *C = dyn_cast<Constant>(Op1); 1458 if (!C) 1459 return nullptr; 1460 1461 if (auto *Phi = dyn_cast<PHINode>(Op0)) 1462 if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) { 1463 Type *Ty = Cmp.getType(); 1464 Builder.SetInsertPoint(Phi); 1465 PHINode *NewPhi = 1466 Builder.CreatePHI(Ty, Phi->getNumOperands()); 1467 for (BasicBlock *Predecessor : predecessors(Phi->getParent())) { 1468 auto *Input = 1469 cast<Constant>(Phi->getIncomingValueForBlock(Predecessor)); 1470 auto *BoolInput = ConstantExpr::getCompare(Pred, Input, C); 1471 NewPhi->addIncoming(BoolInput, Predecessor); 1472 } 1473 NewPhi->takeName(&Cmp); 1474 return replaceInstUsesWith(Cmp, NewPhi); 1475 } 1476 1477 return nullptr; 1478 } 1479 1480 /// Canonicalize icmp instructions based on dominating conditions. 1481 Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) { 1482 // This is a cheap/incomplete check for dominance - just match a single 1483 // predecessor with a conditional branch. 1484 BasicBlock *CmpBB = Cmp.getParent(); 1485 BasicBlock *DomBB = CmpBB->getSinglePredecessor(); 1486 if (!DomBB) 1487 return nullptr; 1488 1489 Value *DomCond; 1490 BasicBlock *TrueBB, *FalseBB; 1491 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB))) 1492 return nullptr; 1493 1494 assert((TrueBB == CmpBB || FalseBB == CmpBB) && 1495 "Predecessor block does not point to successor?"); 1496 1497 // The branch should get simplified. Don't bother simplifying this condition. 1498 if (TrueBB == FalseBB) 1499 return nullptr; 1500 1501 // Try to simplify this compare to T/F based on the dominating condition. 1502 Optional<bool> Imp = isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB); 1503 if (Imp) 1504 return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp)); 1505 1506 CmpInst::Predicate Pred = Cmp.getPredicate(); 1507 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1); 1508 ICmpInst::Predicate DomPred; 1509 const APInt *C, *DomC; 1510 if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) && 1511 match(Y, m_APInt(C))) { 1512 // We have 2 compares of a variable with constants. Calculate the constant 1513 // ranges of those compares to see if we can transform the 2nd compare: 1514 // DomBB: 1515 // DomCond = icmp DomPred X, DomC 1516 // br DomCond, CmpBB, FalseBB 1517 // CmpBB: 1518 // Cmp = icmp Pred X, C 1519 ConstantRange CR = ConstantRange::makeAllowedICmpRegion(Pred, *C); 1520 ConstantRange DominatingCR = 1521 (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC) 1522 : ConstantRange::makeExactICmpRegion( 1523 CmpInst::getInversePredicate(DomPred), *DomC); 1524 ConstantRange Intersection = DominatingCR.intersectWith(CR); 1525 ConstantRange Difference = DominatingCR.difference(CR); 1526 if (Intersection.isEmptySet()) 1527 return replaceInstUsesWith(Cmp, Builder.getFalse()); 1528 if (Difference.isEmptySet()) 1529 return replaceInstUsesWith(Cmp, Builder.getTrue()); 1530 1531 // Canonicalizing a sign bit comparison that gets used in a branch, 1532 // pessimizes codegen by generating branch on zero instruction instead 1533 // of a test and branch. So we avoid canonicalizing in such situations 1534 // because test and branch instruction has better branch displacement 1535 // than compare and branch instruction. 1536 bool UnusedBit; 1537 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit); 1538 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp))) 1539 return nullptr; 1540 1541 if (const APInt *EqC = Intersection.getSingleElement()) 1542 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC)); 1543 if (const APInt *NeC = Difference.getSingleElement()) 1544 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC)); 1545 } 1546 1547 return nullptr; 1548 } 1549 1550 /// Fold icmp (trunc X, Y), C. 1551 Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp, 1552 TruncInst *Trunc, 1553 const APInt &C) { 1554 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1555 Value *X = Trunc->getOperand(0); 1556 if (C.isOneValue() && C.getBitWidth() > 1) { 1557 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1 1558 Value *V = nullptr; 1559 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V)))) 1560 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1561 ConstantInt::get(V->getType(), 1)); 1562 } 1563 1564 if (Cmp.isEquality() && Trunc->hasOneUse()) { 1565 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all 1566 // of the high bits truncated out of x are known. 1567 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(), 1568 SrcBits = X->getType()->getScalarSizeInBits(); 1569 KnownBits Known = computeKnownBits(X, 0, &Cmp); 1570 1571 // If all the high bits are known, we can do this xform. 1572 if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) { 1573 // Pull in the high bits from known-ones set. 1574 APInt NewRHS = C.zext(SrcBits); 1575 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits); 1576 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), NewRHS)); 1577 } 1578 } 1579 1580 return nullptr; 1581 } 1582 1583 /// Fold icmp (xor X, Y), C. 1584 Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp, 1585 BinaryOperator *Xor, 1586 const APInt &C) { 1587 Value *X = Xor->getOperand(0); 1588 Value *Y = Xor->getOperand(1); 1589 const APInt *XorC; 1590 if (!match(Y, m_APInt(XorC))) 1591 return nullptr; 1592 1593 // If this is a comparison that tests the signbit (X < 0) or (x > -1), 1594 // fold the xor. 1595 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1596 bool TrueIfSigned = false; 1597 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) { 1598 1599 // If the sign bit of the XorCst is not set, there is no change to 1600 // the operation, just stop using the Xor. 1601 if (!XorC->isNegative()) 1602 return replaceOperand(Cmp, 0, X); 1603 1604 // Emit the opposite comparison. 1605 if (TrueIfSigned) 1606 return new ICmpInst(ICmpInst::ICMP_SGT, X, 1607 ConstantInt::getAllOnesValue(X->getType())); 1608 else 1609 return new ICmpInst(ICmpInst::ICMP_SLT, X, 1610 ConstantInt::getNullValue(X->getType())); 1611 } 1612 1613 if (Xor->hasOneUse()) { 1614 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask)) 1615 if (!Cmp.isEquality() && XorC->isSignMask()) { 1616 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() 1617 : Cmp.getSignedPredicate(); 1618 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC)); 1619 } 1620 1621 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask)) 1622 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) { 1623 Pred = Cmp.isSigned() ? Cmp.getUnsignedPredicate() 1624 : Cmp.getSignedPredicate(); 1625 Pred = Cmp.getSwappedPredicate(Pred); 1626 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC)); 1627 } 1628 } 1629 1630 // Mask constant magic can eliminate an 'xor' with unsigned compares. 1631 if (Pred == ICmpInst::ICMP_UGT) { 1632 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2) 1633 if (*XorC == ~C && (C + 1).isPowerOf2()) 1634 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 1635 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2) 1636 if (*XorC == C && (C + 1).isPowerOf2()) 1637 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 1638 } 1639 if (Pred == ICmpInst::ICMP_ULT) { 1640 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2) 1641 if (*XorC == -C && C.isPowerOf2()) 1642 return new ICmpInst(ICmpInst::ICMP_UGT, X, 1643 ConstantInt::get(X->getType(), ~C)); 1644 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2) 1645 if (*XorC == C && (-C).isPowerOf2()) 1646 return new ICmpInst(ICmpInst::ICMP_UGT, X, 1647 ConstantInt::get(X->getType(), ~C)); 1648 } 1649 return nullptr; 1650 } 1651 1652 /// Fold icmp (and (sh X, Y), C2), C1. 1653 Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp, 1654 BinaryOperator *And, 1655 const APInt &C1, 1656 const APInt &C2) { 1657 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0)); 1658 if (!Shift || !Shift->isShift()) 1659 return nullptr; 1660 1661 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could 1662 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in 1663 // code produced by the clang front-end, for bitfield access. 1664 // This seemingly simple opportunity to fold away a shift turns out to be 1665 // rather complicated. See PR17827 for details. 1666 unsigned ShiftOpcode = Shift->getOpcode(); 1667 bool IsShl = ShiftOpcode == Instruction::Shl; 1668 const APInt *C3; 1669 if (match(Shift->getOperand(1), m_APInt(C3))) { 1670 APInt NewAndCst, NewCmpCst; 1671 bool AnyCmpCstBitsShiftedOut; 1672 if (ShiftOpcode == Instruction::Shl) { 1673 // For a left shift, we can fold if the comparison is not signed. We can 1674 // also fold a signed comparison if the mask value and comparison value 1675 // are not negative. These constraints may not be obvious, but we can 1676 // prove that they are correct using an SMT solver. 1677 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative())) 1678 return nullptr; 1679 1680 NewCmpCst = C1.lshr(*C3); 1681 NewAndCst = C2.lshr(*C3); 1682 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1; 1683 } else if (ShiftOpcode == Instruction::LShr) { 1684 // For a logical right shift, we can fold if the comparison is not signed. 1685 // We can also fold a signed comparison if the shifted mask value and the 1686 // shifted comparison value are not negative. These constraints may not be 1687 // obvious, but we can prove that they are correct using an SMT solver. 1688 NewCmpCst = C1.shl(*C3); 1689 NewAndCst = C2.shl(*C3); 1690 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1; 1691 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative())) 1692 return nullptr; 1693 } else { 1694 // For an arithmetic shift, check that both constants don't use (in a 1695 // signed sense) the top bits being shifted out. 1696 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode"); 1697 NewCmpCst = C1.shl(*C3); 1698 NewAndCst = C2.shl(*C3); 1699 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1; 1700 if (NewAndCst.ashr(*C3) != C2) 1701 return nullptr; 1702 } 1703 1704 if (AnyCmpCstBitsShiftedOut) { 1705 // If we shifted bits out, the fold is not going to work out. As a 1706 // special case, check to see if this means that the result is always 1707 // true or false now. 1708 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ) 1709 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType())); 1710 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1711 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType())); 1712 } else { 1713 Value *NewAnd = Builder.CreateAnd( 1714 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst)); 1715 return new ICmpInst(Cmp.getPredicate(), 1716 NewAnd, ConstantInt::get(And->getType(), NewCmpCst)); 1717 } 1718 } 1719 1720 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is 1721 // preferable because it allows the C2 << Y expression to be hoisted out of a 1722 // loop if Y is invariant and X is not. 1723 if (Shift->hasOneUse() && C1.isNullValue() && Cmp.isEquality() && 1724 !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) { 1725 // Compute C2 << Y. 1726 Value *NewShift = 1727 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1)) 1728 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1)); 1729 1730 // Compute X & (C2 << Y). 1731 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift); 1732 return replaceOperand(Cmp, 0, NewAnd); 1733 } 1734 1735 return nullptr; 1736 } 1737 1738 /// Fold icmp (and X, C2), C1. 1739 Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp, 1740 BinaryOperator *And, 1741 const APInt &C1) { 1742 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE; 1743 1744 // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1 1745 // TODO: We canonicalize to the longer form for scalars because we have 1746 // better analysis/folds for icmp, and codegen may be better with icmp. 1747 if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isNullValue() && 1748 match(And->getOperand(1), m_One())) 1749 return new TruncInst(And->getOperand(0), Cmp.getType()); 1750 1751 const APInt *C2; 1752 Value *X; 1753 if (!match(And, m_And(m_Value(X), m_APInt(C2)))) 1754 return nullptr; 1755 1756 // Don't perform the following transforms if the AND has multiple uses 1757 if (!And->hasOneUse()) 1758 return nullptr; 1759 1760 if (Cmp.isEquality() && C1.isNullValue()) { 1761 // Restrict this fold to single-use 'and' (PR10267). 1762 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0 1763 if (C2->isSignMask()) { 1764 Constant *Zero = Constant::getNullValue(X->getType()); 1765 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE; 1766 return new ICmpInst(NewPred, X, Zero); 1767 } 1768 1769 // Restrict this fold only for single-use 'and' (PR10267). 1770 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two. 1771 if ((~(*C2) + 1).isPowerOf2()) { 1772 Constant *NegBOC = 1773 ConstantExpr::getNeg(cast<Constant>(And->getOperand(1))); 1774 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 1775 return new ICmpInst(NewPred, X, NegBOC); 1776 } 1777 } 1778 1779 // If the LHS is an 'and' of a truncate and we can widen the and/compare to 1780 // the input width without changing the value produced, eliminate the cast: 1781 // 1782 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1' 1783 // 1784 // We can do this transformation if the constants do not have their sign bits 1785 // set or if it is an equality comparison. Extending a relational comparison 1786 // when we're checking the sign bit would not work. 1787 Value *W; 1788 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) && 1789 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) { 1790 // TODO: Is this a good transform for vectors? Wider types may reduce 1791 // throughput. Should this transform be limited (even for scalars) by using 1792 // shouldChangeType()? 1793 if (!Cmp.getType()->isVectorTy()) { 1794 Type *WideType = W->getType(); 1795 unsigned WideScalarBits = WideType->getScalarSizeInBits(); 1796 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits)); 1797 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits)); 1798 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName()); 1799 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1); 1800 } 1801 } 1802 1803 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2)) 1804 return I; 1805 1806 // (icmp pred (and (or (lshr A, B), A), 1), 0) --> 1807 // (icmp pred (and A, (or (shl 1, B), 1), 0)) 1808 // 1809 // iff pred isn't signed 1810 if (!Cmp.isSigned() && C1.isNullValue() && And->getOperand(0)->hasOneUse() && 1811 match(And->getOperand(1), m_One())) { 1812 Constant *One = cast<Constant>(And->getOperand(1)); 1813 Value *Or = And->getOperand(0); 1814 Value *A, *B, *LShr; 1815 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) && 1816 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) { 1817 unsigned UsesRemoved = 0; 1818 if (And->hasOneUse()) 1819 ++UsesRemoved; 1820 if (Or->hasOneUse()) 1821 ++UsesRemoved; 1822 if (LShr->hasOneUse()) 1823 ++UsesRemoved; 1824 1825 // Compute A & ((1 << B) | 1) 1826 Value *NewOr = nullptr; 1827 if (auto *C = dyn_cast<Constant>(B)) { 1828 if (UsesRemoved >= 1) 1829 NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One); 1830 } else { 1831 if (UsesRemoved >= 3) 1832 NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(), 1833 /*HasNUW=*/true), 1834 One, Or->getName()); 1835 } 1836 if (NewOr) { 1837 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName()); 1838 return replaceOperand(Cmp, 0, NewAnd); 1839 } 1840 } 1841 } 1842 1843 return nullptr; 1844 } 1845 1846 /// Fold icmp (and X, Y), C. 1847 Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp, 1848 BinaryOperator *And, 1849 const APInt &C) { 1850 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C)) 1851 return I; 1852 1853 // TODO: These all require that Y is constant too, so refactor with the above. 1854 1855 // Try to optimize things like "A[i] & 42 == 0" to index computations. 1856 Value *X = And->getOperand(0); 1857 Value *Y = And->getOperand(1); 1858 if (auto *LI = dyn_cast<LoadInst>(X)) 1859 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) 1860 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 1861 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 1862 !LI->isVolatile() && isa<ConstantInt>(Y)) { 1863 ConstantInt *C2 = cast<ConstantInt>(Y); 1864 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, Cmp, C2)) 1865 return Res; 1866 } 1867 1868 if (!Cmp.isEquality()) 1869 return nullptr; 1870 1871 // X & -C == -C -> X > u ~C 1872 // X & -C != -C -> X <= u ~C 1873 // iff C is a power of 2 1874 if (Cmp.getOperand(1) == Y && (-C).isPowerOf2()) { 1875 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT 1876 : CmpInst::ICMP_ULE; 1877 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1)))); 1878 } 1879 1880 // (X & C2) == 0 -> (trunc X) >= 0 1881 // (X & C2) != 0 -> (trunc X) < 0 1882 // iff C2 is a power of 2 and it masks the sign bit of a legal integer type. 1883 const APInt *C2; 1884 if (And->hasOneUse() && C.isNullValue() && match(Y, m_APInt(C2))) { 1885 int32_t ExactLogBase2 = C2->exactLogBase2(); 1886 if (ExactLogBase2 != -1 && DL.isLegalInteger(ExactLogBase2 + 1)) { 1887 Type *NTy = IntegerType::get(Cmp.getContext(), ExactLogBase2 + 1); 1888 if (auto *AndVTy = dyn_cast<VectorType>(And->getType())) 1889 NTy = FixedVectorType::get( 1890 NTy, cast<FixedVectorType>(AndVTy)->getNumElements()); 1891 Value *Trunc = Builder.CreateTrunc(X, NTy); 1892 auto NewPred = Cmp.getPredicate() == CmpInst::ICMP_EQ ? CmpInst::ICMP_SGE 1893 : CmpInst::ICMP_SLT; 1894 return new ICmpInst(NewPred, Trunc, Constant::getNullValue(NTy)); 1895 } 1896 } 1897 1898 return nullptr; 1899 } 1900 1901 /// Fold icmp (or X, Y), C. 1902 Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp, 1903 BinaryOperator *Or, 1904 const APInt &C) { 1905 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1906 if (C.isOneValue()) { 1907 // icmp slt signum(V) 1 --> icmp slt V, 1 1908 Value *V = nullptr; 1909 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V)))) 1910 return new ICmpInst(ICmpInst::ICMP_SLT, V, 1911 ConstantInt::get(V->getType(), 1)); 1912 } 1913 1914 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1); 1915 const APInt *MaskC; 1916 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) { 1917 if (*MaskC == C && (C + 1).isPowerOf2()) { 1918 // X | C == C --> X <=u C 1919 // X | C != C --> X >u C 1920 // iff C+1 is a power of 2 (C is a bitmask of the low bits) 1921 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT; 1922 return new ICmpInst(Pred, OrOp0, OrOp1); 1923 } 1924 1925 // More general: canonicalize 'equality with set bits mask' to 1926 // 'equality with clear bits mask'. 1927 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC 1928 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC 1929 if (Or->hasOneUse()) { 1930 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC)); 1931 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC)); 1932 return new ICmpInst(Pred, And, NewC); 1933 } 1934 } 1935 1936 if (!Cmp.isEquality() || !C.isNullValue() || !Or->hasOneUse()) 1937 return nullptr; 1938 1939 Value *P, *Q; 1940 if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) { 1941 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0 1942 // -> and (icmp eq P, null), (icmp eq Q, null). 1943 Value *CmpP = 1944 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType())); 1945 Value *CmpQ = 1946 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType())); 1947 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1948 return BinaryOperator::Create(BOpc, CmpP, CmpQ); 1949 } 1950 1951 // Are we using xors to bitwise check for a pair of (in)equalities? Convert to 1952 // a shorter form that has more potential to be folded even further. 1953 Value *X1, *X2, *X3, *X4; 1954 if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) && 1955 match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) { 1956 // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4) 1957 // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4) 1958 Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2); 1959 Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4); 1960 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; 1961 return BinaryOperator::Create(BOpc, Cmp12, Cmp34); 1962 } 1963 1964 return nullptr; 1965 } 1966 1967 /// Fold icmp (mul X, Y), C. 1968 Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp, 1969 BinaryOperator *Mul, 1970 const APInt &C) { 1971 const APInt *MulC; 1972 if (!match(Mul->getOperand(1), m_APInt(MulC))) 1973 return nullptr; 1974 1975 // If this is a test of the sign bit and the multiply is sign-preserving with 1976 // a constant operand, use the multiply LHS operand instead. 1977 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1978 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) { 1979 if (MulC->isNegative()) 1980 Pred = ICmpInst::getSwappedPredicate(Pred); 1981 return new ICmpInst(Pred, Mul->getOperand(0), 1982 Constant::getNullValue(Mul->getType())); 1983 } 1984 1985 // If the multiply does not wrap, try to divide the compare constant by the 1986 // multiplication factor. 1987 if (Cmp.isEquality() && !MulC->isNullValue()) { 1988 // (mul nsw X, MulC) == C --> X == C /s MulC 1989 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isNullValue()) { 1990 Constant *NewC = ConstantInt::get(Mul->getType(), C.sdiv(*MulC)); 1991 return new ICmpInst(Pred, Mul->getOperand(0), NewC); 1992 } 1993 // (mul nuw X, MulC) == C --> X == C /u MulC 1994 if (Mul->hasNoUnsignedWrap() && C.urem(*MulC).isNullValue()) { 1995 Constant *NewC = ConstantInt::get(Mul->getType(), C.udiv(*MulC)); 1996 return new ICmpInst(Pred, Mul->getOperand(0), NewC); 1997 } 1998 } 1999 2000 return nullptr; 2001 } 2002 2003 /// Fold icmp (shl 1, Y), C. 2004 static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl, 2005 const APInt &C) { 2006 Value *Y; 2007 if (!match(Shl, m_Shl(m_One(), m_Value(Y)))) 2008 return nullptr; 2009 2010 Type *ShiftType = Shl->getType(); 2011 unsigned TypeBits = C.getBitWidth(); 2012 bool CIsPowerOf2 = C.isPowerOf2(); 2013 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2014 if (Cmp.isUnsigned()) { 2015 // (1 << Y) pred C -> Y pred Log2(C) 2016 if (!CIsPowerOf2) { 2017 // (1 << Y) < 30 -> Y <= 4 2018 // (1 << Y) <= 30 -> Y <= 4 2019 // (1 << Y) >= 30 -> Y > 4 2020 // (1 << Y) > 30 -> Y > 4 2021 if (Pred == ICmpInst::ICMP_ULT) 2022 Pred = ICmpInst::ICMP_ULE; 2023 else if (Pred == ICmpInst::ICMP_UGE) 2024 Pred = ICmpInst::ICMP_UGT; 2025 } 2026 2027 // (1 << Y) >= 2147483648 -> Y >= 31 -> Y == 31 2028 // (1 << Y) < 2147483648 -> Y < 31 -> Y != 31 2029 unsigned CLog2 = C.logBase2(); 2030 if (CLog2 == TypeBits - 1) { 2031 if (Pred == ICmpInst::ICMP_UGE) 2032 Pred = ICmpInst::ICMP_EQ; 2033 else if (Pred == ICmpInst::ICMP_ULT) 2034 Pred = ICmpInst::ICMP_NE; 2035 } 2036 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2)); 2037 } else if (Cmp.isSigned()) { 2038 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1); 2039 if (C.isAllOnesValue()) { 2040 // (1 << Y) <= -1 -> Y == 31 2041 if (Pred == ICmpInst::ICMP_SLE) 2042 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 2043 2044 // (1 << Y) > -1 -> Y != 31 2045 if (Pred == ICmpInst::ICMP_SGT) 2046 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 2047 } else if (!C) { 2048 // (1 << Y) < 0 -> Y == 31 2049 // (1 << Y) <= 0 -> Y == 31 2050 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 2051 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne); 2052 2053 // (1 << Y) >= 0 -> Y != 31 2054 // (1 << Y) > 0 -> Y != 31 2055 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) 2056 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne); 2057 } 2058 } else if (Cmp.isEquality() && CIsPowerOf2) { 2059 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, C.logBase2())); 2060 } 2061 2062 return nullptr; 2063 } 2064 2065 /// Fold icmp (shl X, Y), C. 2066 Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp, 2067 BinaryOperator *Shl, 2068 const APInt &C) { 2069 const APInt *ShiftVal; 2070 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal))) 2071 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal); 2072 2073 const APInt *ShiftAmt; 2074 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt))) 2075 return foldICmpShlOne(Cmp, Shl, C); 2076 2077 // Check that the shift amount is in range. If not, don't perform undefined 2078 // shifts. When the shift is visited, it will be simplified. 2079 unsigned TypeBits = C.getBitWidth(); 2080 if (ShiftAmt->uge(TypeBits)) 2081 return nullptr; 2082 2083 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2084 Value *X = Shl->getOperand(0); 2085 Type *ShType = Shl->getType(); 2086 2087 // NSW guarantees that we are only shifting out sign bits from the high bits, 2088 // so we can ASHR the compare constant without needing a mask and eliminate 2089 // the shift. 2090 if (Shl->hasNoSignedWrap()) { 2091 if (Pred == ICmpInst::ICMP_SGT) { 2092 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt) 2093 APInt ShiftedC = C.ashr(*ShiftAmt); 2094 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2095 } 2096 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 2097 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) { 2098 APInt ShiftedC = C.ashr(*ShiftAmt); 2099 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2100 } 2101 if (Pred == ICmpInst::ICMP_SLT) { 2102 // SLE is the same as above, but SLE is canonicalized to SLT, so convert: 2103 // (X << S) <=s C is equiv to X <=s (C >> S) for all C 2104 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX 2105 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN 2106 assert(!C.isMinSignedValue() && "Unexpected icmp slt"); 2107 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1; 2108 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2109 } 2110 // If this is a signed comparison to 0 and the shift is sign preserving, 2111 // use the shift LHS operand instead; isSignTest may change 'Pred', so only 2112 // do that if we're sure to not continue on in this function. 2113 if (isSignTest(Pred, C)) 2114 return new ICmpInst(Pred, X, Constant::getNullValue(ShType)); 2115 } 2116 2117 // NUW guarantees that we are only shifting out zero bits from the high bits, 2118 // so we can LSHR the compare constant without needing a mask and eliminate 2119 // the shift. 2120 if (Shl->hasNoUnsignedWrap()) { 2121 if (Pred == ICmpInst::ICMP_UGT) { 2122 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt) 2123 APInt ShiftedC = C.lshr(*ShiftAmt); 2124 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2125 } 2126 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) && 2127 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) { 2128 APInt ShiftedC = C.lshr(*ShiftAmt); 2129 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2130 } 2131 if (Pred == ICmpInst::ICMP_ULT) { 2132 // ULE is the same as above, but ULE is canonicalized to ULT, so convert: 2133 // (X << S) <=u C is equiv to X <=u (C >> S) for all C 2134 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u 2135 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0 2136 assert(C.ugt(0) && "ult 0 should have been eliminated"); 2137 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1; 2138 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC)); 2139 } 2140 } 2141 2142 if (Cmp.isEquality() && Shl->hasOneUse()) { 2143 // Strength-reduce the shift into an 'and'. 2144 Constant *Mask = ConstantInt::get( 2145 ShType, 2146 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue())); 2147 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask"); 2148 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt)); 2149 return new ICmpInst(Pred, And, LShrC); 2150 } 2151 2152 // Otherwise, if this is a comparison of the sign bit, simplify to and/test. 2153 bool TrueIfSigned = false; 2154 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) { 2155 // (X << 31) <s 0 --> (X & 1) != 0 2156 Constant *Mask = ConstantInt::get( 2157 ShType, 2158 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1)); 2159 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask"); 2160 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ, 2161 And, Constant::getNullValue(ShType)); 2162 } 2163 2164 // Simplify 'shl' inequality test into 'and' equality test. 2165 if (Cmp.isUnsigned() && Shl->hasOneUse()) { 2166 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0 2167 if ((C + 1).isPowerOf2() && 2168 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) { 2169 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue())); 2170 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ 2171 : ICmpInst::ICMP_NE, 2172 And, Constant::getNullValue(ShType)); 2173 } 2174 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0 2175 if (C.isPowerOf2() && 2176 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) { 2177 Value *And = 2178 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue())); 2179 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ 2180 : ICmpInst::ICMP_NE, 2181 And, Constant::getNullValue(ShType)); 2182 } 2183 } 2184 2185 // Transform (icmp pred iM (shl iM %v, N), C) 2186 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N)) 2187 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N. 2188 // This enables us to get rid of the shift in favor of a trunc that may be 2189 // free on the target. It has the additional benefit of comparing to a 2190 // smaller constant that may be more target-friendly. 2191 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1); 2192 if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt && 2193 DL.isLegalInteger(TypeBits - Amt)) { 2194 Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt); 2195 if (auto *ShVTy = dyn_cast<VectorType>(ShType)) 2196 TruncTy = FixedVectorType::get( 2197 TruncTy, cast<FixedVectorType>(ShVTy)->getNumElements()); 2198 Constant *NewC = 2199 ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt)); 2200 return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC); 2201 } 2202 2203 return nullptr; 2204 } 2205 2206 /// Fold icmp ({al}shr X, Y), C. 2207 Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp, 2208 BinaryOperator *Shr, 2209 const APInt &C) { 2210 // An exact shr only shifts out zero bits, so: 2211 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0 2212 Value *X = Shr->getOperand(0); 2213 CmpInst::Predicate Pred = Cmp.getPredicate(); 2214 if (Cmp.isEquality() && Shr->isExact() && Shr->hasOneUse() && 2215 C.isNullValue()) 2216 return new ICmpInst(Pred, X, Cmp.getOperand(1)); 2217 2218 const APInt *ShiftVal; 2219 if (Cmp.isEquality() && match(Shr->getOperand(0), m_APInt(ShiftVal))) 2220 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftVal); 2221 2222 const APInt *ShiftAmt; 2223 if (!match(Shr->getOperand(1), m_APInt(ShiftAmt))) 2224 return nullptr; 2225 2226 // Check that the shift amount is in range. If not, don't perform undefined 2227 // shifts. When the shift is visited it will be simplified. 2228 unsigned TypeBits = C.getBitWidth(); 2229 unsigned ShAmtVal = ShiftAmt->getLimitedValue(TypeBits); 2230 if (ShAmtVal >= TypeBits || ShAmtVal == 0) 2231 return nullptr; 2232 2233 bool IsAShr = Shr->getOpcode() == Instruction::AShr; 2234 bool IsExact = Shr->isExact(); 2235 Type *ShrTy = Shr->getType(); 2236 // TODO: If we could guarantee that InstSimplify would handle all of the 2237 // constant-value-based preconditions in the folds below, then we could assert 2238 // those conditions rather than checking them. This is difficult because of 2239 // undef/poison (PR34838). 2240 if (IsAShr) { 2241 if (Pred == CmpInst::ICMP_SLT || (Pred == CmpInst::ICMP_SGT && IsExact)) { 2242 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, (C << ShAmtC) 2243 // icmp sgt (ashr exact X, ShAmtC), C --> icmp sgt X, (C << ShAmtC) 2244 APInt ShiftedC = C.shl(ShAmtVal); 2245 if (ShiftedC.ashr(ShAmtVal) == C) 2246 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2247 } 2248 if (Pred == CmpInst::ICMP_SGT) { 2249 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1 2250 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2251 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() && 2252 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1)) 2253 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2254 } 2255 } else { 2256 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) { 2257 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC) 2258 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC) 2259 APInt ShiftedC = C.shl(ShAmtVal); 2260 if (ShiftedC.lshr(ShAmtVal) == C) 2261 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2262 } 2263 if (Pred == CmpInst::ICMP_UGT) { 2264 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1 2265 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1; 2266 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1)) 2267 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC)); 2268 } 2269 } 2270 2271 if (!Cmp.isEquality()) 2272 return nullptr; 2273 2274 // Handle equality comparisons of shift-by-constant. 2275 2276 // If the comparison constant changes with the shift, the comparison cannot 2277 // succeed (bits of the comparison constant cannot match the shifted value). 2278 // This should be known by InstSimplify and already be folded to true/false. 2279 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) || 2280 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) && 2281 "Expected icmp+shr simplify did not occur."); 2282 2283 // If the bits shifted out are known zero, compare the unshifted value: 2284 // (X & 4) >> 1 == 2 --> (X & 4) == 4. 2285 if (Shr->isExact()) 2286 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal)); 2287 2288 if (Shr->hasOneUse()) { 2289 // Canonicalize the shift into an 'and': 2290 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt) 2291 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal)); 2292 Constant *Mask = ConstantInt::get(ShrTy, Val); 2293 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask"); 2294 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal)); 2295 } 2296 2297 return nullptr; 2298 } 2299 2300 Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp, 2301 BinaryOperator *SRem, 2302 const APInt &C) { 2303 // Match an 'is positive' or 'is negative' comparison of remainder by a 2304 // constant power-of-2 value: 2305 // (X % pow2C) sgt/slt 0 2306 const ICmpInst::Predicate Pred = Cmp.getPredicate(); 2307 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT) 2308 return nullptr; 2309 2310 // TODO: The one-use check is standard because we do not typically want to 2311 // create longer instruction sequences, but this might be a special-case 2312 // because srem is not good for analysis or codegen. 2313 if (!SRem->hasOneUse()) 2314 return nullptr; 2315 2316 const APInt *DivisorC; 2317 if (!C.isNullValue() || !match(SRem->getOperand(1), m_Power2(DivisorC))) 2318 return nullptr; 2319 2320 // Mask off the sign bit and the modulo bits (low-bits). 2321 Type *Ty = SRem->getType(); 2322 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits()); 2323 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1)); 2324 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC); 2325 2326 // For 'is positive?' check that the sign-bit is clear and at least 1 masked 2327 // bit is set. Example: 2328 // (i8 X % 32) s> 0 --> (X & 159) s> 0 2329 if (Pred == ICmpInst::ICMP_SGT) 2330 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty)); 2331 2332 // For 'is negative?' check that the sign-bit is set and at least 1 masked 2333 // bit is set. Example: 2334 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768 2335 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask)); 2336 } 2337 2338 /// Fold icmp (udiv X, Y), C. 2339 Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp, 2340 BinaryOperator *UDiv, 2341 const APInt &C) { 2342 const APInt *C2; 2343 if (!match(UDiv->getOperand(0), m_APInt(C2))) 2344 return nullptr; 2345 2346 assert(*C2 != 0 && "udiv 0, X should have been simplified already."); 2347 2348 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1)) 2349 Value *Y = UDiv->getOperand(1); 2350 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT) { 2351 assert(!C.isMaxValue() && 2352 "icmp ugt X, UINT_MAX should have been simplified already."); 2353 return new ICmpInst(ICmpInst::ICMP_ULE, Y, 2354 ConstantInt::get(Y->getType(), C2->udiv(C + 1))); 2355 } 2356 2357 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C) 2358 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT) { 2359 assert(C != 0 && "icmp ult X, 0 should have been simplified already."); 2360 return new ICmpInst(ICmpInst::ICMP_UGT, Y, 2361 ConstantInt::get(Y->getType(), C2->udiv(C))); 2362 } 2363 2364 return nullptr; 2365 } 2366 2367 /// Fold icmp ({su}div X, Y), C. 2368 Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp, 2369 BinaryOperator *Div, 2370 const APInt &C) { 2371 // Fold: icmp pred ([us]div X, C2), C -> range test 2372 // Fold this div into the comparison, producing a range check. 2373 // Determine, based on the divide type, what the range is being 2374 // checked. If there is an overflow on the low or high side, remember 2375 // it, otherwise compute the range [low, hi) bounding the new value. 2376 // See: InsertRangeTest above for the kinds of replacements possible. 2377 const APInt *C2; 2378 if (!match(Div->getOperand(1), m_APInt(C2))) 2379 return nullptr; 2380 2381 // FIXME: If the operand types don't match the type of the divide 2382 // then don't attempt this transform. The code below doesn't have the 2383 // logic to deal with a signed divide and an unsigned compare (and 2384 // vice versa). This is because (x /s C2) <s C produces different 2385 // results than (x /s C2) <u C or (x /u C2) <s C or even 2386 // (x /u C2) <u C. Simply casting the operands and result won't 2387 // work. :( The if statement below tests that condition and bails 2388 // if it finds it. 2389 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv; 2390 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) 2391 return nullptr; 2392 2393 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with 2394 // INT_MIN will also fail if the divisor is 1. Although folds of all these 2395 // division-by-constant cases should be present, we can not assert that they 2396 // have happened before we reach this icmp instruction. 2397 if (C2->isNullValue() || C2->isOneValue() || 2398 (DivIsSigned && C2->isAllOnesValue())) 2399 return nullptr; 2400 2401 // Compute Prod = C * C2. We are essentially solving an equation of 2402 // form X / C2 = C. We solve for X by multiplying C2 and C. 2403 // By solving for X, we can turn this into a range check instead of computing 2404 // a divide. 2405 APInt Prod = C * *C2; 2406 2407 // Determine if the product overflows by seeing if the product is not equal to 2408 // the divide. Make sure we do the same kind of divide as in the LHS 2409 // instruction that we're folding. 2410 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C; 2411 2412 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2413 2414 // If the division is known to be exact, then there is no remainder from the 2415 // divide, so the covered range size is unit, otherwise it is the divisor. 2416 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2; 2417 2418 // Figure out the interval that is being checked. For example, a comparison 2419 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 2420 // Compute this interval based on the constants involved and the signedness of 2421 // the compare/divide. This computes a half-open interval, keeping track of 2422 // whether either value in the interval overflows. After analysis each 2423 // overflow variable is set to 0 if it's corresponding bound variable is valid 2424 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end. 2425 int LoOverflow = 0, HiOverflow = 0; 2426 APInt LoBound, HiBound; 2427 2428 if (!DivIsSigned) { // udiv 2429 // e.g. X/5 op 3 --> [15, 20) 2430 LoBound = Prod; 2431 HiOverflow = LoOverflow = ProdOV; 2432 if (!HiOverflow) { 2433 // If this is not an exact divide, then many values in the range collapse 2434 // to the same result value. 2435 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false); 2436 } 2437 } else if (C2->isStrictlyPositive()) { // Divisor is > 0. 2438 if (C.isNullValue()) { // (X / pos) op 0 2439 // Can't overflow. e.g. X/2 op 0 --> [-1, 2) 2440 LoBound = -(RangeSize - 1); 2441 HiBound = RangeSize; 2442 } else if (C.isStrictlyPositive()) { // (X / pos) op pos 2443 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20) 2444 HiOverflow = LoOverflow = ProdOV; 2445 if (!HiOverflow) 2446 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true); 2447 } else { // (X / pos) op neg 2448 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14) 2449 HiBound = Prod + 1; 2450 LoOverflow = HiOverflow = ProdOV ? -1 : 0; 2451 if (!LoOverflow) { 2452 APInt DivNeg = -RangeSize; 2453 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0; 2454 } 2455 } 2456 } else if (C2->isNegative()) { // Divisor is < 0. 2457 if (Div->isExact()) 2458 RangeSize.negate(); 2459 if (C.isNullValue()) { // (X / neg) op 0 2460 // e.g. X/-5 op 0 --> [-4, 5) 2461 LoBound = RangeSize + 1; 2462 HiBound = -RangeSize; 2463 if (HiBound == *C2) { // -INTMIN = INTMIN 2464 HiOverflow = 1; // [INTMIN+1, overflow) 2465 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN 2466 } 2467 } else if (C.isStrictlyPositive()) { // (X / neg) op pos 2468 // e.g. X/-5 op 3 --> [-19, -14) 2469 HiBound = Prod + 1; 2470 HiOverflow = LoOverflow = ProdOV ? -1 : 0; 2471 if (!LoOverflow) 2472 LoOverflow = addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1:0; 2473 } else { // (X / neg) op neg 2474 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20) 2475 LoOverflow = HiOverflow = ProdOV; 2476 if (!HiOverflow) 2477 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true); 2478 } 2479 2480 // Dividing by a negative swaps the condition. LT <-> GT 2481 Pred = ICmpInst::getSwappedPredicate(Pred); 2482 } 2483 2484 Value *X = Div->getOperand(0); 2485 switch (Pred) { 2486 default: llvm_unreachable("Unhandled icmp opcode!"); 2487 case ICmpInst::ICMP_EQ: 2488 if (LoOverflow && HiOverflow) 2489 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2490 if (HiOverflow) 2491 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 2492 ICmpInst::ICMP_UGE, X, 2493 ConstantInt::get(Div->getType(), LoBound)); 2494 if (LoOverflow) 2495 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 2496 ICmpInst::ICMP_ULT, X, 2497 ConstantInt::get(Div->getType(), HiBound)); 2498 return replaceInstUsesWith( 2499 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true)); 2500 case ICmpInst::ICMP_NE: 2501 if (LoOverflow && HiOverflow) 2502 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2503 if (HiOverflow) 2504 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 2505 ICmpInst::ICMP_ULT, X, 2506 ConstantInt::get(Div->getType(), LoBound)); 2507 if (LoOverflow) 2508 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 2509 ICmpInst::ICMP_UGE, X, 2510 ConstantInt::get(Div->getType(), HiBound)); 2511 return replaceInstUsesWith(Cmp, 2512 insertRangeTest(X, LoBound, HiBound, 2513 DivIsSigned, false)); 2514 case ICmpInst::ICMP_ULT: 2515 case ICmpInst::ICMP_SLT: 2516 if (LoOverflow == +1) // Low bound is greater than input range. 2517 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2518 if (LoOverflow == -1) // Low bound is less than input range. 2519 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2520 return new ICmpInst(Pred, X, ConstantInt::get(Div->getType(), LoBound)); 2521 case ICmpInst::ICMP_UGT: 2522 case ICmpInst::ICMP_SGT: 2523 if (HiOverflow == +1) // High bound greater than input range. 2524 return replaceInstUsesWith(Cmp, Builder.getFalse()); 2525 if (HiOverflow == -1) // High bound less than input range. 2526 return replaceInstUsesWith(Cmp, Builder.getTrue()); 2527 if (Pred == ICmpInst::ICMP_UGT) 2528 return new ICmpInst(ICmpInst::ICMP_UGE, X, 2529 ConstantInt::get(Div->getType(), HiBound)); 2530 return new ICmpInst(ICmpInst::ICMP_SGE, X, 2531 ConstantInt::get(Div->getType(), HiBound)); 2532 } 2533 2534 return nullptr; 2535 } 2536 2537 /// Fold icmp (sub X, Y), C. 2538 Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp, 2539 BinaryOperator *Sub, 2540 const APInt &C) { 2541 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1); 2542 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2543 const APInt *C2; 2544 APInt SubResult; 2545 2546 // icmp eq/ne (sub C, Y), C -> icmp eq/ne Y, 0 2547 if (match(X, m_APInt(C2)) && *C2 == C && Cmp.isEquality()) 2548 return new ICmpInst(Cmp.getPredicate(), Y, 2549 ConstantInt::get(Y->getType(), 0)); 2550 2551 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C) 2552 if (match(X, m_APInt(C2)) && 2553 ((Cmp.isUnsigned() && Sub->hasNoUnsignedWrap()) || 2554 (Cmp.isSigned() && Sub->hasNoSignedWrap())) && 2555 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned())) 2556 return new ICmpInst(Cmp.getSwappedPredicate(), Y, 2557 ConstantInt::get(Y->getType(), SubResult)); 2558 2559 // The following transforms are only worth it if the only user of the subtract 2560 // is the icmp. 2561 if (!Sub->hasOneUse()) 2562 return nullptr; 2563 2564 if (Sub->hasNoSignedWrap()) { 2565 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y) 2566 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnesValue()) 2567 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 2568 2569 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y) 2570 if (Pred == ICmpInst::ICMP_SGT && C.isNullValue()) 2571 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 2572 2573 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y) 2574 if (Pred == ICmpInst::ICMP_SLT && C.isNullValue()) 2575 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 2576 2577 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y) 2578 if (Pred == ICmpInst::ICMP_SLT && C.isOneValue()) 2579 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 2580 } 2581 2582 if (!match(X, m_APInt(C2))) 2583 return nullptr; 2584 2585 // C2 - Y <u C -> (Y | (C - 1)) == C2 2586 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2 2587 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && 2588 (*C2 & (C - 1)) == (C - 1)) 2589 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X); 2590 2591 // C2 - Y >u C -> (Y | C) != C2 2592 // iff C2 & C == C and C + 1 is a power of 2 2593 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C) 2594 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X); 2595 2596 return nullptr; 2597 } 2598 2599 /// Fold icmp (add X, Y), C. 2600 Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp, 2601 BinaryOperator *Add, 2602 const APInt &C) { 2603 Value *Y = Add->getOperand(1); 2604 const APInt *C2; 2605 if (Cmp.isEquality() || !match(Y, m_APInt(C2))) 2606 return nullptr; 2607 2608 // Fold icmp pred (add X, C2), C. 2609 Value *X = Add->getOperand(0); 2610 Type *Ty = Add->getType(); 2611 CmpInst::Predicate Pred = Cmp.getPredicate(); 2612 2613 // If the add does not wrap, we can always adjust the compare by subtracting 2614 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE 2615 // are canonicalized to SGT/SLT/UGT/ULT. 2616 if ((Add->hasNoSignedWrap() && 2617 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) || 2618 (Add->hasNoUnsignedWrap() && 2619 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) { 2620 bool Overflow; 2621 APInt NewC = 2622 Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow); 2623 // If there is overflow, the result must be true or false. 2624 // TODO: Can we assert there is no overflow because InstSimplify always 2625 // handles those cases? 2626 if (!Overflow) 2627 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2) 2628 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC)); 2629 } 2630 2631 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2); 2632 const APInt &Upper = CR.getUpper(); 2633 const APInt &Lower = CR.getLower(); 2634 if (Cmp.isSigned()) { 2635 if (Lower.isSignMask()) 2636 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper)); 2637 if (Upper.isSignMask()) 2638 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower)); 2639 } else { 2640 if (Lower.isMinValue()) 2641 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper)); 2642 if (Upper.isMinValue()) 2643 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower)); 2644 } 2645 2646 if (!Add->hasOneUse()) 2647 return nullptr; 2648 2649 // X+C <u C2 -> (X & -C2) == C 2650 // iff C & (C2-1) == 0 2651 // C2 is a power of 2 2652 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0) 2653 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C), 2654 ConstantExpr::getNeg(cast<Constant>(Y))); 2655 2656 // X+C >u C2 -> (X & ~C2) != C 2657 // iff C & C2 == 0 2658 // C2+1 is a power of 2 2659 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0) 2660 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C), 2661 ConstantExpr::getNeg(cast<Constant>(Y))); 2662 2663 return nullptr; 2664 } 2665 2666 bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, 2667 Value *&RHS, ConstantInt *&Less, 2668 ConstantInt *&Equal, 2669 ConstantInt *&Greater) { 2670 // TODO: Generalize this to work with other comparison idioms or ensure 2671 // they get canonicalized into this form. 2672 2673 // select i1 (a == b), 2674 // i32 Equal, 2675 // i32 (select i1 (a < b), i32 Less, i32 Greater) 2676 // where Equal, Less and Greater are placeholders for any three constants. 2677 ICmpInst::Predicate PredA; 2678 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) || 2679 !ICmpInst::isEquality(PredA)) 2680 return false; 2681 Value *EqualVal = SI->getTrueValue(); 2682 Value *UnequalVal = SI->getFalseValue(); 2683 // We still can get non-canonical predicate here, so canonicalize. 2684 if (PredA == ICmpInst::ICMP_NE) 2685 std::swap(EqualVal, UnequalVal); 2686 if (!match(EqualVal, m_ConstantInt(Equal))) 2687 return false; 2688 ICmpInst::Predicate PredB; 2689 Value *LHS2, *RHS2; 2690 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)), 2691 m_ConstantInt(Less), m_ConstantInt(Greater)))) 2692 return false; 2693 // We can get predicate mismatch here, so canonicalize if possible: 2694 // First, ensure that 'LHS' match. 2695 if (LHS2 != LHS) { 2696 // x sgt y <--> y slt x 2697 std::swap(LHS2, RHS2); 2698 PredB = ICmpInst::getSwappedPredicate(PredB); 2699 } 2700 if (LHS2 != LHS) 2701 return false; 2702 // We also need to canonicalize 'RHS'. 2703 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) { 2704 // x sgt C-1 <--> x sge C <--> not(x slt C) 2705 auto FlippedStrictness = 2706 InstCombiner::getFlippedStrictnessPredicateAndConstant( 2707 PredB, cast<Constant>(RHS2)); 2708 if (!FlippedStrictness) 2709 return false; 2710 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE && "Sanity check"); 2711 RHS2 = FlippedStrictness->second; 2712 // And kind-of perform the result swap. 2713 std::swap(Less, Greater); 2714 PredB = ICmpInst::ICMP_SLT; 2715 } 2716 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2; 2717 } 2718 2719 Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp, 2720 SelectInst *Select, 2721 ConstantInt *C) { 2722 2723 assert(C && "Cmp RHS should be a constant int!"); 2724 // If we're testing a constant value against the result of a three way 2725 // comparison, the result can be expressed directly in terms of the 2726 // original values being compared. Note: We could possibly be more 2727 // aggressive here and remove the hasOneUse test. The original select is 2728 // really likely to simplify or sink when we remove a test of the result. 2729 Value *OrigLHS, *OrigRHS; 2730 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan; 2731 if (Cmp.hasOneUse() && 2732 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal, 2733 C3GreaterThan)) { 2734 assert(C1LessThan && C2Equal && C3GreaterThan); 2735 2736 bool TrueWhenLessThan = 2737 ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C) 2738 ->isAllOnesValue(); 2739 bool TrueWhenEqual = 2740 ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C) 2741 ->isAllOnesValue(); 2742 bool TrueWhenGreaterThan = 2743 ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C) 2744 ->isAllOnesValue(); 2745 2746 // This generates the new instruction that will replace the original Cmp 2747 // Instruction. Instead of enumerating the various combinations when 2748 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus 2749 // false, we rely on chaining of ORs and future passes of InstCombine to 2750 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b). 2751 2752 // When none of the three constants satisfy the predicate for the RHS (C), 2753 // the entire original Cmp can be simplified to a false. 2754 Value *Cond = Builder.getFalse(); 2755 if (TrueWhenLessThan) 2756 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, 2757 OrigLHS, OrigRHS)); 2758 if (TrueWhenEqual) 2759 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, 2760 OrigLHS, OrigRHS)); 2761 if (TrueWhenGreaterThan) 2762 Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, 2763 OrigLHS, OrigRHS)); 2764 2765 return replaceInstUsesWith(Cmp, Cond); 2766 } 2767 return nullptr; 2768 } 2769 2770 static Instruction *foldICmpBitCast(ICmpInst &Cmp, 2771 InstCombiner::BuilderTy &Builder) { 2772 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0)); 2773 if (!Bitcast) 2774 return nullptr; 2775 2776 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2777 Value *Op1 = Cmp.getOperand(1); 2778 Value *BCSrcOp = Bitcast->getOperand(0); 2779 2780 // Make sure the bitcast doesn't change the number of vector elements. 2781 if (Bitcast->getSrcTy()->getScalarSizeInBits() == 2782 Bitcast->getDestTy()->getScalarSizeInBits()) { 2783 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast. 2784 Value *X; 2785 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) { 2786 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0 2787 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0 2788 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0 2789 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0 2790 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT || 2791 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) && 2792 match(Op1, m_Zero())) 2793 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType())); 2794 2795 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1 2796 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One())) 2797 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1)); 2798 2799 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1 2800 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes())) 2801 return new ICmpInst(Pred, X, 2802 ConstantInt::getAllOnesValue(X->getType())); 2803 } 2804 2805 // Zero-equality checks are preserved through unsigned floating-point casts: 2806 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0 2807 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0 2808 if (match(BCSrcOp, m_UIToFP(m_Value(X)))) 2809 if (Cmp.isEquality() && match(Op1, m_Zero())) 2810 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType())); 2811 2812 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate 2813 // the FP extend/truncate because that cast does not change the sign-bit. 2814 // This is true for all standard IEEE-754 types and the X86 80-bit type. 2815 // The sign-bit is always the most significant bit in those types. 2816 const APInt *C; 2817 bool TrueIfSigned; 2818 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() && 2819 InstCombiner::isSignBitCheck(Pred, *C, TrueIfSigned)) { 2820 if (match(BCSrcOp, m_FPExt(m_Value(X))) || 2821 match(BCSrcOp, m_FPTrunc(m_Value(X)))) { 2822 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0 2823 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1 2824 Type *XType = X->getType(); 2825 2826 // We can't currently handle Power style floating point operations here. 2827 if (!(XType->isPPC_FP128Ty() || BCSrcOp->getType()->isPPC_FP128Ty())) { 2828 2829 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits()); 2830 if (auto *XVTy = dyn_cast<VectorType>(XType)) 2831 NewType = FixedVectorType::get( 2832 NewType, cast<FixedVectorType>(XVTy)->getNumElements()); 2833 Value *NewBitcast = Builder.CreateBitCast(X, NewType); 2834 if (TrueIfSigned) 2835 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast, 2836 ConstantInt::getNullValue(NewType)); 2837 else 2838 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast, 2839 ConstantInt::getAllOnesValue(NewType)); 2840 } 2841 } 2842 } 2843 } 2844 2845 // Test to see if the operands of the icmp are casted versions of other 2846 // values. If the ptr->ptr cast can be stripped off both arguments, do so. 2847 if (Bitcast->getType()->isPointerTy() && 2848 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 2849 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast 2850 // so eliminate it as well. 2851 if (auto *BC2 = dyn_cast<BitCastInst>(Op1)) 2852 Op1 = BC2->getOperand(0); 2853 2854 Op1 = Builder.CreateBitCast(Op1, BCSrcOp->getType()); 2855 return new ICmpInst(Pred, BCSrcOp, Op1); 2856 } 2857 2858 // Folding: icmp <pred> iN X, C 2859 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN 2860 // and C is a splat of a K-bit pattern 2861 // and SC is a constant vector = <C', C', C', ..., C'> 2862 // Into: 2863 // %E = extractelement <M x iK> %vec, i32 C' 2864 // icmp <pred> iK %E, trunc(C) 2865 const APInt *C; 2866 if (!match(Cmp.getOperand(1), m_APInt(C)) || 2867 !Bitcast->getType()->isIntegerTy() || 2868 !Bitcast->getSrcTy()->isIntOrIntVectorTy()) 2869 return nullptr; 2870 2871 Value *Vec; 2872 ArrayRef<int> Mask; 2873 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) { 2874 // Check whether every element of Mask is the same constant 2875 if (is_splat(Mask)) { 2876 auto *VecTy = cast<VectorType>(BCSrcOp->getType()); 2877 auto *EltTy = cast<IntegerType>(VecTy->getElementType()); 2878 if (C->isSplat(EltTy->getBitWidth())) { 2879 // Fold the icmp based on the value of C 2880 // If C is M copies of an iK sized bit pattern, 2881 // then: 2882 // => %E = extractelement <N x iK> %vec, i32 Elem 2883 // icmp <pred> iK %SplatVal, <pattern> 2884 Value *Elem = Builder.getInt32(Mask[0]); 2885 Value *Extract = Builder.CreateExtractElement(Vec, Elem); 2886 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth())); 2887 return new ICmpInst(Pred, Extract, NewC); 2888 } 2889 } 2890 } 2891 return nullptr; 2892 } 2893 2894 /// Try to fold integer comparisons with a constant operand: icmp Pred X, C 2895 /// where X is some kind of instruction. 2896 Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) { 2897 const APInt *C; 2898 if (!match(Cmp.getOperand(1), m_APInt(C))) 2899 return nullptr; 2900 2901 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0))) { 2902 switch (BO->getOpcode()) { 2903 case Instruction::Xor: 2904 if (Instruction *I = foldICmpXorConstant(Cmp, BO, *C)) 2905 return I; 2906 break; 2907 case Instruction::And: 2908 if (Instruction *I = foldICmpAndConstant(Cmp, BO, *C)) 2909 return I; 2910 break; 2911 case Instruction::Or: 2912 if (Instruction *I = foldICmpOrConstant(Cmp, BO, *C)) 2913 return I; 2914 break; 2915 case Instruction::Mul: 2916 if (Instruction *I = foldICmpMulConstant(Cmp, BO, *C)) 2917 return I; 2918 break; 2919 case Instruction::Shl: 2920 if (Instruction *I = foldICmpShlConstant(Cmp, BO, *C)) 2921 return I; 2922 break; 2923 case Instruction::LShr: 2924 case Instruction::AShr: 2925 if (Instruction *I = foldICmpShrConstant(Cmp, BO, *C)) 2926 return I; 2927 break; 2928 case Instruction::SRem: 2929 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, *C)) 2930 return I; 2931 break; 2932 case Instruction::UDiv: 2933 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, *C)) 2934 return I; 2935 LLVM_FALLTHROUGH; 2936 case Instruction::SDiv: 2937 if (Instruction *I = foldICmpDivConstant(Cmp, BO, *C)) 2938 return I; 2939 break; 2940 case Instruction::Sub: 2941 if (Instruction *I = foldICmpSubConstant(Cmp, BO, *C)) 2942 return I; 2943 break; 2944 case Instruction::Add: 2945 if (Instruction *I = foldICmpAddConstant(Cmp, BO, *C)) 2946 return I; 2947 break; 2948 default: 2949 break; 2950 } 2951 // TODO: These folds could be refactored to be part of the above calls. 2952 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, *C)) 2953 return I; 2954 } 2955 2956 // Match against CmpInst LHS being instructions other than binary operators. 2957 2958 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0))) { 2959 // For now, we only support constant integers while folding the 2960 // ICMP(SELECT)) pattern. We can extend this to support vector of integers 2961 // similar to the cases handled by binary ops above. 2962 if (ConstantInt *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1))) 2963 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS)) 2964 return I; 2965 } 2966 2967 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0))) { 2968 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C)) 2969 return I; 2970 } 2971 2972 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) 2973 if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C)) 2974 return I; 2975 2976 return nullptr; 2977 } 2978 2979 /// Fold an icmp equality instruction with binary operator LHS and constant RHS: 2980 /// icmp eq/ne BO, C. 2981 Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant( 2982 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) { 2983 // TODO: Some of these folds could work with arbitrary constants, but this 2984 // function is limited to scalar and vector splat constants. 2985 if (!Cmp.isEquality()) 2986 return nullptr; 2987 2988 ICmpInst::Predicate Pred = Cmp.getPredicate(); 2989 bool isICMP_NE = Pred == ICmpInst::ICMP_NE; 2990 Constant *RHS = cast<Constant>(Cmp.getOperand(1)); 2991 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1); 2992 2993 switch (BO->getOpcode()) { 2994 case Instruction::SRem: 2995 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one. 2996 if (C.isNullValue() && BO->hasOneUse()) { 2997 const APInt *BOC; 2998 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) { 2999 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName()); 3000 return new ICmpInst(Pred, NewRem, 3001 Constant::getNullValue(BO->getType())); 3002 } 3003 } 3004 break; 3005 case Instruction::Add: { 3006 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants. 3007 if (Constant *BOC = dyn_cast<Constant>(BOp1)) { 3008 if (BO->hasOneUse()) 3009 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, BOC)); 3010 } else if (C.isNullValue()) { 3011 // Replace ((add A, B) != 0) with (A != -B) if A or B is 3012 // efficiently invertible, or if the add has just this one use. 3013 if (Value *NegVal = dyn_castNegVal(BOp1)) 3014 return new ICmpInst(Pred, BOp0, NegVal); 3015 if (Value *NegVal = dyn_castNegVal(BOp0)) 3016 return new ICmpInst(Pred, NegVal, BOp1); 3017 if (BO->hasOneUse()) { 3018 Value *Neg = Builder.CreateNeg(BOp1); 3019 Neg->takeName(BO); 3020 return new ICmpInst(Pred, BOp0, Neg); 3021 } 3022 } 3023 break; 3024 } 3025 case Instruction::Xor: 3026 if (BO->hasOneUse()) { 3027 if (Constant *BOC = dyn_cast<Constant>(BOp1)) { 3028 // For the xor case, we can xor two constants together, eliminating 3029 // the explicit xor. 3030 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC)); 3031 } else if (C.isNullValue()) { 3032 // Replace ((xor A, B) != 0) with (A != B) 3033 return new ICmpInst(Pred, BOp0, BOp1); 3034 } 3035 } 3036 break; 3037 case Instruction::Sub: 3038 if (BO->hasOneUse()) { 3039 // Only check for constant LHS here, as constant RHS will be canonicalized 3040 // to add and use the fold above. 3041 if (Constant *BOC = dyn_cast<Constant>(BOp0)) { 3042 // Replace ((sub BOC, B) != C) with (B != BOC-C). 3043 return new ICmpInst(Pred, BOp1, ConstantExpr::getSub(BOC, RHS)); 3044 } else if (C.isNullValue()) { 3045 // Replace ((sub A, B) != 0) with (A != B). 3046 return new ICmpInst(Pred, BOp0, BOp1); 3047 } 3048 } 3049 break; 3050 case Instruction::Or: { 3051 const APInt *BOC; 3052 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) { 3053 // Comparing if all bits outside of a constant mask are set? 3054 // Replace (X | C) == -1 with (X & ~C) == ~C. 3055 // This removes the -1 constant. 3056 Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1)); 3057 Value *And = Builder.CreateAnd(BOp0, NotBOC); 3058 return new ICmpInst(Pred, And, NotBOC); 3059 } 3060 break; 3061 } 3062 case Instruction::And: { 3063 const APInt *BOC; 3064 if (match(BOp1, m_APInt(BOC))) { 3065 // If we have ((X & C) == C), turn it into ((X & C) != 0). 3066 if (C == *BOC && C.isPowerOf2()) 3067 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE, 3068 BO, Constant::getNullValue(RHS->getType())); 3069 } 3070 break; 3071 } 3072 case Instruction::UDiv: 3073 if (C.isNullValue()) { 3074 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A) 3075 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; 3076 return new ICmpInst(NewPred, BOp1, BOp0); 3077 } 3078 break; 3079 default: 3080 break; 3081 } 3082 return nullptr; 3083 } 3084 3085 /// Fold an equality icmp with LLVM intrinsic and constant operand. 3086 Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant( 3087 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) { 3088 Type *Ty = II->getType(); 3089 unsigned BitWidth = C.getBitWidth(); 3090 switch (II->getIntrinsicID()) { 3091 case Intrinsic::bswap: 3092 // bswap(A) == C -> A == bswap(C) 3093 return new ICmpInst(Cmp.getPredicate(), II->getArgOperand(0), 3094 ConstantInt::get(Ty, C.byteSwap())); 3095 3096 case Intrinsic::ctlz: 3097 case Intrinsic::cttz: { 3098 // ctz(A) == bitwidth(A) -> A == 0 and likewise for != 3099 if (C == BitWidth) 3100 return new ICmpInst(Cmp.getPredicate(), II->getArgOperand(0), 3101 ConstantInt::getNullValue(Ty)); 3102 3103 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set 3104 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits. 3105 // Limit to one use to ensure we don't increase instruction count. 3106 unsigned Num = C.getLimitedValue(BitWidth); 3107 if (Num != BitWidth && II->hasOneUse()) { 3108 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz; 3109 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1) 3110 : APInt::getHighBitsSet(BitWidth, Num + 1); 3111 APInt Mask2 = IsTrailing 3112 ? APInt::getOneBitSet(BitWidth, Num) 3113 : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1); 3114 return new ICmpInst(Cmp.getPredicate(), 3115 Builder.CreateAnd(II->getArgOperand(0), Mask1), 3116 ConstantInt::get(Ty, Mask2)); 3117 } 3118 break; 3119 } 3120 3121 case Intrinsic::ctpop: { 3122 // popcount(A) == 0 -> A == 0 and likewise for != 3123 // popcount(A) == bitwidth(A) -> A == -1 and likewise for != 3124 bool IsZero = C.isNullValue(); 3125 if (IsZero || C == BitWidth) 3126 return new ICmpInst(Cmp.getPredicate(), II->getArgOperand(0), 3127 IsZero ? Constant::getNullValue(Ty) : Constant::getAllOnesValue(Ty)); 3128 3129 break; 3130 } 3131 3132 case Intrinsic::uadd_sat: { 3133 // uadd.sat(a, b) == 0 -> (a | b) == 0 3134 if (C.isNullValue()) { 3135 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1)); 3136 return new ICmpInst(Cmp.getPredicate(), Or, Constant::getNullValue(Ty)); 3137 } 3138 break; 3139 } 3140 3141 case Intrinsic::usub_sat: { 3142 // usub.sat(a, b) == 0 -> a <= b 3143 if (C.isNullValue()) { 3144 ICmpInst::Predicate NewPred = Cmp.getPredicate() == ICmpInst::ICMP_EQ 3145 ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT; 3146 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1)); 3147 } 3148 break; 3149 } 3150 default: 3151 break; 3152 } 3153 3154 return nullptr; 3155 } 3156 3157 /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C. 3158 Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp, 3159 IntrinsicInst *II, 3160 const APInt &C) { 3161 if (Cmp.isEquality()) 3162 return foldICmpEqIntrinsicWithConstant(Cmp, II, C); 3163 3164 Type *Ty = II->getType(); 3165 unsigned BitWidth = C.getBitWidth(); 3166 switch (II->getIntrinsicID()) { 3167 case Intrinsic::ctlz: { 3168 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000 3169 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) { 3170 unsigned Num = C.getLimitedValue(); 3171 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1); 3172 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT, 3173 II->getArgOperand(0), ConstantInt::get(Ty, Limit)); 3174 } 3175 3176 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111 3177 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && 3178 C.uge(1) && C.ule(BitWidth)) { 3179 unsigned Num = C.getLimitedValue(); 3180 APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num); 3181 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT, 3182 II->getArgOperand(0), ConstantInt::get(Ty, Limit)); 3183 } 3184 break; 3185 } 3186 case Intrinsic::cttz: { 3187 // Limit to one use to ensure we don't increase instruction count. 3188 if (!II->hasOneUse()) 3189 return nullptr; 3190 3191 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0 3192 if (Cmp.getPredicate() == ICmpInst::ICMP_UGT && C.ult(BitWidth)) { 3193 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1); 3194 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, 3195 Builder.CreateAnd(II->getArgOperand(0), Mask), 3196 ConstantInt::getNullValue(Ty)); 3197 } 3198 3199 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0 3200 if (Cmp.getPredicate() == ICmpInst::ICMP_ULT && 3201 C.uge(1) && C.ule(BitWidth)) { 3202 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue()); 3203 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, 3204 Builder.CreateAnd(II->getArgOperand(0), Mask), 3205 ConstantInt::getNullValue(Ty)); 3206 } 3207 break; 3208 } 3209 default: 3210 break; 3211 } 3212 3213 return nullptr; 3214 } 3215 3216 /// Handle icmp with constant (but not simple integer constant) RHS. 3217 Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) { 3218 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3219 Constant *RHSC = dyn_cast<Constant>(Op1); 3220 Instruction *LHSI = dyn_cast<Instruction>(Op0); 3221 if (!RHSC || !LHSI) 3222 return nullptr; 3223 3224 switch (LHSI->getOpcode()) { 3225 case Instruction::GetElementPtr: 3226 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null 3227 if (RHSC->isNullValue() && 3228 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices()) 3229 return new ICmpInst( 3230 I.getPredicate(), LHSI->getOperand(0), 3231 Constant::getNullValue(LHSI->getOperand(0)->getType())); 3232 break; 3233 case Instruction::PHI: 3234 // Only fold icmp into the PHI if the phi and icmp are in the same 3235 // block. If in the same block, we're encouraging jump threading. If 3236 // not, we are just pessimizing the code by making an i1 phi. 3237 if (LHSI->getParent() == I.getParent()) 3238 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI))) 3239 return NV; 3240 break; 3241 case Instruction::Select: { 3242 // If either operand of the select is a constant, we can fold the 3243 // comparison into the select arms, which will cause one to be 3244 // constant folded and the select turned into a bitwise or. 3245 Value *Op1 = nullptr, *Op2 = nullptr; 3246 ConstantInt *CI = nullptr; 3247 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) { 3248 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 3249 CI = dyn_cast<ConstantInt>(Op1); 3250 } 3251 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) { 3252 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC); 3253 CI = dyn_cast<ConstantInt>(Op2); 3254 } 3255 3256 // We only want to perform this transformation if it will not lead to 3257 // additional code. This is true if either both sides of the select 3258 // fold to a constant (in which case the icmp is replaced with a select 3259 // which will usually simplify) or this is the only user of the 3260 // select (in which case we are trading a select+icmp for a simpler 3261 // select+icmp) or all uses of the select can be replaced based on 3262 // dominance information ("Global cases"). 3263 bool Transform = false; 3264 if (Op1 && Op2) 3265 Transform = true; 3266 else if (Op1 || Op2) { 3267 // Local case 3268 if (LHSI->hasOneUse()) 3269 Transform = true; 3270 // Global cases 3271 else if (CI && !CI->isZero()) 3272 // When Op1 is constant try replacing select with second operand. 3273 // Otherwise Op2 is constant and try replacing select with first 3274 // operand. 3275 Transform = 3276 replacedSelectWithOperand(cast<SelectInst>(LHSI), &I, Op1 ? 2 : 1); 3277 } 3278 if (Transform) { 3279 if (!Op1) 3280 Op1 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(1), RHSC, 3281 I.getName()); 3282 if (!Op2) 3283 Op2 = Builder.CreateICmp(I.getPredicate(), LHSI->getOperand(2), RHSC, 3284 I.getName()); 3285 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2); 3286 } 3287 break; 3288 } 3289 case Instruction::IntToPtr: 3290 // icmp pred inttoptr(X), null -> icmp pred X, 0 3291 if (RHSC->isNullValue() && 3292 DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType()) 3293 return new ICmpInst( 3294 I.getPredicate(), LHSI->getOperand(0), 3295 Constant::getNullValue(LHSI->getOperand(0)->getType())); 3296 break; 3297 3298 case Instruction::Load: 3299 // Try to optimize things like "A[i] > 4" to index computations. 3300 if (GetElementPtrInst *GEP = 3301 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) { 3302 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 3303 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 3304 !cast<LoadInst>(LHSI)->isVolatile()) 3305 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) 3306 return Res; 3307 } 3308 break; 3309 } 3310 3311 return nullptr; 3312 } 3313 3314 /// Some comparisons can be simplified. 3315 /// In this case, we are looking for comparisons that look like 3316 /// a check for a lossy truncation. 3317 /// Folds: 3318 /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask 3319 /// Where Mask is some pattern that produces all-ones in low bits: 3320 /// (-1 >> y) 3321 /// ((-1 << y) >> y) <- non-canonical, has extra uses 3322 /// ~(-1 << y) 3323 /// ((1 << y) + (-1)) <- non-canonical, has extra uses 3324 /// The Mask can be a constant, too. 3325 /// For some predicates, the operands are commutative. 3326 /// For others, x can only be on a specific side. 3327 static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I, 3328 InstCombiner::BuilderTy &Builder) { 3329 ICmpInst::Predicate SrcPred; 3330 Value *X, *M, *Y; 3331 auto m_VariableMask = m_CombineOr( 3332 m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())), 3333 m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())), 3334 m_CombineOr(m_LShr(m_AllOnes(), m_Value()), 3335 m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y)))); 3336 auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask()); 3337 if (!match(&I, m_c_ICmp(SrcPred, 3338 m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)), 3339 m_Deferred(X)))) 3340 return nullptr; 3341 3342 ICmpInst::Predicate DstPred; 3343 switch (SrcPred) { 3344 case ICmpInst::Predicate::ICMP_EQ: 3345 // x & (-1 >> y) == x -> x u<= (-1 >> y) 3346 DstPred = ICmpInst::Predicate::ICMP_ULE; 3347 break; 3348 case ICmpInst::Predicate::ICMP_NE: 3349 // x & (-1 >> y) != x -> x u> (-1 >> y) 3350 DstPred = ICmpInst::Predicate::ICMP_UGT; 3351 break; 3352 case ICmpInst::Predicate::ICMP_ULT: 3353 // x & (-1 >> y) u< x -> x u> (-1 >> y) 3354 // x u> x & (-1 >> y) -> x u> (-1 >> y) 3355 DstPred = ICmpInst::Predicate::ICMP_UGT; 3356 break; 3357 case ICmpInst::Predicate::ICMP_UGE: 3358 // x & (-1 >> y) u>= x -> x u<= (-1 >> y) 3359 // x u<= x & (-1 >> y) -> x u<= (-1 >> y) 3360 DstPred = ICmpInst::Predicate::ICMP_ULE; 3361 break; 3362 case ICmpInst::Predicate::ICMP_SLT: 3363 // x & (-1 >> y) s< x -> x s> (-1 >> y) 3364 // x s> x & (-1 >> y) -> x s> (-1 >> y) 3365 if (!match(M, m_Constant())) // Can not do this fold with non-constant. 3366 return nullptr; 3367 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements. 3368 return nullptr; 3369 DstPred = ICmpInst::Predicate::ICMP_SGT; 3370 break; 3371 case ICmpInst::Predicate::ICMP_SGE: 3372 // x & (-1 >> y) s>= x -> x s<= (-1 >> y) 3373 // x s<= x & (-1 >> y) -> x s<= (-1 >> y) 3374 if (!match(M, m_Constant())) // Can not do this fold with non-constant. 3375 return nullptr; 3376 if (!match(M, m_NonNegative())) // Must not have any -1 vector elements. 3377 return nullptr; 3378 DstPred = ICmpInst::Predicate::ICMP_SLE; 3379 break; 3380 case ICmpInst::Predicate::ICMP_SGT: 3381 case ICmpInst::Predicate::ICMP_SLE: 3382 return nullptr; 3383 case ICmpInst::Predicate::ICMP_UGT: 3384 case ICmpInst::Predicate::ICMP_ULE: 3385 llvm_unreachable("Instsimplify took care of commut. variant"); 3386 break; 3387 default: 3388 llvm_unreachable("All possible folds are handled."); 3389 } 3390 3391 // The mask value may be a vector constant that has undefined elements. But it 3392 // may not be safe to propagate those undefs into the new compare, so replace 3393 // those elements by copying an existing, defined, and safe scalar constant. 3394 Type *OpTy = M->getType(); 3395 auto *VecC = dyn_cast<Constant>(M); 3396 if (OpTy->isVectorTy() && VecC && VecC->containsUndefElement()) { 3397 auto *OpVTy = cast<FixedVectorType>(OpTy); 3398 Constant *SafeReplacementConstant = nullptr; 3399 for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) { 3400 if (!isa<UndefValue>(VecC->getAggregateElement(i))) { 3401 SafeReplacementConstant = VecC->getAggregateElement(i); 3402 break; 3403 } 3404 } 3405 assert(SafeReplacementConstant && "Failed to find undef replacement"); 3406 M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant); 3407 } 3408 3409 return Builder.CreateICmp(DstPred, X, M); 3410 } 3411 3412 /// Some comparisons can be simplified. 3413 /// In this case, we are looking for comparisons that look like 3414 /// a check for a lossy signed truncation. 3415 /// Folds: (MaskedBits is a constant.) 3416 /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x 3417 /// Into: 3418 /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits) 3419 /// Where KeptBits = bitwidth(%x) - MaskedBits 3420 static Value * 3421 foldICmpWithTruncSignExtendedVal(ICmpInst &I, 3422 InstCombiner::BuilderTy &Builder) { 3423 ICmpInst::Predicate SrcPred; 3424 Value *X; 3425 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef. 3426 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use. 3427 if (!match(&I, m_c_ICmp(SrcPred, 3428 m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)), 3429 m_APInt(C1))), 3430 m_Deferred(X)))) 3431 return nullptr; 3432 3433 // Potential handling of non-splats: for each element: 3434 // * if both are undef, replace with constant 0. 3435 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0. 3436 // * if both are not undef, and are different, bailout. 3437 // * else, only one is undef, then pick the non-undef one. 3438 3439 // The shift amount must be equal. 3440 if (*C0 != *C1) 3441 return nullptr; 3442 const APInt &MaskedBits = *C0; 3443 assert(MaskedBits != 0 && "shift by zero should be folded away already."); 3444 3445 ICmpInst::Predicate DstPred; 3446 switch (SrcPred) { 3447 case ICmpInst::Predicate::ICMP_EQ: 3448 // ((%x << MaskedBits) a>> MaskedBits) == %x 3449 // => 3450 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits) 3451 DstPred = ICmpInst::Predicate::ICMP_ULT; 3452 break; 3453 case ICmpInst::Predicate::ICMP_NE: 3454 // ((%x << MaskedBits) a>> MaskedBits) != %x 3455 // => 3456 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits) 3457 DstPred = ICmpInst::Predicate::ICMP_UGE; 3458 break; 3459 // FIXME: are more folds possible? 3460 default: 3461 return nullptr; 3462 } 3463 3464 auto *XType = X->getType(); 3465 const unsigned XBitWidth = XType->getScalarSizeInBits(); 3466 const APInt BitWidth = APInt(XBitWidth, XBitWidth); 3467 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched"); 3468 3469 // KeptBits = bitwidth(%x) - MaskedBits 3470 const APInt KeptBits = BitWidth - MaskedBits; 3471 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable"); 3472 // ICmpCst = (1 << KeptBits) 3473 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits); 3474 assert(ICmpCst.isPowerOf2()); 3475 // AddCst = (1 << (KeptBits-1)) 3476 const APInt AddCst = ICmpCst.lshr(1); 3477 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2()); 3478 3479 // T0 = add %x, AddCst 3480 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst)); 3481 // T1 = T0 DstPred ICmpCst 3482 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst)); 3483 3484 return T1; 3485 } 3486 3487 // Given pattern: 3488 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0 3489 // we should move shifts to the same hand of 'and', i.e. rewrite as 3490 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x) 3491 // We are only interested in opposite logical shifts here. 3492 // One of the shifts can be truncated. 3493 // If we can, we want to end up creating 'lshr' shift. 3494 static Value * 3495 foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, 3496 InstCombiner::BuilderTy &Builder) { 3497 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) || 3498 !I.getOperand(0)->hasOneUse()) 3499 return nullptr; 3500 3501 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value()); 3502 3503 // Look for an 'and' of two logical shifts, one of which may be truncated. 3504 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case. 3505 Instruction *XShift, *MaybeTruncation, *YShift; 3506 if (!match( 3507 I.getOperand(0), 3508 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)), 3509 m_CombineAnd(m_TruncOrSelf(m_CombineAnd( 3510 m_AnyLogicalShift, m_Instruction(YShift))), 3511 m_Instruction(MaybeTruncation))))) 3512 return nullptr; 3513 3514 // We potentially looked past 'trunc', but only when matching YShift, 3515 // therefore YShift must have the widest type. 3516 Instruction *WidestShift = YShift; 3517 // Therefore XShift must have the shallowest type. 3518 // Or they both have identical types if there was no truncation. 3519 Instruction *NarrowestShift = XShift; 3520 3521 Type *WidestTy = WidestShift->getType(); 3522 Type *NarrowestTy = NarrowestShift->getType(); 3523 assert(NarrowestTy == I.getOperand(0)->getType() && 3524 "We did not look past any shifts while matching XShift though."); 3525 bool HadTrunc = WidestTy != I.getOperand(0)->getType(); 3526 3527 // If YShift is a 'lshr', swap the shifts around. 3528 if (match(YShift, m_LShr(m_Value(), m_Value()))) 3529 std::swap(XShift, YShift); 3530 3531 // The shifts must be in opposite directions. 3532 auto XShiftOpcode = XShift->getOpcode(); 3533 if (XShiftOpcode == YShift->getOpcode()) 3534 return nullptr; // Do not care about same-direction shifts here. 3535 3536 Value *X, *XShAmt, *Y, *YShAmt; 3537 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt)))); 3538 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt)))); 3539 3540 // If one of the values being shifted is a constant, then we will end with 3541 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not, 3542 // however, we will need to ensure that we won't increase instruction count. 3543 if (!isa<Constant>(X) && !isa<Constant>(Y)) { 3544 // At least one of the hands of the 'and' should be one-use shift. 3545 if (!match(I.getOperand(0), 3546 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value()))) 3547 return nullptr; 3548 if (HadTrunc) { 3549 // Due to the 'trunc', we will need to widen X. For that either the old 3550 // 'trunc' or the shift amt in the non-truncated shift should be one-use. 3551 if (!MaybeTruncation->hasOneUse() && 3552 !NarrowestShift->getOperand(1)->hasOneUse()) 3553 return nullptr; 3554 } 3555 } 3556 3557 // We have two shift amounts from two different shifts. The types of those 3558 // shift amounts may not match. If that's the case let's bailout now. 3559 if (XShAmt->getType() != YShAmt->getType()) 3560 return nullptr; 3561 3562 // As input, we have the following pattern: 3563 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0 3564 // We want to rewrite that as: 3565 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x) 3566 // While we know that originally (Q+K) would not overflow 3567 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of 3568 // shift amounts. so it may now overflow in smaller bitwidth. 3569 // To ensure that does not happen, we need to ensure that the total maximal 3570 // shift amount is still representable in that smaller bit width. 3571 unsigned MaximalPossibleTotalShiftAmount = 3572 (WidestTy->getScalarSizeInBits() - 1) + 3573 (NarrowestTy->getScalarSizeInBits() - 1); 3574 APInt MaximalRepresentableShiftAmount = 3575 APInt::getAllOnesValue(XShAmt->getType()->getScalarSizeInBits()); 3576 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount)) 3577 return nullptr; 3578 3579 // Can we fold (XShAmt+YShAmt) ? 3580 auto *NewShAmt = dyn_cast_or_null<Constant>( 3581 SimplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false, 3582 /*isNUW=*/false, SQ.getWithInstruction(&I))); 3583 if (!NewShAmt) 3584 return nullptr; 3585 NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy); 3586 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits(); 3587 3588 // Is the new shift amount smaller than the bit width? 3589 // FIXME: could also rely on ConstantRange. 3590 if (!match(NewShAmt, 3591 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT, 3592 APInt(WidestBitWidth, WidestBitWidth)))) 3593 return nullptr; 3594 3595 // An extra legality check is needed if we had trunc-of-lshr. 3596 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) { 3597 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ, 3598 WidestShift]() { 3599 // It isn't obvious whether it's worth it to analyze non-constants here. 3600 // Also, let's basically give up on non-splat cases, pessimizing vectors. 3601 // If *any* of these preconditions matches we can perform the fold. 3602 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy() 3603 ? NewShAmt->getSplatValue() 3604 : NewShAmt; 3605 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold. 3606 if (NewShAmtSplat && 3607 (NewShAmtSplat->isNullValue() || 3608 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1)) 3609 return true; 3610 // We consider *min* leading zeros so a single outlier 3611 // blocks the transform as opposed to allowing it. 3612 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) { 3613 KnownBits Known = computeKnownBits(C, SQ.DL); 3614 unsigned MinLeadZero = Known.countMinLeadingZeros(); 3615 // If the value being shifted has at most lowest bit set we can fold. 3616 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero; 3617 if (MaxActiveBits <= 1) 3618 return true; 3619 // Precondition: NewShAmt u<= countLeadingZeros(C) 3620 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero)) 3621 return true; 3622 } 3623 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) { 3624 KnownBits Known = computeKnownBits(C, SQ.DL); 3625 unsigned MinLeadZero = Known.countMinLeadingZeros(); 3626 // If the value being shifted has at most lowest bit set we can fold. 3627 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero; 3628 if (MaxActiveBits <= 1) 3629 return true; 3630 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C) 3631 if (NewShAmtSplat) { 3632 APInt AdjNewShAmt = 3633 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger(); 3634 if (AdjNewShAmt.ule(MinLeadZero)) 3635 return true; 3636 } 3637 } 3638 return false; // Can't tell if it's ok. 3639 }; 3640 if (!CanFold()) 3641 return nullptr; 3642 } 3643 3644 // All good, we can do this fold. 3645 X = Builder.CreateZExt(X, WidestTy); 3646 Y = Builder.CreateZExt(Y, WidestTy); 3647 // The shift is the same that was for X. 3648 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr 3649 ? Builder.CreateLShr(X, NewShAmt) 3650 : Builder.CreateShl(X, NewShAmt); 3651 Value *T1 = Builder.CreateAnd(T0, Y); 3652 return Builder.CreateICmp(I.getPredicate(), T1, 3653 Constant::getNullValue(WidestTy)); 3654 } 3655 3656 /// Fold 3657 /// (-1 u/ x) u< y 3658 /// ((x * y) u/ x) != y 3659 /// to 3660 /// @llvm.umul.with.overflow(x, y) plus extraction of overflow bit 3661 /// Note that the comparison is commutative, while inverted (u>=, ==) predicate 3662 /// will mean that we are looking for the opposite answer. 3663 Value *InstCombinerImpl::foldUnsignedMultiplicationOverflowCheck(ICmpInst &I) { 3664 ICmpInst::Predicate Pred; 3665 Value *X, *Y; 3666 Instruction *Mul; 3667 bool NeedNegation; 3668 // Look for: (-1 u/ x) u</u>= y 3669 if (!I.isEquality() && 3670 match(&I, m_c_ICmp(Pred, m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))), 3671 m_Value(Y)))) { 3672 Mul = nullptr; 3673 3674 // Are we checking that overflow does not happen, or does happen? 3675 switch (Pred) { 3676 case ICmpInst::Predicate::ICMP_ULT: 3677 NeedNegation = false; 3678 break; // OK 3679 case ICmpInst::Predicate::ICMP_UGE: 3680 NeedNegation = true; 3681 break; // OK 3682 default: 3683 return nullptr; // Wrong predicate. 3684 } 3685 } else // Look for: ((x * y) u/ x) !=/== y 3686 if (I.isEquality() && 3687 match(&I, m_c_ICmp(Pred, m_Value(Y), 3688 m_OneUse(m_UDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y), 3689 m_Value(X)), 3690 m_Instruction(Mul)), 3691 m_Deferred(X)))))) { 3692 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ; 3693 } else 3694 return nullptr; 3695 3696 BuilderTy::InsertPointGuard Guard(Builder); 3697 // If the pattern included (x * y), we'll want to insert new instructions 3698 // right before that original multiplication so that we can replace it. 3699 bool MulHadOtherUses = Mul && !Mul->hasOneUse(); 3700 if (MulHadOtherUses) 3701 Builder.SetInsertPoint(Mul); 3702 3703 Function *F = Intrinsic::getDeclaration( 3704 I.getModule(), Intrinsic::umul_with_overflow, X->getType()); 3705 CallInst *Call = Builder.CreateCall(F, {X, Y}, "umul"); 3706 3707 // If the multiplication was used elsewhere, to ensure that we don't leave 3708 // "duplicate" instructions, replace uses of that original multiplication 3709 // with the multiplication result from the with.overflow intrinsic. 3710 if (MulHadOtherUses) 3711 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "umul.val")); 3712 3713 Value *Res = Builder.CreateExtractValue(Call, 1, "umul.ov"); 3714 if (NeedNegation) // This technically increases instruction count. 3715 Res = Builder.CreateNot(Res, "umul.not.ov"); 3716 3717 // If we replaced the mul, erase it. Do this after all uses of Builder, 3718 // as the mul is used as insertion point. 3719 if (MulHadOtherUses) 3720 eraseInstFromFunction(*Mul); 3721 3722 return Res; 3723 } 3724 3725 static Instruction *foldICmpXNegX(ICmpInst &I) { 3726 CmpInst::Predicate Pred; 3727 Value *X; 3728 if (!match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) 3729 return nullptr; 3730 3731 if (ICmpInst::isSigned(Pred)) 3732 Pred = ICmpInst::getSwappedPredicate(Pred); 3733 else if (ICmpInst::isUnsigned(Pred)) 3734 Pred = ICmpInst::getSignedPredicate(Pred); 3735 // else for equality-comparisons just keep the predicate. 3736 3737 return ICmpInst::Create(Instruction::ICmp, Pred, X, 3738 Constant::getNullValue(X->getType()), I.getName()); 3739 } 3740 3741 /// Try to fold icmp (binop), X or icmp X, (binop). 3742 /// TODO: A large part of this logic is duplicated in InstSimplify's 3743 /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code 3744 /// duplication. 3745 Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I, 3746 const SimplifyQuery &SQ) { 3747 const SimplifyQuery Q = SQ.getWithInstruction(&I); 3748 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3749 3750 // Special logic for binary operators. 3751 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0); 3752 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1); 3753 if (!BO0 && !BO1) 3754 return nullptr; 3755 3756 if (Instruction *NewICmp = foldICmpXNegX(I)) 3757 return NewICmp; 3758 3759 const CmpInst::Predicate Pred = I.getPredicate(); 3760 Value *X; 3761 3762 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare. 3763 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X 3764 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) && 3765 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) 3766 return new ICmpInst(Pred, Builder.CreateNot(Op1), X); 3767 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0 3768 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) && 3769 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) 3770 return new ICmpInst(Pred, X, Builder.CreateNot(Op0)); 3771 3772 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false; 3773 if (BO0 && isa<OverflowingBinaryOperator>(BO0)) 3774 NoOp0WrapProblem = 3775 ICmpInst::isEquality(Pred) || 3776 (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) || 3777 (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap()); 3778 if (BO1 && isa<OverflowingBinaryOperator>(BO1)) 3779 NoOp1WrapProblem = 3780 ICmpInst::isEquality(Pred) || 3781 (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) || 3782 (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap()); 3783 3784 // Analyze the case when either Op0 or Op1 is an add instruction. 3785 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null). 3786 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 3787 if (BO0 && BO0->getOpcode() == Instruction::Add) { 3788 A = BO0->getOperand(0); 3789 B = BO0->getOperand(1); 3790 } 3791 if (BO1 && BO1->getOpcode() == Instruction::Add) { 3792 C = BO1->getOperand(0); 3793 D = BO1->getOperand(1); 3794 } 3795 3796 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow. 3797 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow. 3798 if ((A == Op1 || B == Op1) && NoOp0WrapProblem) 3799 return new ICmpInst(Pred, A == Op1 ? B : A, 3800 Constant::getNullValue(Op1->getType())); 3801 3802 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow. 3803 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow. 3804 if ((C == Op0 || D == Op0) && NoOp1WrapProblem) 3805 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()), 3806 C == Op0 ? D : C); 3807 3808 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow. 3809 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem && 3810 NoOp1WrapProblem) { 3811 // Determine Y and Z in the form icmp (X+Y), (X+Z). 3812 Value *Y, *Z; 3813 if (A == C) { 3814 // C + B == C + D -> B == D 3815 Y = B; 3816 Z = D; 3817 } else if (A == D) { 3818 // D + B == C + D -> B == C 3819 Y = B; 3820 Z = C; 3821 } else if (B == C) { 3822 // A + C == C + D -> A == D 3823 Y = A; 3824 Z = D; 3825 } else { 3826 assert(B == D); 3827 // A + D == C + D -> A == C 3828 Y = A; 3829 Z = C; 3830 } 3831 return new ICmpInst(Pred, Y, Z); 3832 } 3833 3834 // icmp slt (A + -1), Op1 -> icmp sle A, Op1 3835 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT && 3836 match(B, m_AllOnes())) 3837 return new ICmpInst(CmpInst::ICMP_SLE, A, Op1); 3838 3839 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1 3840 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE && 3841 match(B, m_AllOnes())) 3842 return new ICmpInst(CmpInst::ICMP_SGT, A, Op1); 3843 3844 // icmp sle (A + 1), Op1 -> icmp slt A, Op1 3845 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One())) 3846 return new ICmpInst(CmpInst::ICMP_SLT, A, Op1); 3847 3848 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1 3849 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One())) 3850 return new ICmpInst(CmpInst::ICMP_SGE, A, Op1); 3851 3852 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C 3853 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT && 3854 match(D, m_AllOnes())) 3855 return new ICmpInst(CmpInst::ICMP_SGE, Op0, C); 3856 3857 // icmp sle Op0, (C + -1) -> icmp slt Op0, C 3858 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE && 3859 match(D, m_AllOnes())) 3860 return new ICmpInst(CmpInst::ICMP_SLT, Op0, C); 3861 3862 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C 3863 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One())) 3864 return new ICmpInst(CmpInst::ICMP_SGT, Op0, C); 3865 3866 // icmp slt Op0, (C + 1) -> icmp sle Op0, C 3867 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One())) 3868 return new ICmpInst(CmpInst::ICMP_SLE, Op0, C); 3869 3870 // TODO: The subtraction-related identities shown below also hold, but 3871 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations 3872 // wouldn't happen even if they were implemented. 3873 // 3874 // icmp ult (A - 1), Op1 -> icmp ule A, Op1 3875 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1 3876 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C 3877 // icmp ule Op0, (C - 1) -> icmp ult Op0, C 3878 3879 // icmp ule (A + 1), Op0 -> icmp ult A, Op1 3880 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One())) 3881 return new ICmpInst(CmpInst::ICMP_ULT, A, Op1); 3882 3883 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1 3884 if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One())) 3885 return new ICmpInst(CmpInst::ICMP_UGE, A, Op1); 3886 3887 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C 3888 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One())) 3889 return new ICmpInst(CmpInst::ICMP_UGT, Op0, C); 3890 3891 // icmp ult Op0, (C + 1) -> icmp ule Op0, C 3892 if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One())) 3893 return new ICmpInst(CmpInst::ICMP_ULE, Op0, C); 3894 3895 // if C1 has greater magnitude than C2: 3896 // icmp (A + C1), (C + C2) -> icmp (A + C3), C 3897 // s.t. C3 = C1 - C2 3898 // 3899 // if C2 has greater magnitude than C1: 3900 // icmp (A + C1), (C + C2) -> icmp A, (C + C3) 3901 // s.t. C3 = C2 - C1 3902 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem && 3903 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) 3904 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B)) 3905 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D)) { 3906 const APInt &AP1 = C1->getValue(); 3907 const APInt &AP2 = C2->getValue(); 3908 if (AP1.isNegative() == AP2.isNegative()) { 3909 APInt AP1Abs = C1->getValue().abs(); 3910 APInt AP2Abs = C2->getValue().abs(); 3911 if (AP1Abs.uge(AP2Abs)) { 3912 ConstantInt *C3 = Builder.getInt(AP1 - AP2); 3913 Value *NewAdd = Builder.CreateNSWAdd(A, C3); 3914 return new ICmpInst(Pred, NewAdd, C); 3915 } else { 3916 ConstantInt *C3 = Builder.getInt(AP2 - AP1); 3917 Value *NewAdd = Builder.CreateNSWAdd(C, C3); 3918 return new ICmpInst(Pred, A, NewAdd); 3919 } 3920 } 3921 } 3922 3923 // Analyze the case when either Op0 or Op1 is a sub instruction. 3924 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null). 3925 A = nullptr; 3926 B = nullptr; 3927 C = nullptr; 3928 D = nullptr; 3929 if (BO0 && BO0->getOpcode() == Instruction::Sub) { 3930 A = BO0->getOperand(0); 3931 B = BO0->getOperand(1); 3932 } 3933 if (BO1 && BO1->getOpcode() == Instruction::Sub) { 3934 C = BO1->getOperand(0); 3935 D = BO1->getOperand(1); 3936 } 3937 3938 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow. 3939 if (A == Op1 && NoOp0WrapProblem) 3940 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B); 3941 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow. 3942 if (C == Op0 && NoOp1WrapProblem) 3943 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType())); 3944 3945 // Convert sub-with-unsigned-overflow comparisons into a comparison of args. 3946 // (A - B) u>/u<= A --> B u>/u<= A 3947 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) 3948 return new ICmpInst(Pred, B, A); 3949 // C u</u>= (C - D) --> C u</u>= D 3950 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) 3951 return new ICmpInst(Pred, C, D); 3952 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0 3953 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) && 3954 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 3955 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A); 3956 // C u<=/u> (C - D) --> C u</u>= D iff B != 0 3957 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) && 3958 isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 3959 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D); 3960 3961 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow. 3962 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem) 3963 return new ICmpInst(Pred, A, C); 3964 3965 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow. 3966 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem) 3967 return new ICmpInst(Pred, D, B); 3968 3969 // icmp (0-X) < cst --> x > -cst 3970 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) { 3971 Value *X; 3972 if (match(BO0, m_Neg(m_Value(X)))) 3973 if (Constant *RHSC = dyn_cast<Constant>(Op1)) 3974 if (RHSC->isNotMinSignedValue()) 3975 return new ICmpInst(I.getSwappedPredicate(), X, 3976 ConstantExpr::getNeg(RHSC)); 3977 } 3978 3979 BinaryOperator *SRem = nullptr; 3980 // icmp (srem X, Y), Y 3981 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1)) 3982 SRem = BO0; 3983 // icmp Y, (srem X, Y) 3984 else if (BO1 && BO1->getOpcode() == Instruction::SRem && 3985 Op0 == BO1->getOperand(1)) 3986 SRem = BO1; 3987 if (SRem) { 3988 // We don't check hasOneUse to avoid increasing register pressure because 3989 // the value we use is the same value this instruction was already using. 3990 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) { 3991 default: 3992 break; 3993 case ICmpInst::ICMP_EQ: 3994 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 3995 case ICmpInst::ICMP_NE: 3996 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 3997 case ICmpInst::ICMP_SGT: 3998 case ICmpInst::ICMP_SGE: 3999 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1), 4000 Constant::getAllOnesValue(SRem->getType())); 4001 case ICmpInst::ICMP_SLT: 4002 case ICmpInst::ICMP_SLE: 4003 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1), 4004 Constant::getNullValue(SRem->getType())); 4005 } 4006 } 4007 4008 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() && 4009 BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) { 4010 switch (BO0->getOpcode()) { 4011 default: 4012 break; 4013 case Instruction::Add: 4014 case Instruction::Sub: 4015 case Instruction::Xor: { 4016 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b 4017 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4018 4019 const APInt *C; 4020 if (match(BO0->getOperand(1), m_APInt(C))) { 4021 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b 4022 if (C->isSignMask()) { 4023 ICmpInst::Predicate NewPred = 4024 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); 4025 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); 4026 } 4027 4028 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b 4029 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) { 4030 ICmpInst::Predicate NewPred = 4031 I.isSigned() ? I.getUnsignedPredicate() : I.getSignedPredicate(); 4032 NewPred = I.getSwappedPredicate(NewPred); 4033 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0)); 4034 } 4035 } 4036 break; 4037 } 4038 case Instruction::Mul: { 4039 if (!I.isEquality()) 4040 break; 4041 4042 const APInt *C; 4043 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isNullValue() && 4044 !C->isOneValue()) { 4045 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask) 4046 // Mask = -1 >> count-trailing-zeros(C). 4047 if (unsigned TZs = C->countTrailingZeros()) { 4048 Constant *Mask = ConstantInt::get( 4049 BO0->getType(), 4050 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs)); 4051 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask); 4052 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask); 4053 return new ICmpInst(Pred, And1, And2); 4054 } 4055 // If there are no trailing zeros in the multiplier, just eliminate 4056 // the multiplies (no masking is needed): 4057 // icmp eq/ne (X * C), (Y * C) --> icmp eq/ne X, Y 4058 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4059 } 4060 break; 4061 } 4062 case Instruction::UDiv: 4063 case Instruction::LShr: 4064 if (I.isSigned() || !BO0->isExact() || !BO1->isExact()) 4065 break; 4066 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4067 4068 case Instruction::SDiv: 4069 if (!I.isEquality() || !BO0->isExact() || !BO1->isExact()) 4070 break; 4071 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4072 4073 case Instruction::AShr: 4074 if (!BO0->isExact() || !BO1->isExact()) 4075 break; 4076 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4077 4078 case Instruction::Shl: { 4079 bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap(); 4080 bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap(); 4081 if (!NUW && !NSW) 4082 break; 4083 if (!NSW && I.isSigned()) 4084 break; 4085 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0)); 4086 } 4087 } 4088 } 4089 4090 if (BO0) { 4091 // Transform A & (L - 1) `ult` L --> L != 0 4092 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes()); 4093 auto BitwiseAnd = m_c_And(m_Value(), LSubOne); 4094 4095 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) { 4096 auto *Zero = Constant::getNullValue(BO0->getType()); 4097 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero); 4098 } 4099 } 4100 4101 if (Value *V = foldUnsignedMultiplicationOverflowCheck(I)) 4102 return replaceInstUsesWith(I, V); 4103 4104 if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder)) 4105 return replaceInstUsesWith(I, V); 4106 4107 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder)) 4108 return replaceInstUsesWith(I, V); 4109 4110 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder)) 4111 return replaceInstUsesWith(I, V); 4112 4113 return nullptr; 4114 } 4115 4116 /// Fold icmp Pred min|max(X, Y), X. 4117 static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) { 4118 ICmpInst::Predicate Pred = Cmp.getPredicate(); 4119 Value *Op0 = Cmp.getOperand(0); 4120 Value *X = Cmp.getOperand(1); 4121 4122 // Canonicalize minimum or maximum operand to LHS of the icmp. 4123 if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) || 4124 match(X, m_c_SMax(m_Specific(Op0), m_Value())) || 4125 match(X, m_c_UMin(m_Specific(Op0), m_Value())) || 4126 match(X, m_c_UMax(m_Specific(Op0), m_Value()))) { 4127 std::swap(Op0, X); 4128 Pred = Cmp.getSwappedPredicate(); 4129 } 4130 4131 Value *Y; 4132 if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) { 4133 // smin(X, Y) == X --> X s<= Y 4134 // smin(X, Y) s>= X --> X s<= Y 4135 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE) 4136 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y); 4137 4138 // smin(X, Y) != X --> X s> Y 4139 // smin(X, Y) s< X --> X s> Y 4140 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT) 4141 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y); 4142 4143 // These cases should be handled in InstSimplify: 4144 // smin(X, Y) s<= X --> true 4145 // smin(X, Y) s> X --> false 4146 return nullptr; 4147 } 4148 4149 if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) { 4150 // smax(X, Y) == X --> X s>= Y 4151 // smax(X, Y) s<= X --> X s>= Y 4152 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE) 4153 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y); 4154 4155 // smax(X, Y) != X --> X s< Y 4156 // smax(X, Y) s> X --> X s< Y 4157 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT) 4158 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y); 4159 4160 // These cases should be handled in InstSimplify: 4161 // smax(X, Y) s>= X --> true 4162 // smax(X, Y) s< X --> false 4163 return nullptr; 4164 } 4165 4166 if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) { 4167 // umin(X, Y) == X --> X u<= Y 4168 // umin(X, Y) u>= X --> X u<= Y 4169 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE) 4170 return new ICmpInst(ICmpInst::ICMP_ULE, X, Y); 4171 4172 // umin(X, Y) != X --> X u> Y 4173 // umin(X, Y) u< X --> X u> Y 4174 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT) 4175 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y); 4176 4177 // These cases should be handled in InstSimplify: 4178 // umin(X, Y) u<= X --> true 4179 // umin(X, Y) u> X --> false 4180 return nullptr; 4181 } 4182 4183 if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) { 4184 // umax(X, Y) == X --> X u>= Y 4185 // umax(X, Y) u<= X --> X u>= Y 4186 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE) 4187 return new ICmpInst(ICmpInst::ICMP_UGE, X, Y); 4188 4189 // umax(X, Y) != X --> X u< Y 4190 // umax(X, Y) u> X --> X u< Y 4191 if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT) 4192 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y); 4193 4194 // These cases should be handled in InstSimplify: 4195 // umax(X, Y) u>= X --> true 4196 // umax(X, Y) u< X --> false 4197 return nullptr; 4198 } 4199 4200 return nullptr; 4201 } 4202 4203 Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) { 4204 if (!I.isEquality()) 4205 return nullptr; 4206 4207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4208 const CmpInst::Predicate Pred = I.getPredicate(); 4209 Value *A, *B, *C, *D; 4210 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) { 4211 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0 4212 Value *OtherVal = A == Op1 ? B : A; 4213 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType())); 4214 } 4215 4216 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) { 4217 // A^c1 == C^c2 --> A == C^(c1^c2) 4218 ConstantInt *C1, *C2; 4219 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) && 4220 Op1->hasOneUse()) { 4221 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue()); 4222 Value *Xor = Builder.CreateXor(C, NC); 4223 return new ICmpInst(Pred, A, Xor); 4224 } 4225 4226 // A^B == A^D -> B == D 4227 if (A == C) 4228 return new ICmpInst(Pred, B, D); 4229 if (A == D) 4230 return new ICmpInst(Pred, B, C); 4231 if (B == C) 4232 return new ICmpInst(Pred, A, D); 4233 if (B == D) 4234 return new ICmpInst(Pred, A, C); 4235 } 4236 } 4237 4238 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) { 4239 // A == (A^B) -> B == 0 4240 Value *OtherVal = A == Op0 ? B : A; 4241 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType())); 4242 } 4243 4244 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0 4245 if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) && 4246 match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) { 4247 Value *X = nullptr, *Y = nullptr, *Z = nullptr; 4248 4249 if (A == C) { 4250 X = B; 4251 Y = D; 4252 Z = A; 4253 } else if (A == D) { 4254 X = B; 4255 Y = C; 4256 Z = A; 4257 } else if (B == C) { 4258 X = A; 4259 Y = D; 4260 Z = B; 4261 } else if (B == D) { 4262 X = A; 4263 Y = C; 4264 Z = B; 4265 } 4266 4267 if (X) { // Build (X^Y) & Z 4268 Op1 = Builder.CreateXor(X, Y); 4269 Op1 = Builder.CreateAnd(Op1, Z); 4270 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType())); 4271 } 4272 } 4273 4274 // Transform (zext A) == (B & (1<<X)-1) --> A == (trunc B) 4275 // and (B & (1<<X)-1) == (zext A) --> A == (trunc B) 4276 ConstantInt *Cst1; 4277 if ((Op0->hasOneUse() && match(Op0, m_ZExt(m_Value(A))) && 4278 match(Op1, m_And(m_Value(B), m_ConstantInt(Cst1)))) || 4279 (Op1->hasOneUse() && match(Op0, m_And(m_Value(B), m_ConstantInt(Cst1))) && 4280 match(Op1, m_ZExt(m_Value(A))))) { 4281 APInt Pow2 = Cst1->getValue() + 1; 4282 if (Pow2.isPowerOf2() && isa<IntegerType>(A->getType()) && 4283 Pow2.logBase2() == cast<IntegerType>(A->getType())->getBitWidth()) 4284 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType())); 4285 } 4286 4287 // (A >> C) == (B >> C) --> (A^B) u< (1 << C) 4288 // For lshr and ashr pairs. 4289 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_ConstantInt(Cst1)))) && 4290 match(Op1, m_OneUse(m_LShr(m_Value(B), m_Specific(Cst1))))) || 4291 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_ConstantInt(Cst1)))) && 4292 match(Op1, m_OneUse(m_AShr(m_Value(B), m_Specific(Cst1)))))) { 4293 unsigned TypeBits = Cst1->getBitWidth(); 4294 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 4295 if (ShAmt < TypeBits && ShAmt != 0) { 4296 ICmpInst::Predicate NewPred = 4297 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT; 4298 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted"); 4299 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt); 4300 return new ICmpInst(NewPred, Xor, Builder.getInt(CmpVal)); 4301 } 4302 } 4303 4304 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0 4305 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) && 4306 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) { 4307 unsigned TypeBits = Cst1->getBitWidth(); 4308 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits); 4309 if (ShAmt < TypeBits && ShAmt != 0) { 4310 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted"); 4311 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt); 4312 Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal), 4313 I.getName() + ".mask"); 4314 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType())); 4315 } 4316 } 4317 4318 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to 4319 // "icmp (and X, mask), cst" 4320 uint64_t ShAmt = 0; 4321 if (Op0->hasOneUse() && 4322 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) && 4323 match(Op1, m_ConstantInt(Cst1)) && 4324 // Only do this when A has multiple uses. This is most important to do 4325 // when it exposes other optimizations. 4326 !A->hasOneUse()) { 4327 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits(); 4328 4329 if (ShAmt < ASize) { 4330 APInt MaskV = 4331 APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits()); 4332 MaskV <<= ShAmt; 4333 4334 APInt CmpV = Cst1->getValue().zext(ASize); 4335 CmpV <<= ShAmt; 4336 4337 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV)); 4338 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV)); 4339 } 4340 } 4341 4342 // If both operands are byte-swapped or bit-reversed, just compare the 4343 // original values. 4344 // TODO: Move this to a function similar to foldICmpIntrinsicWithConstant() 4345 // and handle more intrinsics. 4346 if ((match(Op0, m_BSwap(m_Value(A))) && match(Op1, m_BSwap(m_Value(B)))) || 4347 (match(Op0, m_BitReverse(m_Value(A))) && 4348 match(Op1, m_BitReverse(m_Value(B))))) 4349 return new ICmpInst(Pred, A, B); 4350 4351 // Canonicalize checking for a power-of-2-or-zero value: 4352 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants) 4353 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants) 4354 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()), 4355 m_Deferred(A)))) || 4356 !match(Op1, m_ZeroInt())) 4357 A = nullptr; 4358 4359 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants) 4360 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants) 4361 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1))))) 4362 A = Op1; 4363 else if (match(Op1, 4364 m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0))))) 4365 A = Op0; 4366 4367 if (A) { 4368 Type *Ty = A->getType(); 4369 CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A); 4370 return Pred == ICmpInst::ICMP_EQ 4371 ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2)) 4372 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1)); 4373 } 4374 4375 return nullptr; 4376 } 4377 4378 static Instruction *foldICmpWithZextOrSext(ICmpInst &ICmp, 4379 InstCombiner::BuilderTy &Builder) { 4380 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0"); 4381 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0)); 4382 Value *X; 4383 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X)))) 4384 return nullptr; 4385 4386 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt; 4387 bool IsSignedCmp = ICmp.isSigned(); 4388 if (auto *CastOp1 = dyn_cast<CastInst>(ICmp.getOperand(1))) { 4389 // If the signedness of the two casts doesn't agree (i.e. one is a sext 4390 // and the other is a zext), then we can't handle this. 4391 // TODO: This is too strict. We can handle some predicates (equality?). 4392 if (CastOp0->getOpcode() != CastOp1->getOpcode()) 4393 return nullptr; 4394 4395 // Not an extension from the same type? 4396 Value *Y = CastOp1->getOperand(0); 4397 Type *XTy = X->getType(), *YTy = Y->getType(); 4398 if (XTy != YTy) { 4399 // One of the casts must have one use because we are creating a new cast. 4400 if (!CastOp0->hasOneUse() && !CastOp1->hasOneUse()) 4401 return nullptr; 4402 // Extend the narrower operand to the type of the wider operand. 4403 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits()) 4404 X = Builder.CreateCast(CastOp0->getOpcode(), X, YTy); 4405 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits()) 4406 Y = Builder.CreateCast(CastOp0->getOpcode(), Y, XTy); 4407 else 4408 return nullptr; 4409 } 4410 4411 // (zext X) == (zext Y) --> X == Y 4412 // (sext X) == (sext Y) --> X == Y 4413 if (ICmp.isEquality()) 4414 return new ICmpInst(ICmp.getPredicate(), X, Y); 4415 4416 // A signed comparison of sign extended values simplifies into a 4417 // signed comparison. 4418 if (IsSignedCmp && IsSignedExt) 4419 return new ICmpInst(ICmp.getPredicate(), X, Y); 4420 4421 // The other three cases all fold into an unsigned comparison. 4422 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y); 4423 } 4424 4425 // Below here, we are only folding a compare with constant. 4426 auto *C = dyn_cast<Constant>(ICmp.getOperand(1)); 4427 if (!C) 4428 return nullptr; 4429 4430 // Compute the constant that would happen if we truncated to SrcTy then 4431 // re-extended to DestTy. 4432 Type *SrcTy = CastOp0->getSrcTy(); 4433 Type *DestTy = CastOp0->getDestTy(); 4434 Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy); 4435 Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy); 4436 4437 // If the re-extended constant didn't change... 4438 if (Res2 == C) { 4439 if (ICmp.isEquality()) 4440 return new ICmpInst(ICmp.getPredicate(), X, Res1); 4441 4442 // A signed comparison of sign extended values simplifies into a 4443 // signed comparison. 4444 if (IsSignedExt && IsSignedCmp) 4445 return new ICmpInst(ICmp.getPredicate(), X, Res1); 4446 4447 // The other three cases all fold into an unsigned comparison. 4448 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1); 4449 } 4450 4451 // The re-extended constant changed, partly changed (in the case of a vector), 4452 // or could not be determined to be equal (in the case of a constant 4453 // expression), so the constant cannot be represented in the shorter type. 4454 // All the cases that fold to true or false will have already been handled 4455 // by SimplifyICmpInst, so only deal with the tricky case. 4456 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C)) 4457 return nullptr; 4458 4459 // Is source op positive? 4460 // icmp ult (sext X), C --> icmp sgt X, -1 4461 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT) 4462 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy)); 4463 4464 // Is source op negative? 4465 // icmp ugt (sext X), C --> icmp slt X, 0 4466 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!"); 4467 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy)); 4468 } 4469 4470 /// Handle icmp (cast x), (cast or constant). 4471 Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) { 4472 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0)); 4473 if (!CastOp0) 4474 return nullptr; 4475 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1))) 4476 return nullptr; 4477 4478 Value *Op0Src = CastOp0->getOperand(0); 4479 Type *SrcTy = CastOp0->getSrcTy(); 4480 Type *DestTy = CastOp0->getDestTy(); 4481 4482 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 4483 // integer type is the same size as the pointer type. 4484 auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) { 4485 if (isa<VectorType>(SrcTy)) { 4486 SrcTy = cast<VectorType>(SrcTy)->getElementType(); 4487 DestTy = cast<VectorType>(DestTy)->getElementType(); 4488 } 4489 return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth(); 4490 }; 4491 if (CastOp0->getOpcode() == Instruction::PtrToInt && 4492 CompatibleSizes(SrcTy, DestTy)) { 4493 Value *NewOp1 = nullptr; 4494 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) { 4495 Value *PtrSrc = PtrToIntOp1->getOperand(0); 4496 if (PtrSrc->getType()->getPointerAddressSpace() == 4497 Op0Src->getType()->getPointerAddressSpace()) { 4498 NewOp1 = PtrToIntOp1->getOperand(0); 4499 // If the pointer types don't match, insert a bitcast. 4500 if (Op0Src->getType() != NewOp1->getType()) 4501 NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType()); 4502 } 4503 } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) { 4504 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy); 4505 } 4506 4507 if (NewOp1) 4508 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1); 4509 } 4510 4511 return foldICmpWithZextOrSext(ICmp, Builder); 4512 } 4513 4514 static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS) { 4515 switch (BinaryOp) { 4516 default: 4517 llvm_unreachable("Unsupported binary op"); 4518 case Instruction::Add: 4519 case Instruction::Sub: 4520 return match(RHS, m_Zero()); 4521 case Instruction::Mul: 4522 return match(RHS, m_One()); 4523 } 4524 } 4525 4526 OverflowResult 4527 InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp, 4528 bool IsSigned, Value *LHS, Value *RHS, 4529 Instruction *CxtI) const { 4530 switch (BinaryOp) { 4531 default: 4532 llvm_unreachable("Unsupported binary op"); 4533 case Instruction::Add: 4534 if (IsSigned) 4535 return computeOverflowForSignedAdd(LHS, RHS, CxtI); 4536 else 4537 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI); 4538 case Instruction::Sub: 4539 if (IsSigned) 4540 return computeOverflowForSignedSub(LHS, RHS, CxtI); 4541 else 4542 return computeOverflowForUnsignedSub(LHS, RHS, CxtI); 4543 case Instruction::Mul: 4544 if (IsSigned) 4545 return computeOverflowForSignedMul(LHS, RHS, CxtI); 4546 else 4547 return computeOverflowForUnsignedMul(LHS, RHS, CxtI); 4548 } 4549 } 4550 4551 bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, 4552 bool IsSigned, Value *LHS, 4553 Value *RHS, Instruction &OrigI, 4554 Value *&Result, 4555 Constant *&Overflow) { 4556 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS)) 4557 std::swap(LHS, RHS); 4558 4559 // If the overflow check was an add followed by a compare, the insertion point 4560 // may be pointing to the compare. We want to insert the new instructions 4561 // before the add in case there are uses of the add between the add and the 4562 // compare. 4563 Builder.SetInsertPoint(&OrigI); 4564 4565 if (isNeutralValue(BinaryOp, RHS)) { 4566 Result = LHS; 4567 Overflow = Builder.getFalse(); 4568 return true; 4569 } 4570 4571 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) { 4572 case OverflowResult::MayOverflow: 4573 return false; 4574 case OverflowResult::AlwaysOverflowsLow: 4575 case OverflowResult::AlwaysOverflowsHigh: 4576 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS); 4577 Result->takeName(&OrigI); 4578 Overflow = Builder.getTrue(); 4579 return true; 4580 case OverflowResult::NeverOverflows: 4581 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS); 4582 Result->takeName(&OrigI); 4583 Overflow = Builder.getFalse(); 4584 if (auto *Inst = dyn_cast<Instruction>(Result)) { 4585 if (IsSigned) 4586 Inst->setHasNoSignedWrap(); 4587 else 4588 Inst->setHasNoUnsignedWrap(); 4589 } 4590 return true; 4591 } 4592 4593 llvm_unreachable("Unexpected overflow result"); 4594 } 4595 4596 /// Recognize and process idiom involving test for multiplication 4597 /// overflow. 4598 /// 4599 /// The caller has matched a pattern of the form: 4600 /// I = cmp u (mul(zext A, zext B), V 4601 /// The function checks if this is a test for overflow and if so replaces 4602 /// multiplication with call to 'mul.with.overflow' intrinsic. 4603 /// 4604 /// \param I Compare instruction. 4605 /// \param MulVal Result of 'mult' instruction. It is one of the arguments of 4606 /// the compare instruction. Must be of integer type. 4607 /// \param OtherVal The other argument of compare instruction. 4608 /// \returns Instruction which must replace the compare instruction, NULL if no 4609 /// replacement required. 4610 static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal, 4611 Value *OtherVal, 4612 InstCombinerImpl &IC) { 4613 // Don't bother doing this transformation for pointers, don't do it for 4614 // vectors. 4615 if (!isa<IntegerType>(MulVal->getType())) 4616 return nullptr; 4617 4618 assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal); 4619 assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal); 4620 auto *MulInstr = dyn_cast<Instruction>(MulVal); 4621 if (!MulInstr) 4622 return nullptr; 4623 assert(MulInstr->getOpcode() == Instruction::Mul); 4624 4625 auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)), 4626 *RHS = cast<ZExtOperator>(MulInstr->getOperand(1)); 4627 assert(LHS->getOpcode() == Instruction::ZExt); 4628 assert(RHS->getOpcode() == Instruction::ZExt); 4629 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0); 4630 4631 // Calculate type and width of the result produced by mul.with.overflow. 4632 Type *TyA = A->getType(), *TyB = B->getType(); 4633 unsigned WidthA = TyA->getPrimitiveSizeInBits(), 4634 WidthB = TyB->getPrimitiveSizeInBits(); 4635 unsigned MulWidth; 4636 Type *MulType; 4637 if (WidthB > WidthA) { 4638 MulWidth = WidthB; 4639 MulType = TyB; 4640 } else { 4641 MulWidth = WidthA; 4642 MulType = TyA; 4643 } 4644 4645 // In order to replace the original mul with a narrower mul.with.overflow, 4646 // all uses must ignore upper bits of the product. The number of used low 4647 // bits must be not greater than the width of mul.with.overflow. 4648 if (MulVal->hasNUsesOrMore(2)) 4649 for (User *U : MulVal->users()) { 4650 if (U == &I) 4651 continue; 4652 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 4653 // Check if truncation ignores bits above MulWidth. 4654 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits(); 4655 if (TruncWidth > MulWidth) 4656 return nullptr; 4657 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 4658 // Check if AND ignores bits above MulWidth. 4659 if (BO->getOpcode() != Instruction::And) 4660 return nullptr; 4661 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) { 4662 const APInt &CVal = CI->getValue(); 4663 if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth) 4664 return nullptr; 4665 } else { 4666 // In this case we could have the operand of the binary operation 4667 // being defined in another block, and performing the replacement 4668 // could break the dominance relation. 4669 return nullptr; 4670 } 4671 } else { 4672 // Other uses prohibit this transformation. 4673 return nullptr; 4674 } 4675 } 4676 4677 // Recognize patterns 4678 switch (I.getPredicate()) { 4679 case ICmpInst::ICMP_EQ: 4680 case ICmpInst::ICMP_NE: 4681 // Recognize pattern: 4682 // mulval = mul(zext A, zext B) 4683 // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits. 4684 ConstantInt *CI; 4685 Value *ValToMask; 4686 if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) { 4687 if (ValToMask != MulVal) 4688 return nullptr; 4689 const APInt &CVal = CI->getValue() + 1; 4690 if (CVal.isPowerOf2()) { 4691 unsigned MaskWidth = CVal.logBase2(); 4692 if (MaskWidth == MulWidth) 4693 break; // Recognized 4694 } 4695 } 4696 return nullptr; 4697 4698 case ICmpInst::ICMP_UGT: 4699 // Recognize pattern: 4700 // mulval = mul(zext A, zext B) 4701 // cmp ugt mulval, max 4702 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4703 APInt MaxVal = APInt::getMaxValue(MulWidth); 4704 MaxVal = MaxVal.zext(CI->getBitWidth()); 4705 if (MaxVal.eq(CI->getValue())) 4706 break; // Recognized 4707 } 4708 return nullptr; 4709 4710 case ICmpInst::ICMP_UGE: 4711 // Recognize pattern: 4712 // mulval = mul(zext A, zext B) 4713 // cmp uge mulval, max+1 4714 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4715 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 4716 if (MaxVal.eq(CI->getValue())) 4717 break; // Recognized 4718 } 4719 return nullptr; 4720 4721 case ICmpInst::ICMP_ULE: 4722 // Recognize pattern: 4723 // mulval = mul(zext A, zext B) 4724 // cmp ule mulval, max 4725 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4726 APInt MaxVal = APInt::getMaxValue(MulWidth); 4727 MaxVal = MaxVal.zext(CI->getBitWidth()); 4728 if (MaxVal.eq(CI->getValue())) 4729 break; // Recognized 4730 } 4731 return nullptr; 4732 4733 case ICmpInst::ICMP_ULT: 4734 // Recognize pattern: 4735 // mulval = mul(zext A, zext B) 4736 // cmp ule mulval, max + 1 4737 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) { 4738 APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth); 4739 if (MaxVal.eq(CI->getValue())) 4740 break; // Recognized 4741 } 4742 return nullptr; 4743 4744 default: 4745 return nullptr; 4746 } 4747 4748 InstCombiner::BuilderTy &Builder = IC.Builder; 4749 Builder.SetInsertPoint(MulInstr); 4750 4751 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B) 4752 Value *MulA = A, *MulB = B; 4753 if (WidthA < MulWidth) 4754 MulA = Builder.CreateZExt(A, MulType); 4755 if (WidthB < MulWidth) 4756 MulB = Builder.CreateZExt(B, MulType); 4757 Function *F = Intrinsic::getDeclaration( 4758 I.getModule(), Intrinsic::umul_with_overflow, MulType); 4759 CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul"); 4760 IC.addToWorklist(MulInstr); 4761 4762 // If there are uses of mul result other than the comparison, we know that 4763 // they are truncation or binary AND. Change them to use result of 4764 // mul.with.overflow and adjust properly mask/size. 4765 if (MulVal->hasNUsesOrMore(2)) { 4766 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value"); 4767 for (auto UI = MulVal->user_begin(), UE = MulVal->user_end(); UI != UE;) { 4768 User *U = *UI++; 4769 if (U == &I || U == OtherVal) 4770 continue; 4771 if (TruncInst *TI = dyn_cast<TruncInst>(U)) { 4772 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth) 4773 IC.replaceInstUsesWith(*TI, Mul); 4774 else 4775 TI->setOperand(0, Mul); 4776 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) { 4777 assert(BO->getOpcode() == Instruction::And); 4778 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask) 4779 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1)); 4780 APInt ShortMask = CI->getValue().trunc(MulWidth); 4781 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask); 4782 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType()); 4783 IC.replaceInstUsesWith(*BO, Zext); 4784 } else { 4785 llvm_unreachable("Unexpected Binary operation"); 4786 } 4787 IC.addToWorklist(cast<Instruction>(U)); 4788 } 4789 } 4790 if (isa<Instruction>(OtherVal)) 4791 IC.addToWorklist(cast<Instruction>(OtherVal)); 4792 4793 // The original icmp gets replaced with the overflow value, maybe inverted 4794 // depending on predicate. 4795 bool Inverse = false; 4796 switch (I.getPredicate()) { 4797 case ICmpInst::ICMP_NE: 4798 break; 4799 case ICmpInst::ICMP_EQ: 4800 Inverse = true; 4801 break; 4802 case ICmpInst::ICMP_UGT: 4803 case ICmpInst::ICMP_UGE: 4804 if (I.getOperand(0) == MulVal) 4805 break; 4806 Inverse = true; 4807 break; 4808 case ICmpInst::ICMP_ULT: 4809 case ICmpInst::ICMP_ULE: 4810 if (I.getOperand(1) == MulVal) 4811 break; 4812 Inverse = true; 4813 break; 4814 default: 4815 llvm_unreachable("Unexpected predicate"); 4816 } 4817 if (Inverse) { 4818 Value *Res = Builder.CreateExtractValue(Call, 1); 4819 return BinaryOperator::CreateNot(Res); 4820 } 4821 4822 return ExtractValueInst::Create(Call, 1); 4823 } 4824 4825 /// When performing a comparison against a constant, it is possible that not all 4826 /// the bits in the LHS are demanded. This helper method computes the mask that 4827 /// IS demanded. 4828 static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) { 4829 const APInt *RHS; 4830 if (!match(I.getOperand(1), m_APInt(RHS))) 4831 return APInt::getAllOnesValue(BitWidth); 4832 4833 // If this is a normal comparison, it demands all bits. If it is a sign bit 4834 // comparison, it only demands the sign bit. 4835 bool UnusedBit; 4836 if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit)) 4837 return APInt::getSignMask(BitWidth); 4838 4839 switch (I.getPredicate()) { 4840 // For a UGT comparison, we don't care about any bits that 4841 // correspond to the trailing ones of the comparand. The value of these 4842 // bits doesn't impact the outcome of the comparison, because any value 4843 // greater than the RHS must differ in a bit higher than these due to carry. 4844 case ICmpInst::ICMP_UGT: 4845 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes()); 4846 4847 // Similarly, for a ULT comparison, we don't care about the trailing zeros. 4848 // Any value less than the RHS must differ in a higher bit because of carries. 4849 case ICmpInst::ICMP_ULT: 4850 return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros()); 4851 4852 default: 4853 return APInt::getAllOnesValue(BitWidth); 4854 } 4855 } 4856 4857 /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst 4858 /// should be swapped. 4859 /// The decision is based on how many times these two operands are reused 4860 /// as subtract operands and their positions in those instructions. 4861 /// The rationale is that several architectures use the same instruction for 4862 /// both subtract and cmp. Thus, it is better if the order of those operands 4863 /// match. 4864 /// \return true if Op0 and Op1 should be swapped. 4865 static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) { 4866 // Filter out pointer values as those cannot appear directly in subtract. 4867 // FIXME: we may want to go through inttoptrs or bitcasts. 4868 if (Op0->getType()->isPointerTy()) 4869 return false; 4870 // If a subtract already has the same operands as a compare, swapping would be 4871 // bad. If a subtract has the same operands as a compare but in reverse order, 4872 // then swapping is good. 4873 int GoodToSwap = 0; 4874 for (const User *U : Op0->users()) { 4875 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0)))) 4876 GoodToSwap++; 4877 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1)))) 4878 GoodToSwap--; 4879 } 4880 return GoodToSwap > 0; 4881 } 4882 4883 /// Check that one use is in the same block as the definition and all 4884 /// other uses are in blocks dominated by a given block. 4885 /// 4886 /// \param DI Definition 4887 /// \param UI Use 4888 /// \param DB Block that must dominate all uses of \p DI outside 4889 /// the parent block 4890 /// \return true when \p UI is the only use of \p DI in the parent block 4891 /// and all other uses of \p DI are in blocks dominated by \p DB. 4892 /// 4893 bool InstCombinerImpl::dominatesAllUses(const Instruction *DI, 4894 const Instruction *UI, 4895 const BasicBlock *DB) const { 4896 assert(DI && UI && "Instruction not defined\n"); 4897 // Ignore incomplete definitions. 4898 if (!DI->getParent()) 4899 return false; 4900 // DI and UI must be in the same block. 4901 if (DI->getParent() != UI->getParent()) 4902 return false; 4903 // Protect from self-referencing blocks. 4904 if (DI->getParent() == DB) 4905 return false; 4906 for (const User *U : DI->users()) { 4907 auto *Usr = cast<Instruction>(U); 4908 if (Usr != UI && !DT.dominates(DB, Usr->getParent())) 4909 return false; 4910 } 4911 return true; 4912 } 4913 4914 /// Return true when the instruction sequence within a block is select-cmp-br. 4915 static bool isChainSelectCmpBranch(const SelectInst *SI) { 4916 const BasicBlock *BB = SI->getParent(); 4917 if (!BB) 4918 return false; 4919 auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator()); 4920 if (!BI || BI->getNumSuccessors() != 2) 4921 return false; 4922 auto *IC = dyn_cast<ICmpInst>(BI->getCondition()); 4923 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI)) 4924 return false; 4925 return true; 4926 } 4927 4928 /// True when a select result is replaced by one of its operands 4929 /// in select-icmp sequence. This will eventually result in the elimination 4930 /// of the select. 4931 /// 4932 /// \param SI Select instruction 4933 /// \param Icmp Compare instruction 4934 /// \param SIOpd Operand that replaces the select 4935 /// 4936 /// Notes: 4937 /// - The replacement is global and requires dominator information 4938 /// - The caller is responsible for the actual replacement 4939 /// 4940 /// Example: 4941 /// 4942 /// entry: 4943 /// %4 = select i1 %3, %C* %0, %C* null 4944 /// %5 = icmp eq %C* %4, null 4945 /// br i1 %5, label %9, label %7 4946 /// ... 4947 /// ; <label>:7 ; preds = %entry 4948 /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0 4949 /// ... 4950 /// 4951 /// can be transformed to 4952 /// 4953 /// %5 = icmp eq %C* %0, null 4954 /// %6 = select i1 %3, i1 %5, i1 true 4955 /// br i1 %6, label %9, label %7 4956 /// ... 4957 /// ; <label>:7 ; preds = %entry 4958 /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0! 4959 /// 4960 /// Similar when the first operand of the select is a constant or/and 4961 /// the compare is for not equal rather than equal. 4962 /// 4963 /// NOTE: The function is only called when the select and compare constants 4964 /// are equal, the optimization can work only for EQ predicates. This is not a 4965 /// major restriction since a NE compare should be 'normalized' to an equal 4966 /// compare, which usually happens in the combiner and test case 4967 /// select-cmp-br.ll checks for it. 4968 bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI, 4969 const ICmpInst *Icmp, 4970 const unsigned SIOpd) { 4971 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!"); 4972 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) { 4973 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1); 4974 // The check for the single predecessor is not the best that can be 4975 // done. But it protects efficiently against cases like when SI's 4976 // home block has two successors, Succ and Succ1, and Succ1 predecessor 4977 // of Succ. Then SI can't be replaced by SIOpd because the use that gets 4978 // replaced can be reached on either path. So the uniqueness check 4979 // guarantees that the path all uses of SI (outside SI's parent) are on 4980 // is disjoint from all other paths out of SI. But that information 4981 // is more expensive to compute, and the trade-off here is in favor 4982 // of compile-time. It should also be noticed that we check for a single 4983 // predecessor and not only uniqueness. This to handle the situation when 4984 // Succ and Succ1 points to the same basic block. 4985 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) { 4986 NumSel++; 4987 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent()); 4988 return true; 4989 } 4990 } 4991 return false; 4992 } 4993 4994 /// Try to fold the comparison based on range information we can get by checking 4995 /// whether bits are known to be zero or one in the inputs. 4996 Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) { 4997 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 4998 Type *Ty = Op0->getType(); 4999 ICmpInst::Predicate Pred = I.getPredicate(); 5000 5001 // Get scalar or pointer size. 5002 unsigned BitWidth = Ty->isIntOrIntVectorTy() 5003 ? Ty->getScalarSizeInBits() 5004 : DL.getPointerTypeSizeInBits(Ty->getScalarType()); 5005 5006 if (!BitWidth) 5007 return nullptr; 5008 5009 KnownBits Op0Known(BitWidth); 5010 KnownBits Op1Known(BitWidth); 5011 5012 if (SimplifyDemandedBits(&I, 0, 5013 getDemandedBitsLHSMask(I, BitWidth), 5014 Op0Known, 0)) 5015 return &I; 5016 5017 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnesValue(BitWidth), 5018 Op1Known, 0)) 5019 return &I; 5020 5021 // Given the known and unknown bits, compute a range that the LHS could be 5022 // in. Compute the Min, Max and RHS values based on the known bits. For the 5023 // EQ and NE we use unsigned values. 5024 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0); 5025 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0); 5026 if (I.isSigned()) { 5027 computeSignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max); 5028 computeSignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max); 5029 } else { 5030 computeUnsignedMinMaxValuesFromKnownBits(Op0Known, Op0Min, Op0Max); 5031 computeUnsignedMinMaxValuesFromKnownBits(Op1Known, Op1Min, Op1Max); 5032 } 5033 5034 // If Min and Max are known to be the same, then SimplifyDemandedBits figured 5035 // out that the LHS or RHS is a constant. Constant fold this now, so that 5036 // code below can assume that Min != Max. 5037 if (!isa<Constant>(Op0) && Op0Min == Op0Max) 5038 return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1); 5039 if (!isa<Constant>(Op1) && Op1Min == Op1Max) 5040 return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min)); 5041 5042 // Based on the range information we know about the LHS, see if we can 5043 // simplify this comparison. For example, (x&4) < 8 is always true. 5044 switch (Pred) { 5045 default: 5046 llvm_unreachable("Unknown icmp opcode!"); 5047 case ICmpInst::ICMP_EQ: 5048 case ICmpInst::ICMP_NE: { 5049 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max)) { 5050 return Pred == CmpInst::ICMP_EQ 5051 ? replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())) 5052 : replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5053 } 5054 5055 // If all bits are known zero except for one, then we know at most one bit 5056 // is set. If the comparison is against zero, then this is a check to see if 5057 // *that* bit is set. 5058 APInt Op0KnownZeroInverted = ~Op0Known.Zero; 5059 if (Op1Known.isZero()) { 5060 // If the LHS is an AND with the same constant, look through it. 5061 Value *LHS = nullptr; 5062 const APInt *LHSC; 5063 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) || 5064 *LHSC != Op0KnownZeroInverted) 5065 LHS = Op0; 5066 5067 Value *X; 5068 if (match(LHS, m_Shl(m_One(), m_Value(X)))) { 5069 APInt ValToCheck = Op0KnownZeroInverted; 5070 Type *XTy = X->getType(); 5071 if (ValToCheck.isPowerOf2()) { 5072 // ((1 << X) & 8) == 0 -> X != 3 5073 // ((1 << X) & 8) != 0 -> X == 3 5074 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); 5075 auto NewPred = ICmpInst::getInversePredicate(Pred); 5076 return new ICmpInst(NewPred, X, CmpC); 5077 } else if ((++ValToCheck).isPowerOf2()) { 5078 // ((1 << X) & 7) == 0 -> X >= 3 5079 // ((1 << X) & 7) != 0 -> X < 3 5080 auto *CmpC = ConstantInt::get(XTy, ValToCheck.countTrailingZeros()); 5081 auto NewPred = 5082 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT; 5083 return new ICmpInst(NewPred, X, CmpC); 5084 } 5085 } 5086 5087 // Check if the LHS is 8 >>u x and the result is a power of 2 like 1. 5088 const APInt *CI; 5089 if (Op0KnownZeroInverted.isOneValue() && 5090 match(LHS, m_LShr(m_Power2(CI), m_Value(X)))) { 5091 // ((8 >>u X) & 1) == 0 -> X != 3 5092 // ((8 >>u X) & 1) != 0 -> X == 3 5093 unsigned CmpVal = CI->countTrailingZeros(); 5094 auto NewPred = ICmpInst::getInversePredicate(Pred); 5095 return new ICmpInst(NewPred, X, ConstantInt::get(X->getType(), CmpVal)); 5096 } 5097 } 5098 break; 5099 } 5100 case ICmpInst::ICMP_ULT: { 5101 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B) 5102 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5103 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B) 5104 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5105 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B) 5106 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5107 5108 const APInt *CmpC; 5109 if (match(Op1, m_APInt(CmpC))) { 5110 // A <u C -> A == C-1 if min(A)+1 == C 5111 if (*CmpC == Op0Min + 1) 5112 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5113 ConstantInt::get(Op1->getType(), *CmpC - 1)); 5114 // X <u C --> X == 0, if the number of zero bits in the bottom of X 5115 // exceeds the log2 of C. 5116 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2()) 5117 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5118 Constant::getNullValue(Op1->getType())); 5119 } 5120 break; 5121 } 5122 case ICmpInst::ICMP_UGT: { 5123 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B) 5124 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5125 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B) 5126 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5127 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B) 5128 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5129 5130 const APInt *CmpC; 5131 if (match(Op1, m_APInt(CmpC))) { 5132 // A >u C -> A == C+1 if max(a)-1 == C 5133 if (*CmpC == Op0Max - 1) 5134 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5135 ConstantInt::get(Op1->getType(), *CmpC + 1)); 5136 // X >u C --> X != 0, if the number of zero bits in the bottom of X 5137 // exceeds the log2 of C. 5138 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits()) 5139 return new ICmpInst(ICmpInst::ICMP_NE, Op0, 5140 Constant::getNullValue(Op1->getType())); 5141 } 5142 break; 5143 } 5144 case ICmpInst::ICMP_SLT: { 5145 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C) 5146 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5147 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C) 5148 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5149 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B) 5150 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5151 const APInt *CmpC; 5152 if (match(Op1, m_APInt(CmpC))) { 5153 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C 5154 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5155 ConstantInt::get(Op1->getType(), *CmpC - 1)); 5156 } 5157 break; 5158 } 5159 case ICmpInst::ICMP_SGT: { 5160 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B) 5161 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5162 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B) 5163 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5164 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B) 5165 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1); 5166 const APInt *CmpC; 5167 if (match(Op1, m_APInt(CmpC))) { 5168 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C 5169 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, 5170 ConstantInt::get(Op1->getType(), *CmpC + 1)); 5171 } 5172 break; 5173 } 5174 case ICmpInst::ICMP_SGE: 5175 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!"); 5176 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B) 5177 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5178 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B) 5179 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5180 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B) 5181 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5182 break; 5183 case ICmpInst::ICMP_SLE: 5184 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!"); 5185 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B) 5186 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5187 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B) 5188 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5189 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B) 5190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5191 break; 5192 case ICmpInst::ICMP_UGE: 5193 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!"); 5194 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B) 5195 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5196 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B) 5197 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5198 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B) 5199 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5200 break; 5201 case ICmpInst::ICMP_ULE: 5202 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!"); 5203 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B) 5204 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType())); 5205 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B) 5206 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType())); 5207 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B) 5208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1); 5209 break; 5210 } 5211 5212 // Turn a signed comparison into an unsigned one if both operands are known to 5213 // have the same sign. 5214 if (I.isSigned() && 5215 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) || 5216 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) 5217 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1); 5218 5219 return nullptr; 5220 } 5221 5222 llvm::Optional<std::pair<CmpInst::Predicate, Constant *>> 5223 InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred, 5224 Constant *C) { 5225 assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) && 5226 "Only for relational integer predicates."); 5227 5228 Type *Type = C->getType(); 5229 bool IsSigned = ICmpInst::isSigned(Pred); 5230 5231 CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred); 5232 bool WillIncrement = 5233 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT; 5234 5235 // Check if the constant operand can be safely incremented/decremented 5236 // without overflowing/underflowing. 5237 auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) { 5238 return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned); 5239 }; 5240 5241 Constant *SafeReplacementConstant = nullptr; 5242 if (auto *CI = dyn_cast<ConstantInt>(C)) { 5243 // Bail out if the constant can't be safely incremented/decremented. 5244 if (!ConstantIsOk(CI)) 5245 return llvm::None; 5246 } else if (auto *VTy = dyn_cast<VectorType>(Type)) { 5247 unsigned NumElts = cast<FixedVectorType>(VTy)->getNumElements(); 5248 for (unsigned i = 0; i != NumElts; ++i) { 5249 Constant *Elt = C->getAggregateElement(i); 5250 if (!Elt) 5251 return llvm::None; 5252 5253 if (isa<UndefValue>(Elt)) 5254 continue; 5255 5256 // Bail out if we can't determine if this constant is min/max or if we 5257 // know that this constant is min/max. 5258 auto *CI = dyn_cast<ConstantInt>(Elt); 5259 if (!CI || !ConstantIsOk(CI)) 5260 return llvm::None; 5261 5262 if (!SafeReplacementConstant) 5263 SafeReplacementConstant = CI; 5264 } 5265 } else { 5266 // ConstantExpr? 5267 return llvm::None; 5268 } 5269 5270 // It may not be safe to change a compare predicate in the presence of 5271 // undefined elements, so replace those elements with the first safe constant 5272 // that we found. 5273 if (C->containsUndefElement()) { 5274 assert(SafeReplacementConstant && "Replacement constant not set"); 5275 C = Constant::replaceUndefsWith(C, SafeReplacementConstant); 5276 } 5277 5278 CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred); 5279 5280 // Increment or decrement the constant. 5281 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true); 5282 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne); 5283 5284 return std::make_pair(NewPred, NewC); 5285 } 5286 5287 /// If we have an icmp le or icmp ge instruction with a constant operand, turn 5288 /// it into the appropriate icmp lt or icmp gt instruction. This transform 5289 /// allows them to be folded in visitICmpInst. 5290 static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) { 5291 ICmpInst::Predicate Pred = I.getPredicate(); 5292 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) || 5293 InstCombiner::isCanonicalPredicate(Pred)) 5294 return nullptr; 5295 5296 Value *Op0 = I.getOperand(0); 5297 Value *Op1 = I.getOperand(1); 5298 auto *Op1C = dyn_cast<Constant>(Op1); 5299 if (!Op1C) 5300 return nullptr; 5301 5302 auto FlippedStrictness = 5303 InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C); 5304 if (!FlippedStrictness) 5305 return nullptr; 5306 5307 return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second); 5308 } 5309 5310 /// If we have a comparison with a non-canonical predicate, if we can update 5311 /// all the users, invert the predicate and adjust all the users. 5312 CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) { 5313 // Is the predicate already canonical? 5314 CmpInst::Predicate Pred = I.getPredicate(); 5315 if (InstCombiner::isCanonicalPredicate(Pred)) 5316 return nullptr; 5317 5318 // Can all users be adjusted to predicate inversion? 5319 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr)) 5320 return nullptr; 5321 5322 // Ok, we can canonicalize comparison! 5323 // Let's first invert the comparison's predicate. 5324 I.setPredicate(CmpInst::getInversePredicate(Pred)); 5325 I.setName(I.getName() + ".not"); 5326 5327 // And now let's adjust every user. 5328 for (User *U : I.users()) { 5329 switch (cast<Instruction>(U)->getOpcode()) { 5330 case Instruction::Select: { 5331 auto *SI = cast<SelectInst>(U); 5332 SI->swapValues(); 5333 SI->swapProfMetadata(); 5334 break; 5335 } 5336 case Instruction::Br: 5337 cast<BranchInst>(U)->swapSuccessors(); // swaps prof metadata too 5338 break; 5339 case Instruction::Xor: 5340 replaceInstUsesWith(cast<Instruction>(*U), &I); 5341 break; 5342 default: 5343 llvm_unreachable("Got unexpected user - out of sync with " 5344 "canFreelyInvertAllUsersOf() ?"); 5345 } 5346 } 5347 5348 return &I; 5349 } 5350 5351 /// Integer compare with boolean values can always be turned into bitwise ops. 5352 static Instruction *canonicalizeICmpBool(ICmpInst &I, 5353 InstCombiner::BuilderTy &Builder) { 5354 Value *A = I.getOperand(0), *B = I.getOperand(1); 5355 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only"); 5356 5357 // A boolean compared to true/false can be simplified to Op0/true/false in 5358 // 14 out of the 20 (10 predicates * 2 constants) possible combinations. 5359 // Cases not handled by InstSimplify are always 'not' of Op0. 5360 if (match(B, m_Zero())) { 5361 switch (I.getPredicate()) { 5362 case CmpInst::ICMP_EQ: // A == 0 -> !A 5363 case CmpInst::ICMP_ULE: // A <=u 0 -> !A 5364 case CmpInst::ICMP_SGE: // A >=s 0 -> !A 5365 return BinaryOperator::CreateNot(A); 5366 default: 5367 llvm_unreachable("ICmp i1 X, C not simplified as expected."); 5368 } 5369 } else if (match(B, m_One())) { 5370 switch (I.getPredicate()) { 5371 case CmpInst::ICMP_NE: // A != 1 -> !A 5372 case CmpInst::ICMP_ULT: // A <u 1 -> !A 5373 case CmpInst::ICMP_SGT: // A >s -1 -> !A 5374 return BinaryOperator::CreateNot(A); 5375 default: 5376 llvm_unreachable("ICmp i1 X, C not simplified as expected."); 5377 } 5378 } 5379 5380 switch (I.getPredicate()) { 5381 default: 5382 llvm_unreachable("Invalid icmp instruction!"); 5383 case ICmpInst::ICMP_EQ: 5384 // icmp eq i1 A, B -> ~(A ^ B) 5385 return BinaryOperator::CreateNot(Builder.CreateXor(A, B)); 5386 5387 case ICmpInst::ICMP_NE: 5388 // icmp ne i1 A, B -> A ^ B 5389 return BinaryOperator::CreateXor(A, B); 5390 5391 case ICmpInst::ICMP_UGT: 5392 // icmp ugt -> icmp ult 5393 std::swap(A, B); 5394 LLVM_FALLTHROUGH; 5395 case ICmpInst::ICMP_ULT: 5396 // icmp ult i1 A, B -> ~A & B 5397 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B); 5398 5399 case ICmpInst::ICMP_SGT: 5400 // icmp sgt -> icmp slt 5401 std::swap(A, B); 5402 LLVM_FALLTHROUGH; 5403 case ICmpInst::ICMP_SLT: 5404 // icmp slt i1 A, B -> A & ~B 5405 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A); 5406 5407 case ICmpInst::ICMP_UGE: 5408 // icmp uge -> icmp ule 5409 std::swap(A, B); 5410 LLVM_FALLTHROUGH; 5411 case ICmpInst::ICMP_ULE: 5412 // icmp ule i1 A, B -> ~A | B 5413 return BinaryOperator::CreateOr(Builder.CreateNot(A), B); 5414 5415 case ICmpInst::ICMP_SGE: 5416 // icmp sge -> icmp sle 5417 std::swap(A, B); 5418 LLVM_FALLTHROUGH; 5419 case ICmpInst::ICMP_SLE: 5420 // icmp sle i1 A, B -> A | ~B 5421 return BinaryOperator::CreateOr(Builder.CreateNot(B), A); 5422 } 5423 } 5424 5425 // Transform pattern like: 5426 // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X 5427 // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X 5428 // Into: 5429 // (X l>> Y) != 0 5430 // (X l>> Y) == 0 5431 static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp, 5432 InstCombiner::BuilderTy &Builder) { 5433 ICmpInst::Predicate Pred, NewPred; 5434 Value *X, *Y; 5435 if (match(&Cmp, 5436 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) { 5437 switch (Pred) { 5438 case ICmpInst::ICMP_ULE: 5439 NewPred = ICmpInst::ICMP_NE; 5440 break; 5441 case ICmpInst::ICMP_UGT: 5442 NewPred = ICmpInst::ICMP_EQ; 5443 break; 5444 default: 5445 return nullptr; 5446 } 5447 } else if (match(&Cmp, m_c_ICmp(Pred, 5448 m_OneUse(m_CombineOr( 5449 m_Not(m_Shl(m_AllOnes(), m_Value(Y))), 5450 m_Add(m_Shl(m_One(), m_Value(Y)), 5451 m_AllOnes()))), 5452 m_Value(X)))) { 5453 // The variant with 'add' is not canonical, (the variant with 'not' is) 5454 // we only get it because it has extra uses, and can't be canonicalized, 5455 5456 switch (Pred) { 5457 case ICmpInst::ICMP_ULT: 5458 NewPred = ICmpInst::ICMP_NE; 5459 break; 5460 case ICmpInst::ICMP_UGE: 5461 NewPred = ICmpInst::ICMP_EQ; 5462 break; 5463 default: 5464 return nullptr; 5465 } 5466 } else 5467 return nullptr; 5468 5469 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits"); 5470 Constant *Zero = Constant::getNullValue(NewX->getType()); 5471 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero); 5472 } 5473 5474 static Instruction *foldVectorCmp(CmpInst &Cmp, 5475 InstCombiner::BuilderTy &Builder) { 5476 const CmpInst::Predicate Pred = Cmp.getPredicate(); 5477 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1); 5478 Value *V1, *V2; 5479 ArrayRef<int> M; 5480 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M)))) 5481 return nullptr; 5482 5483 // If both arguments of the cmp are shuffles that use the same mask and 5484 // shuffle within a single vector, move the shuffle after the cmp: 5485 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M 5486 Type *V1Ty = V1->getType(); 5487 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) && 5488 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) { 5489 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2); 5490 return new ShuffleVectorInst(NewCmp, UndefValue::get(NewCmp->getType()), M); 5491 } 5492 5493 // Try to canonicalize compare with splatted operand and splat constant. 5494 // TODO: We could generalize this for more than splats. See/use the code in 5495 // InstCombiner::foldVectorBinop(). 5496 Constant *C; 5497 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C))) 5498 return nullptr; 5499 5500 // Length-changing splats are ok, so adjust the constants as needed: 5501 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M 5502 Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true); 5503 int MaskSplatIndex; 5504 if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) { 5505 // We allow undefs in matching, but this transform removes those for safety. 5506 // Demanded elements analysis should be able to recover some/all of that. 5507 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(), 5508 ScalarC); 5509 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex); 5510 Value *NewCmp = Builder.CreateCmp(Pred, V1, C); 5511 return new ShuffleVectorInst(NewCmp, UndefValue::get(NewCmp->getType()), 5512 NewM); 5513 } 5514 5515 return nullptr; 5516 } 5517 5518 // extract(uadd.with.overflow(A, B), 0) ult A 5519 // -> extract(uadd.with.overflow(A, B), 1) 5520 static Instruction *foldICmpOfUAddOv(ICmpInst &I) { 5521 CmpInst::Predicate Pred = I.getPredicate(); 5522 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 5523 5524 Value *UAddOv; 5525 Value *A, *B; 5526 auto UAddOvResultPat = m_ExtractValue<0>( 5527 m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B))); 5528 if (match(Op0, UAddOvResultPat) && 5529 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) || 5530 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) && 5531 (match(A, m_One()) || match(B, m_One()))) || 5532 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) && 5533 (match(A, m_AllOnes()) || match(B, m_AllOnes()))))) 5534 // extract(uadd.with.overflow(A, B), 0) < A 5535 // extract(uadd.with.overflow(A, 1), 0) == 0 5536 // extract(uadd.with.overflow(A, -1), 0) != -1 5537 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand(); 5538 else if (match(Op1, UAddOvResultPat) && 5539 Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B)) 5540 // A > extract(uadd.with.overflow(A, B), 0) 5541 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand(); 5542 else 5543 return nullptr; 5544 5545 return ExtractValueInst::Create(UAddOv, 1); 5546 } 5547 5548 Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) { 5549 bool Changed = false; 5550 const SimplifyQuery Q = SQ.getWithInstruction(&I); 5551 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 5552 unsigned Op0Cplxity = getComplexity(Op0); 5553 unsigned Op1Cplxity = getComplexity(Op1); 5554 5555 /// Orders the operands of the compare so that they are listed from most 5556 /// complex to least complex. This puts constants before unary operators, 5557 /// before binary operators. 5558 if (Op0Cplxity < Op1Cplxity || 5559 (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) { 5560 I.swapOperands(); 5561 std::swap(Op0, Op1); 5562 Changed = true; 5563 } 5564 5565 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, Q)) 5566 return replaceInstUsesWith(I, V); 5567 5568 // Comparing -val or val with non-zero is the same as just comparing val 5569 // ie, abs(val) != 0 -> val != 0 5570 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) { 5571 Value *Cond, *SelectTrue, *SelectFalse; 5572 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue), 5573 m_Value(SelectFalse)))) { 5574 if (Value *V = dyn_castNegVal(SelectTrue)) { 5575 if (V == SelectFalse) 5576 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 5577 } 5578 else if (Value *V = dyn_castNegVal(SelectFalse)) { 5579 if (V == SelectTrue) 5580 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1); 5581 } 5582 } 5583 } 5584 5585 if (Op0->getType()->isIntOrIntVectorTy(1)) 5586 if (Instruction *Res = canonicalizeICmpBool(I, Builder)) 5587 return Res; 5588 5589 if (Instruction *Res = canonicalizeCmpWithConstant(I)) 5590 return Res; 5591 5592 if (Instruction *Res = canonicalizeICmpPredicate(I)) 5593 return Res; 5594 5595 if (Instruction *Res = foldICmpWithConstant(I)) 5596 return Res; 5597 5598 if (Instruction *Res = foldICmpWithDominatingICmp(I)) 5599 return Res; 5600 5601 if (Instruction *Res = foldICmpBinOp(I, Q)) 5602 return Res; 5603 5604 if (Instruction *Res = foldICmpUsingKnownBits(I)) 5605 return Res; 5606 5607 // Test if the ICmpInst instruction is used exclusively by a select as 5608 // part of a minimum or maximum operation. If so, refrain from doing 5609 // any other folding. This helps out other analyses which understand 5610 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 5611 // and CodeGen. And in this case, at least one of the comparison 5612 // operands has at least one user besides the compare (the select), 5613 // which would often largely negate the benefit of folding anyway. 5614 // 5615 // Do the same for the other patterns recognized by matchSelectPattern. 5616 if (I.hasOneUse()) 5617 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) { 5618 Value *A, *B; 5619 SelectPatternResult SPR = matchSelectPattern(SI, A, B); 5620 if (SPR.Flavor != SPF_UNKNOWN) 5621 return nullptr; 5622 } 5623 5624 // Do this after checking for min/max to prevent infinite looping. 5625 if (Instruction *Res = foldICmpWithZero(I)) 5626 return Res; 5627 5628 // FIXME: We only do this after checking for min/max to prevent infinite 5629 // looping caused by a reverse canonicalization of these patterns for min/max. 5630 // FIXME: The organization of folds is a mess. These would naturally go into 5631 // canonicalizeCmpWithConstant(), but we can't move all of the above folds 5632 // down here after the min/max restriction. 5633 ICmpInst::Predicate Pred = I.getPredicate(); 5634 const APInt *C; 5635 if (match(Op1, m_APInt(C))) { 5636 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set 5637 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) { 5638 Constant *Zero = Constant::getNullValue(Op0->getType()); 5639 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero); 5640 } 5641 5642 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear 5643 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) { 5644 Constant *AllOnes = Constant::getAllOnesValue(Op0->getType()); 5645 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes); 5646 } 5647 } 5648 5649 if (Instruction *Res = foldICmpInstWithConstant(I)) 5650 return Res; 5651 5652 // Try to match comparison as a sign bit test. Intentionally do this after 5653 // foldICmpInstWithConstant() to potentially let other folds to happen first. 5654 if (Instruction *New = foldSignBitTest(I)) 5655 return New; 5656 5657 if (Instruction *Res = foldICmpInstWithConstantNotInt(I)) 5658 return Res; 5659 5660 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now. 5661 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0)) 5662 if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I)) 5663 return NI; 5664 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1)) 5665 if (Instruction *NI = foldGEPICmp(GEP, Op0, 5666 ICmpInst::getSwappedPredicate(I.getPredicate()), I)) 5667 return NI; 5668 5669 // Try to optimize equality comparisons against alloca-based pointers. 5670 if (Op0->getType()->isPointerTy() && I.isEquality()) { 5671 assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?"); 5672 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0))) 5673 if (Instruction *New = foldAllocaCmp(I, Alloca, Op1)) 5674 return New; 5675 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1))) 5676 if (Instruction *New = foldAllocaCmp(I, Alloca, Op0)) 5677 return New; 5678 } 5679 5680 if (Instruction *Res = foldICmpBitCast(I, Builder)) 5681 return Res; 5682 5683 // TODO: Hoist this above the min/max bailout. 5684 if (Instruction *R = foldICmpWithCastOp(I)) 5685 return R; 5686 5687 if (Instruction *Res = foldICmpWithMinMax(I)) 5688 return Res; 5689 5690 { 5691 Value *A, *B; 5692 // Transform (A & ~B) == 0 --> (A & B) != 0 5693 // and (A & ~B) != 0 --> (A & B) == 0 5694 // if A is a power of 2. 5695 if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) && 5696 match(Op1, m_Zero()) && 5697 isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality()) 5698 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B), 5699 Op1); 5700 5701 // ~X < ~Y --> Y < X 5702 // ~X < C --> X > ~C 5703 if (match(Op0, m_Not(m_Value(A)))) { 5704 if (match(Op1, m_Not(m_Value(B)))) 5705 return new ICmpInst(I.getPredicate(), B, A); 5706 5707 const APInt *C; 5708 if (match(Op1, m_APInt(C))) 5709 return new ICmpInst(I.getSwappedPredicate(), A, 5710 ConstantInt::get(Op1->getType(), ~(*C))); 5711 } 5712 5713 Instruction *AddI = nullptr; 5714 if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B), 5715 m_Instruction(AddI))) && 5716 isa<IntegerType>(A->getType())) { 5717 Value *Result; 5718 Constant *Overflow; 5719 // m_UAddWithOverflow can match patterns that do not include an explicit 5720 // "add" instruction, so check the opcode of the matched op. 5721 if (AddI->getOpcode() == Instruction::Add && 5722 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, A, B, *AddI, 5723 Result, Overflow)) { 5724 replaceInstUsesWith(*AddI, Result); 5725 eraseInstFromFunction(*AddI); 5726 return replaceInstUsesWith(I, Overflow); 5727 } 5728 } 5729 5730 // (zext a) * (zext b) --> llvm.umul.with.overflow. 5731 if (match(Op0, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 5732 if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this)) 5733 return R; 5734 } 5735 if (match(Op1, m_Mul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) { 5736 if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this)) 5737 return R; 5738 } 5739 } 5740 5741 if (Instruction *Res = foldICmpEquality(I)) 5742 return Res; 5743 5744 if (Instruction *Res = foldICmpOfUAddOv(I)) 5745 return Res; 5746 5747 // The 'cmpxchg' instruction returns an aggregate containing the old value and 5748 // an i1 which indicates whether or not we successfully did the swap. 5749 // 5750 // Replace comparisons between the old value and the expected value with the 5751 // indicator that 'cmpxchg' returns. 5752 // 5753 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to 5754 // spuriously fail. In those cases, the old value may equal the expected 5755 // value but it is possible for the swap to not occur. 5756 if (I.getPredicate() == ICmpInst::ICMP_EQ) 5757 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0)) 5758 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand())) 5759 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 && 5760 !ACXI->isWeak()) 5761 return ExtractValueInst::Create(ACXI, 1); 5762 5763 { 5764 Value *X; 5765 const APInt *C; 5766 // icmp X+Cst, X 5767 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X) 5768 return foldICmpAddOpConst(X, *C, I.getPredicate()); 5769 5770 // icmp X, X+Cst 5771 if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X) 5772 return foldICmpAddOpConst(X, *C, I.getSwappedPredicate()); 5773 } 5774 5775 if (Instruction *Res = foldICmpWithHighBitMask(I, Builder)) 5776 return Res; 5777 5778 if (I.getType()->isVectorTy()) 5779 if (Instruction *Res = foldVectorCmp(I, Builder)) 5780 return Res; 5781 5782 return Changed ? &I : nullptr; 5783 } 5784 5785 /// Fold fcmp ([us]itofp x, cst) if possible. 5786 Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I, 5787 Instruction *LHSI, 5788 Constant *RHSC) { 5789 if (!isa<ConstantFP>(RHSC)) return nullptr; 5790 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF(); 5791 5792 // Get the width of the mantissa. We don't want to hack on conversions that 5793 // might lose information from the integer, e.g. "i64 -> float" 5794 int MantissaWidth = LHSI->getType()->getFPMantissaWidth(); 5795 if (MantissaWidth == -1) return nullptr; // Unknown. 5796 5797 IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType()); 5798 5799 bool LHSUnsigned = isa<UIToFPInst>(LHSI); 5800 5801 if (I.isEquality()) { 5802 FCmpInst::Predicate P = I.getPredicate(); 5803 bool IsExact = false; 5804 APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned); 5805 RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact); 5806 5807 // If the floating point constant isn't an integer value, we know if we will 5808 // ever compare equal / not equal to it. 5809 if (!IsExact) { 5810 // TODO: Can never be -0.0 and other non-representable values 5811 APFloat RHSRoundInt(RHS); 5812 RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven); 5813 if (RHS != RHSRoundInt) { 5814 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ) 5815 return replaceInstUsesWith(I, Builder.getFalse()); 5816 5817 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE); 5818 return replaceInstUsesWith(I, Builder.getTrue()); 5819 } 5820 } 5821 5822 // TODO: If the constant is exactly representable, is it always OK to do 5823 // equality compares as integer? 5824 } 5825 5826 // Check to see that the input is converted from an integer type that is small 5827 // enough that preserves all bits. TODO: check here for "known" sign bits. 5828 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e. 5829 unsigned InputSize = IntTy->getScalarSizeInBits(); 5830 5831 // Following test does NOT adjust InputSize downwards for signed inputs, 5832 // because the most negative value still requires all the mantissa bits 5833 // to distinguish it from one less than that value. 5834 if ((int)InputSize > MantissaWidth) { 5835 // Conversion would lose accuracy. Check if loss can impact comparison. 5836 int Exp = ilogb(RHS); 5837 if (Exp == APFloat::IEK_Inf) { 5838 int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics())); 5839 if (MaxExponent < (int)InputSize - !LHSUnsigned) 5840 // Conversion could create infinity. 5841 return nullptr; 5842 } else { 5843 // Note that if RHS is zero or NaN, then Exp is negative 5844 // and first condition is trivially false. 5845 if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned) 5846 // Conversion could affect comparison. 5847 return nullptr; 5848 } 5849 } 5850 5851 // Otherwise, we can potentially simplify the comparison. We know that it 5852 // will always come through as an integer value and we know the constant is 5853 // not a NAN (it would have been previously simplified). 5854 assert(!RHS.isNaN() && "NaN comparison not already folded!"); 5855 5856 ICmpInst::Predicate Pred; 5857 switch (I.getPredicate()) { 5858 default: llvm_unreachable("Unexpected predicate!"); 5859 case FCmpInst::FCMP_UEQ: 5860 case FCmpInst::FCMP_OEQ: 5861 Pred = ICmpInst::ICMP_EQ; 5862 break; 5863 case FCmpInst::FCMP_UGT: 5864 case FCmpInst::FCMP_OGT: 5865 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT; 5866 break; 5867 case FCmpInst::FCMP_UGE: 5868 case FCmpInst::FCMP_OGE: 5869 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE; 5870 break; 5871 case FCmpInst::FCMP_ULT: 5872 case FCmpInst::FCMP_OLT: 5873 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT; 5874 break; 5875 case FCmpInst::FCMP_ULE: 5876 case FCmpInst::FCMP_OLE: 5877 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE; 5878 break; 5879 case FCmpInst::FCMP_UNE: 5880 case FCmpInst::FCMP_ONE: 5881 Pred = ICmpInst::ICMP_NE; 5882 break; 5883 case FCmpInst::FCMP_ORD: 5884 return replaceInstUsesWith(I, Builder.getTrue()); 5885 case FCmpInst::FCMP_UNO: 5886 return replaceInstUsesWith(I, Builder.getFalse()); 5887 } 5888 5889 // Now we know that the APFloat is a normal number, zero or inf. 5890 5891 // See if the FP constant is too large for the integer. For example, 5892 // comparing an i8 to 300.0. 5893 unsigned IntWidth = IntTy->getScalarSizeInBits(); 5894 5895 if (!LHSUnsigned) { 5896 // If the RHS value is > SignedMax, fold the comparison. This handles +INF 5897 // and large values. 5898 APFloat SMax(RHS.getSemantics()); 5899 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true, 5900 APFloat::rmNearestTiesToEven); 5901 if (SMax < RHS) { // smax < 13123.0 5902 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT || 5903 Pred == ICmpInst::ICMP_SLE) 5904 return replaceInstUsesWith(I, Builder.getTrue()); 5905 return replaceInstUsesWith(I, Builder.getFalse()); 5906 } 5907 } else { 5908 // If the RHS value is > UnsignedMax, fold the comparison. This handles 5909 // +INF and large values. 5910 APFloat UMax(RHS.getSemantics()); 5911 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false, 5912 APFloat::rmNearestTiesToEven); 5913 if (UMax < RHS) { // umax < 13123.0 5914 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT || 5915 Pred == ICmpInst::ICMP_ULE) 5916 return replaceInstUsesWith(I, Builder.getTrue()); 5917 return replaceInstUsesWith(I, Builder.getFalse()); 5918 } 5919 } 5920 5921 if (!LHSUnsigned) { 5922 // See if the RHS value is < SignedMin. 5923 APFloat SMin(RHS.getSemantics()); 5924 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true, 5925 APFloat::rmNearestTiesToEven); 5926 if (SMin > RHS) { // smin > 12312.0 5927 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT || 5928 Pred == ICmpInst::ICMP_SGE) 5929 return replaceInstUsesWith(I, Builder.getTrue()); 5930 return replaceInstUsesWith(I, Builder.getFalse()); 5931 } 5932 } else { 5933 // See if the RHS value is < UnsignedMin. 5934 APFloat UMin(RHS.getSemantics()); 5935 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false, 5936 APFloat::rmNearestTiesToEven); 5937 if (UMin > RHS) { // umin > 12312.0 5938 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT || 5939 Pred == ICmpInst::ICMP_UGE) 5940 return replaceInstUsesWith(I, Builder.getTrue()); 5941 return replaceInstUsesWith(I, Builder.getFalse()); 5942 } 5943 } 5944 5945 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or 5946 // [0, UMAX], but it may still be fractional. See if it is fractional by 5947 // casting the FP value to the integer value and back, checking for equality. 5948 // Don't do this for zero, because -0.0 is not fractional. 5949 Constant *RHSInt = LHSUnsigned 5950 ? ConstantExpr::getFPToUI(RHSC, IntTy) 5951 : ConstantExpr::getFPToSI(RHSC, IntTy); 5952 if (!RHS.isZero()) { 5953 bool Equal = LHSUnsigned 5954 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC 5955 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC; 5956 if (!Equal) { 5957 // If we had a comparison against a fractional value, we have to adjust 5958 // the compare predicate and sometimes the value. RHSC is rounded towards 5959 // zero at this point. 5960 switch (Pred) { 5961 default: llvm_unreachable("Unexpected integer comparison!"); 5962 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true 5963 return replaceInstUsesWith(I, Builder.getTrue()); 5964 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false 5965 return replaceInstUsesWith(I, Builder.getFalse()); 5966 case ICmpInst::ICMP_ULE: 5967 // (float)int <= 4.4 --> int <= 4 5968 // (float)int <= -4.4 --> false 5969 if (RHS.isNegative()) 5970 return replaceInstUsesWith(I, Builder.getFalse()); 5971 break; 5972 case ICmpInst::ICMP_SLE: 5973 // (float)int <= 4.4 --> int <= 4 5974 // (float)int <= -4.4 --> int < -4 5975 if (RHS.isNegative()) 5976 Pred = ICmpInst::ICMP_SLT; 5977 break; 5978 case ICmpInst::ICMP_ULT: 5979 // (float)int < -4.4 --> false 5980 // (float)int < 4.4 --> int <= 4 5981 if (RHS.isNegative()) 5982 return replaceInstUsesWith(I, Builder.getFalse()); 5983 Pred = ICmpInst::ICMP_ULE; 5984 break; 5985 case ICmpInst::ICMP_SLT: 5986 // (float)int < -4.4 --> int < -4 5987 // (float)int < 4.4 --> int <= 4 5988 if (!RHS.isNegative()) 5989 Pred = ICmpInst::ICMP_SLE; 5990 break; 5991 case ICmpInst::ICMP_UGT: 5992 // (float)int > 4.4 --> int > 4 5993 // (float)int > -4.4 --> true 5994 if (RHS.isNegative()) 5995 return replaceInstUsesWith(I, Builder.getTrue()); 5996 break; 5997 case ICmpInst::ICMP_SGT: 5998 // (float)int > 4.4 --> int > 4 5999 // (float)int > -4.4 --> int >= -4 6000 if (RHS.isNegative()) 6001 Pred = ICmpInst::ICMP_SGE; 6002 break; 6003 case ICmpInst::ICMP_UGE: 6004 // (float)int >= -4.4 --> true 6005 // (float)int >= 4.4 --> int > 4 6006 if (RHS.isNegative()) 6007 return replaceInstUsesWith(I, Builder.getTrue()); 6008 Pred = ICmpInst::ICMP_UGT; 6009 break; 6010 case ICmpInst::ICMP_SGE: 6011 // (float)int >= -4.4 --> int >= -4 6012 // (float)int >= 4.4 --> int > 4 6013 if (!RHS.isNegative()) 6014 Pred = ICmpInst::ICMP_SGT; 6015 break; 6016 } 6017 } 6018 } 6019 6020 // Lower this FP comparison into an appropriate integer version of the 6021 // comparison. 6022 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt); 6023 } 6024 6025 /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary. 6026 static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, 6027 Constant *RHSC) { 6028 // When C is not 0.0 and infinities are not allowed: 6029 // (C / X) < 0.0 is a sign-bit test of X 6030 // (C / X) < 0.0 --> X < 0.0 (if C is positive) 6031 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate) 6032 // 6033 // Proof: 6034 // Multiply (C / X) < 0.0 by X * X / C. 6035 // - X is non zero, if it is the flag 'ninf' is violated. 6036 // - C defines the sign of X * X * C. Thus it also defines whether to swap 6037 // the predicate. C is also non zero by definition. 6038 // 6039 // Thus X * X / C is non zero and the transformation is valid. [qed] 6040 6041 FCmpInst::Predicate Pred = I.getPredicate(); 6042 6043 // Check that predicates are valid. 6044 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) && 6045 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE)) 6046 return nullptr; 6047 6048 // Check that RHS operand is zero. 6049 if (!match(RHSC, m_AnyZeroFP())) 6050 return nullptr; 6051 6052 // Check fastmath flags ('ninf'). 6053 if (!LHSI->hasNoInfs() || !I.hasNoInfs()) 6054 return nullptr; 6055 6056 // Check the properties of the dividend. It must not be zero to avoid a 6057 // division by zero (see Proof). 6058 const APFloat *C; 6059 if (!match(LHSI->getOperand(0), m_APFloat(C))) 6060 return nullptr; 6061 6062 if (C->isZero()) 6063 return nullptr; 6064 6065 // Get swapped predicate if necessary. 6066 if (C->isNegative()) 6067 Pred = I.getSwappedPredicate(); 6068 6069 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I); 6070 } 6071 6072 /// Optimize fabs(X) compared with zero. 6073 static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) { 6074 Value *X; 6075 if (!match(I.getOperand(0), m_Intrinsic<Intrinsic::fabs>(m_Value(X))) || 6076 !match(I.getOperand(1), m_PosZeroFP())) 6077 return nullptr; 6078 6079 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) { 6080 I->setPredicate(P); 6081 return IC.replaceOperand(*I, 0, X); 6082 }; 6083 6084 switch (I.getPredicate()) { 6085 case FCmpInst::FCMP_UGE: 6086 case FCmpInst::FCMP_OLT: 6087 // fabs(X) >= 0.0 --> true 6088 // fabs(X) < 0.0 --> false 6089 llvm_unreachable("fcmp should have simplified"); 6090 6091 case FCmpInst::FCMP_OGT: 6092 // fabs(X) > 0.0 --> X != 0.0 6093 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X); 6094 6095 case FCmpInst::FCMP_UGT: 6096 // fabs(X) u> 0.0 --> X u!= 0.0 6097 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X); 6098 6099 case FCmpInst::FCMP_OLE: 6100 // fabs(X) <= 0.0 --> X == 0.0 6101 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X); 6102 6103 case FCmpInst::FCMP_ULE: 6104 // fabs(X) u<= 0.0 --> X u== 0.0 6105 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X); 6106 6107 case FCmpInst::FCMP_OGE: 6108 // fabs(X) >= 0.0 --> !isnan(X) 6109 assert(!I.hasNoNaNs() && "fcmp should have simplified"); 6110 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X); 6111 6112 case FCmpInst::FCMP_ULT: 6113 // fabs(X) u< 0.0 --> isnan(X) 6114 assert(!I.hasNoNaNs() && "fcmp should have simplified"); 6115 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X); 6116 6117 case FCmpInst::FCMP_OEQ: 6118 case FCmpInst::FCMP_UEQ: 6119 case FCmpInst::FCMP_ONE: 6120 case FCmpInst::FCMP_UNE: 6121 case FCmpInst::FCMP_ORD: 6122 case FCmpInst::FCMP_UNO: 6123 // Look through the fabs() because it doesn't change anything but the sign. 6124 // fabs(X) == 0.0 --> X == 0.0, 6125 // fabs(X) != 0.0 --> X != 0.0 6126 // isnan(fabs(X)) --> isnan(X) 6127 // !isnan(fabs(X) --> !isnan(X) 6128 return replacePredAndOp0(&I, I.getPredicate(), X); 6129 6130 default: 6131 return nullptr; 6132 } 6133 } 6134 6135 Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) { 6136 bool Changed = false; 6137 6138 /// Orders the operands of the compare so that they are listed from most 6139 /// complex to least complex. This puts constants before unary operators, 6140 /// before binary operators. 6141 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) { 6142 I.swapOperands(); 6143 Changed = true; 6144 } 6145 6146 const CmpInst::Predicate Pred = I.getPredicate(); 6147 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 6148 if (Value *V = SimplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(), 6149 SQ.getWithInstruction(&I))) 6150 return replaceInstUsesWith(I, V); 6151 6152 // Simplify 'fcmp pred X, X' 6153 Type *OpType = Op0->getType(); 6154 assert(OpType == Op1->getType() && "fcmp with different-typed operands?"); 6155 if (Op0 == Op1) { 6156 switch (Pred) { 6157 default: break; 6158 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y) 6159 case FCmpInst::FCMP_ULT: // True if unordered or less than 6160 case FCmpInst::FCMP_UGT: // True if unordered or greater than 6161 case FCmpInst::FCMP_UNE: // True if unordered or not equal 6162 // Canonicalize these to be 'fcmp uno %X, 0.0'. 6163 I.setPredicate(FCmpInst::FCMP_UNO); 6164 I.setOperand(1, Constant::getNullValue(OpType)); 6165 return &I; 6166 6167 case FCmpInst::FCMP_ORD: // True if ordered (no nans) 6168 case FCmpInst::FCMP_OEQ: // True if ordered and equal 6169 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal 6170 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal 6171 // Canonicalize these to be 'fcmp ord %X, 0.0'. 6172 I.setPredicate(FCmpInst::FCMP_ORD); 6173 I.setOperand(1, Constant::getNullValue(OpType)); 6174 return &I; 6175 } 6176 } 6177 6178 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand, 6179 // then canonicalize the operand to 0.0. 6180 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) { 6181 if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI)) 6182 return replaceOperand(I, 0, ConstantFP::getNullValue(OpType)); 6183 6184 if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI)) 6185 return replaceOperand(I, 1, ConstantFP::getNullValue(OpType)); 6186 } 6187 6188 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y 6189 Value *X, *Y; 6190 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y)))) 6191 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I); 6192 6193 // Test if the FCmpInst instruction is used exclusively by a select as 6194 // part of a minimum or maximum operation. If so, refrain from doing 6195 // any other folding. This helps out other analyses which understand 6196 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution 6197 // and CodeGen. And in this case, at least one of the comparison 6198 // operands has at least one user besides the compare (the select), 6199 // which would often largely negate the benefit of folding anyway. 6200 if (I.hasOneUse()) 6201 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) { 6202 Value *A, *B; 6203 SelectPatternResult SPR = matchSelectPattern(SI, A, B); 6204 if (SPR.Flavor != SPF_UNKNOWN) 6205 return nullptr; 6206 } 6207 6208 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0: 6209 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0 6210 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP())) 6211 return replaceOperand(I, 1, ConstantFP::getNullValue(OpType)); 6212 6213 // Handle fcmp with instruction LHS and constant RHS. 6214 Instruction *LHSI; 6215 Constant *RHSC; 6216 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) { 6217 switch (LHSI->getOpcode()) { 6218 case Instruction::PHI: 6219 // Only fold fcmp into the PHI if the phi and fcmp are in the same 6220 // block. If in the same block, we're encouraging jump threading. If 6221 // not, we are just pessimizing the code by making an i1 phi. 6222 if (LHSI->getParent() == I.getParent()) 6223 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI))) 6224 return NV; 6225 break; 6226 case Instruction::SIToFP: 6227 case Instruction::UIToFP: 6228 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC)) 6229 return NV; 6230 break; 6231 case Instruction::FDiv: 6232 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC)) 6233 return NV; 6234 break; 6235 case Instruction::Load: 6236 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) 6237 if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) 6238 if (GV->isConstant() && GV->hasDefinitiveInitializer() && 6239 !cast<LoadInst>(LHSI)->isVolatile()) 6240 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(GEP, GV, I)) 6241 return Res; 6242 break; 6243 } 6244 } 6245 6246 if (Instruction *R = foldFabsWithFcmpZero(I, *this)) 6247 return R; 6248 6249 if (match(Op0, m_FNeg(m_Value(X)))) { 6250 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C 6251 Constant *C; 6252 if (match(Op1, m_Constant(C))) { 6253 Constant *NegC = ConstantExpr::getFNeg(C); 6254 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I); 6255 } 6256 } 6257 6258 if (match(Op0, m_FPExt(m_Value(X)))) { 6259 // fcmp (fpext X), (fpext Y) -> fcmp X, Y 6260 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType()) 6261 return new FCmpInst(Pred, X, Y, "", &I); 6262 6263 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless 6264 const APFloat *C; 6265 if (match(Op1, m_APFloat(C))) { 6266 const fltSemantics &FPSem = 6267 X->getType()->getScalarType()->getFltSemantics(); 6268 bool Lossy; 6269 APFloat TruncC = *C; 6270 TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy); 6271 6272 // Avoid lossy conversions and denormals. 6273 // Zero is a special case that's OK to convert. 6274 APFloat Fabs = TruncC; 6275 Fabs.clearSign(); 6276 if (!Lossy && 6277 (!(Fabs < APFloat::getSmallestNormalized(FPSem)) || Fabs.isZero())) { 6278 Constant *NewC = ConstantFP::get(X->getType(), TruncC); 6279 return new FCmpInst(Pred, X, NewC, "", &I); 6280 } 6281 } 6282 } 6283 6284 if (I.getType()->isVectorTy()) 6285 if (Instruction *Res = foldVectorCmp(I, Builder)) 6286 return Res; 6287 6288 return Changed ? &I : nullptr; 6289 } 6290