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