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/APFloat.h"
15#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/CaptureTracking.h"
19#include "llvm/Analysis/CmpInstAnalysis.h"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/Loads.h"
23#include "llvm/Analysis/Utils/Local.h"
24#include "llvm/Analysis/VectorUtils.h"
25#include "llvm/IR/ConstantRange.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/PatternMatch.h"
33#include "llvm/Support/KnownBits.h"
34#include "llvm/Transforms/InstCombine/InstCombiner.h"
35#include <bitset>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42// How many times is a select replaced by one of its operands?
43STATISTIC(NumSel, "Number of select opts");
44
45/// Compute Result = In1+In2, returning true if the result overflowed for this
46/// type.
47static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
48 bool IsSigned = false) {
49 bool Overflow;
50 if (IsSigned)
51 Result = In1.sadd_ov(RHS: In2, Overflow);
52 else
53 Result = In1.uadd_ov(RHS: In2, Overflow);
54
55 return Overflow;
56}
57
58/// Compute Result = In1-In2, returning true if the result overflowed for this
59/// type.
60static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
61 bool IsSigned = false) {
62 bool Overflow;
63 if (IsSigned)
64 Result = In1.ssub_ov(RHS: In2, Overflow);
65 else
66 Result = In1.usub_ov(RHS: In2, Overflow);
67
68 return Overflow;
69}
70
71/// Given an icmp instruction, return true if any use of this comparison is a
72/// branch on sign bit comparison.
73static bool hasBranchUse(ICmpInst &I) {
74 for (auto *U : I.users())
75 if (isa<CondBrInst>(Val: U))
76 return true;
77 return false;
78}
79
80/// Returns true if the exploded icmp can be expressed as a signed comparison
81/// to zero and updates the predicate accordingly.
82/// The signedness of the comparison is preserved.
83/// TODO: Refactor with decomposeBitTestICmp()?
84static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
85 if (!ICmpInst::isSigned(Pred))
86 return false;
87
88 if (C.isZero())
89 return ICmpInst::isRelational(P: Pred);
90
91 if (C.isOne()) {
92 if (Pred == ICmpInst::ICMP_SLT) {
93 Pred = ICmpInst::ICMP_SLE;
94 return true;
95 }
96 } else if (C.isAllOnes()) {
97 if (Pred == ICmpInst::ICMP_SGT) {
98 Pred = ICmpInst::ICMP_SGE;
99 return true;
100 }
101 }
102
103 return false;
104}
105
106/// This is called when we see this pattern:
107/// cmp pred (load (gep GV, ...)), cmpcst
108/// where GV is a global variable with a constant initializer. Try to simplify
109/// this into some simple computation that does not need the load. For example
110/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
111///
112/// If AndCst is non-null, then the loaded value is masked with that constant
113/// before doing the comparison. This handles cases like "A[i]&4 == 0".
114///
115/// We allow multi-use cases in this fold, even though it can increase
116/// instruction count, because it appears to be mostly beneficial in practice.
117/// Even if there are multiple uses, they can often be sunk into the block
118/// guarded by the icmp.
119Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
120 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
121 auto *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: GEP));
122 if (LI->isVolatile() || !GV || !GV->isConstant() ||
123 !GV->hasDefinitiveInitializer())
124 return nullptr;
125
126 Type *EltTy = LI->getType();
127 TypeSize EltSize = DL.getTypeStoreSize(Ty: EltTy);
128 if (EltSize.isScalable())
129 return nullptr;
130
131 LinearExpression Expr = decomposeLinearExpression(DL, Ptr: GEP);
132 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
133 return nullptr;
134
135 Constant *Init = GV->getInitializer();
136 TypeSize GlobalSize = DL.getTypeAllocSize(Ty: Init->getType());
137
138 Value *Idx = Expr.Index;
139 const APInt &Stride = Expr.Scale;
140 const APInt &ConstOffset = Expr.Offset;
141
142 // Allow an additional context offset, but only within the stride.
143 if (!ConstOffset.ult(RHS: Stride))
144 return nullptr;
145
146 // Don't handle overlapping loads for now.
147 if (!Stride.uge(RHS: EltSize.getFixedValue()))
148 return nullptr;
149
150 // Don't blow up on huge arrays.
151 uint64_t ArrayElementCount =
152 divideCeil(Numerator: (GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
153 Denominator: Stride.getZExtValue());
154 if (ArrayElementCount > MaxArraySizeForCombine)
155 return nullptr;
156
157 enum { Overdefined = -3, Undefined = -2 };
158
159 // Variables for our state machines.
160
161 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
162 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
163 // and 87 is the second (and last) index. FirstTrueElement is -2 when
164 // undefined, otherwise set to the first true element. SecondTrueElement is
165 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
166 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
167
168 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
169 // form "i != 47 & i != 87". Same state transitions as for true elements.
170 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
171
172 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
173 /// define a state machine that triggers for ranges of values that the index
174 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
175 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
176 /// index in the range (inclusive). We use -2 for undefined here because we
177 /// use relative comparisons and don't want 0-1 to match -1.
178 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
179
180 // MagicBitvector - This is a magic bitvector where we set a bit if the
181 // comparison is true for element 'i'. If there are 64 elements or less in
182 // the array, this will fully represent all the comparison results.
183 uint64_t MagicBitvector = 0;
184
185 // Scan the array and see if one of our patterns matches.
186 Constant *CompareRHS = cast<Constant>(Val: ICI.getOperand(i_nocapture: 1));
187 APInt Offset = ConstOffset;
188 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
189 Constant *Elt = ConstantFoldLoadFromConst(C: Init, Ty: EltTy, Offset, DL);
190 if (!Elt)
191 return nullptr;
192
193 // If the element is masked, handle it.
194 if (AndCst) {
195 Elt = ConstantFoldBinaryOpOperands(Opcode: Instruction::And, LHS: Elt, RHS: AndCst, DL);
196 if (!Elt)
197 return nullptr;
198 }
199
200 // Find out if the comparison would be true or false for the i'th element.
201 Constant *C = ConstantFoldCompareInstOperands(Predicate: ICI.getPredicate(), LHS: Elt,
202 RHS: CompareRHS, DL, TLI: &TLI);
203 if (!C)
204 return nullptr;
205
206 // If the result is undef for this element, ignore it.
207 if (isa<UndefValue>(Val: C)) {
208 // Extend range state machines to cover this element in case there is an
209 // undef in the middle of the range.
210 if (TrueRangeEnd == (int)i - 1)
211 TrueRangeEnd = i;
212 if (FalseRangeEnd == (int)i - 1)
213 FalseRangeEnd = i;
214 continue;
215 }
216
217 // If we can't compute the result for any of the elements, we have to give
218 // up evaluating the entire conditional.
219 if (!isa<ConstantInt>(Val: C))
220 return nullptr;
221
222 // Otherwise, we know if the comparison is true or false for this element,
223 // update our state machines.
224 bool IsTrueForElt = !cast<ConstantInt>(Val: C)->isZero();
225
226 // State machine for single/double/range index comparison.
227 if (IsTrueForElt) {
228 // Update the TrueElement state machine.
229 if (FirstTrueElement == Undefined)
230 FirstTrueElement = TrueRangeEnd = i; // First true element.
231 else {
232 // Update double-compare state machine.
233 if (SecondTrueElement == Undefined)
234 SecondTrueElement = i;
235 else
236 SecondTrueElement = Overdefined;
237
238 // Update range state machine.
239 if (TrueRangeEnd == (int)i - 1)
240 TrueRangeEnd = i;
241 else
242 TrueRangeEnd = Overdefined;
243 }
244 } else {
245 // Update the FalseElement state machine.
246 if (FirstFalseElement == Undefined)
247 FirstFalseElement = FalseRangeEnd = i; // First false element.
248 else {
249 // Update double-compare state machine.
250 if (SecondFalseElement == Undefined)
251 SecondFalseElement = i;
252 else
253 SecondFalseElement = Overdefined;
254
255 // Update range state machine.
256 if (FalseRangeEnd == (int)i - 1)
257 FalseRangeEnd = i;
258 else
259 FalseRangeEnd = Overdefined;
260 }
261 }
262
263 // If this element is in range, update our magic bitvector.
264 if (i < 64 && IsTrueForElt)
265 MagicBitvector |= 1ULL << i;
266
267 // If all of our states become overdefined, bail out early. Since the
268 // predicate is expensive, only check it every 8 elements. This is only
269 // really useful for really huge arrays.
270 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
271 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
272 FalseRangeEnd == Overdefined)
273 return nullptr;
274 }
275
276 // Now that we've scanned the entire array, emit our new comparison(s). We
277 // order the state machines in complexity of the generated code.
278
279 // If inbounds keyword is not present, Idx * Stride can overflow.
280 // Let's assume that Stride is 2 and the wanted value is at offset 0.
281 // Then, there are two possible values for Idx to match offset 0:
282 // 0x00..00, 0x80..00.
283 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
284 // comparison is false if Idx was 0x80..00.
285 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
286 auto MaskIdx = [&](Value *Idx) {
287 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
288 Value *Mask = Constant::getAllOnesValue(Ty: Idx->getType());
289 Mask = Builder.CreateLShr(LHS: Mask, RHS: Stride.countr_zero());
290 Idx = Builder.CreateAnd(LHS: Idx, RHS: Mask);
291 }
292 return Idx;
293 };
294
295 // If the comparison is only true for one or two elements, emit direct
296 // comparisons.
297 if (SecondTrueElement != Overdefined) {
298 Idx = MaskIdx(Idx);
299 // None true -> false.
300 if (FirstTrueElement == Undefined)
301 return replaceInstUsesWith(I&: ICI, V: Builder.getFalse());
302
303 Value *FirstTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstTrueElement);
304
305 // True for one element -> 'i == 47'.
306 if (SecondTrueElement == Undefined)
307 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
308
309 // True for two elements -> 'i == 47 | i == 72'.
310 Value *C1 = Builder.CreateICmpEQ(LHS: Idx, RHS: FirstTrueIdx);
311 Value *SecondTrueIdx = ConstantInt::get(Ty: Idx->getType(), V: SecondTrueElement);
312 Value *C2 = Builder.CreateICmpEQ(LHS: Idx, RHS: SecondTrueIdx);
313 return BinaryOperator::CreateOr(V1: C1, V2: C2);
314 }
315
316 // If the comparison is only false for one or two elements, emit direct
317 // comparisons.
318 if (SecondFalseElement != Overdefined) {
319 Idx = MaskIdx(Idx);
320 // None false -> true.
321 if (FirstFalseElement == Undefined)
322 return replaceInstUsesWith(I&: ICI, V: Builder.getTrue());
323
324 Value *FirstFalseIdx = ConstantInt::get(Ty: Idx->getType(), V: FirstFalseElement);
325
326 // False for one element -> 'i != 47'.
327 if (SecondFalseElement == Undefined)
328 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
329
330 // False for two elements -> 'i != 47 & i != 72'.
331 Value *C1 = Builder.CreateICmpNE(LHS: Idx, RHS: FirstFalseIdx);
332 Value *SecondFalseIdx =
333 ConstantInt::get(Ty: Idx->getType(), V: SecondFalseElement);
334 Value *C2 = Builder.CreateICmpNE(LHS: Idx, RHS: SecondFalseIdx);
335 return BinaryOperator::CreateAnd(V1: C1, V2: C2);
336 }
337
338 // If the comparison can be replaced with a range comparison for the elements
339 // where it is true, emit the range check.
340 if (TrueRangeEnd != Overdefined) {
341 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
342 Idx = MaskIdx(Idx);
343
344 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
345 if (FirstTrueElement) {
346 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstTrueElement);
347 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
348 }
349
350 Value *End =
351 ConstantInt::get(Ty: Idx->getType(), V: TrueRangeEnd - FirstTrueElement + 1);
352 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
353 }
354
355 // False range check.
356 if (FalseRangeEnd != Overdefined) {
357 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
358 Idx = MaskIdx(Idx);
359 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
360 if (FirstFalseElement) {
361 Value *Offs = ConstantInt::getSigned(Ty: Idx->getType(), V: -FirstFalseElement);
362 Idx = Builder.CreateAdd(LHS: Idx, RHS: Offs);
363 }
364
365 Value *End =
366 ConstantInt::get(Ty: Idx->getType(), V: FalseRangeEnd - FirstFalseElement);
367 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
368 }
369
370 // If a magic bitvector captures the entire comparison state
371 // of this load, replace it with computation that does:
372 // ((magic_cst >> i) & 1) != 0
373 {
374 Type *Ty = nullptr;
375
376 // Look for an appropriate type:
377 // - The type of Idx if the magic fits
378 // - The smallest fitting legal type
379 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
380 Ty = Idx->getType();
381 else
382 Ty = DL.getSmallestLegalIntType(C&: Init->getContext(), Width: ArrayElementCount);
383
384 if (Ty) {
385 Idx = MaskIdx(Idx);
386 Value *V = Builder.CreateIntCast(V: Idx, DestTy: Ty, isSigned: false);
387 V = Builder.CreateLShr(LHS: ConstantInt::get(Ty, V: MagicBitvector), RHS: V);
388 V = Builder.CreateAnd(LHS: ConstantInt::get(Ty, V: 1), RHS: V);
389 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, V: 0));
390 }
391 }
392
393 return nullptr;
394}
395
396/// Returns true if we can rewrite Start as a GEP with pointer Base
397/// and some integer offset. The nodes that need to be re-written
398/// for this transformation will be added to Explored.
399static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW,
400 const DataLayout &DL,
401 SetVector<Value *> &Explored) {
402 SmallVector<Value *, 16> WorkList(1, Start);
403 Explored.insert(X: Base);
404
405 // The following traversal gives us an order which can be used
406 // when doing the final transformation. Since in the final
407 // transformation we create the PHI replacement instructions first,
408 // we don't have to get them in any particular order.
409 //
410 // However, for other instructions we will have to traverse the
411 // operands of an instruction first, which means that we have to
412 // do a post-order traversal.
413 while (!WorkList.empty()) {
414 SetVector<PHINode *> PHIs;
415
416 while (!WorkList.empty()) {
417 if (Explored.size() >= 100)
418 return false;
419
420 Value *V = WorkList.back();
421
422 if (Explored.contains(key: V)) {
423 WorkList.pop_back();
424 continue;
425 }
426
427 if (!isa<GetElementPtrInst>(Val: V) && !isa<PHINode>(Val: V))
428 // We've found some value that we can't explore which is different from
429 // the base. Therefore we can't do this transformation.
430 return false;
431
432 if (auto *GEP = dyn_cast<GEPOperator>(Val: V)) {
433 // Only allow inbounds GEPs with at most one variable offset.
434 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(Val: V); };
435 if (!GEP->isInBounds() || count_if(Range: GEP->indices(), P: IsNonConst) > 1)
436 return false;
437
438 NW = NW.intersectForOffsetAdd(Other: GEP->getNoWrapFlags());
439 if (!Explored.contains(key: GEP->getOperand(i_nocapture: 0)))
440 WorkList.push_back(Elt: GEP->getOperand(i_nocapture: 0));
441 }
442
443 if (WorkList.back() == V) {
444 WorkList.pop_back();
445 // We've finished visiting this node, mark it as such.
446 Explored.insert(X: V);
447 }
448
449 if (auto *PN = dyn_cast<PHINode>(Val: V)) {
450 // We cannot transform PHIs on unsplittable basic blocks.
451 if (isa<CatchSwitchInst>(Val: PN->getParent()->getTerminator()))
452 return false;
453 Explored.insert(X: PN);
454 PHIs.insert(X: PN);
455 }
456 }
457
458 // Explore the PHI nodes further.
459 for (auto *PN : PHIs)
460 for (Value *Op : PN->incoming_values())
461 if (!Explored.contains(key: Op))
462 WorkList.push_back(Elt: Op);
463 }
464
465 // Make sure that we can do this. Since we can't insert GEPs in a basic
466 // block before a PHI node, we can't easily do this transformation if
467 // we have PHI node users of transformed instructions.
468 for (Value *Val : Explored) {
469 for (Value *Use : Val->uses()) {
470
471 auto *PHI = dyn_cast<PHINode>(Val: Use);
472 auto *Inst = dyn_cast<Instruction>(Val);
473
474 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
475 !Explored.contains(key: PHI))
476 continue;
477
478 if (PHI->getParent() == Inst->getParent())
479 return false;
480 }
481 }
482 return true;
483}
484
485// Sets the appropriate insert point on Builder where we can add
486// a replacement Instruction for V (if that is possible).
487static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
488 bool Before = true) {
489 if (auto *PHI = dyn_cast<PHINode>(Val: V)) {
490 BasicBlock *Parent = PHI->getParent();
491 Builder.SetInsertPoint(TheBB: Parent, IP: Parent->getFirstInsertionPt());
492 return;
493 }
494 if (auto *I = dyn_cast<Instruction>(Val: V)) {
495 if (!Before)
496 I = &*std::next(x: I->getIterator());
497 Builder.SetInsertPoint(I);
498 return;
499 }
500 if (auto *A = dyn_cast<Argument>(Val: V)) {
501 // Set the insertion point in the entry block.
502 BasicBlock &Entry = A->getParent()->getEntryBlock();
503 Builder.SetInsertPoint(TheBB: &Entry, IP: Entry.getFirstInsertionPt());
504 return;
505 }
506 // Otherwise, this is a constant and we don't need to set a new
507 // insertion point.
508 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
509}
510
511/// Returns a re-written value of Start as an indexed GEP using Base as a
512/// pointer.
513static Value *rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW,
514 const DataLayout &DL,
515 SetVector<Value *> &Explored,
516 InstCombiner &IC) {
517 // Perform all the substitutions. This is a bit tricky because we can
518 // have cycles in our use-def chains.
519 // 1. Create the PHI nodes without any incoming values.
520 // 2. Create all the other values.
521 // 3. Add the edges for the PHI nodes.
522 // 4. Emit GEPs to get the original pointers.
523 // 5. Remove the original instructions.
524 Type *IndexType = IntegerType::get(
525 C&: Base->getContext(), NumBits: DL.getIndexTypeSizeInBits(Ty: Start->getType()));
526
527 DenseMap<Value *, Value *> NewInsts;
528 NewInsts[Base] = ConstantInt::getNullValue(Ty: IndexType);
529
530 // Create the new PHI nodes, without adding any incoming values.
531 for (Value *Val : Explored) {
532 if (Val == Base)
533 continue;
534 // Create empty phi nodes. This avoids cyclic dependencies when creating
535 // the remaining instructions.
536 if (auto *PHI = dyn_cast<PHINode>(Val))
537 NewInsts[PHI] =
538 PHINode::Create(Ty: IndexType, NumReservedValues: PHI->getNumIncomingValues(),
539 NameStr: PHI->getName() + ".idx", InsertBefore: PHI->getIterator());
540 }
541 IRBuilder<> Builder(Base->getContext());
542
543 // Create all the other instructions.
544 for (Value *Val : Explored) {
545 if (NewInsts.contains(Val))
546 continue;
547
548 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
549 setInsertionPoint(Builder, V: GEP);
550 Value *Op = NewInsts[GEP->getOperand(i_nocapture: 0)];
551 Value *OffsetV = emitGEPOffset(Builder: &Builder, DL, GEP);
552 if (isa<ConstantInt>(Val: Op) && cast<ConstantInt>(Val: Op)->isZero())
553 NewInsts[GEP] = OffsetV;
554 else
555 NewInsts[GEP] = Builder.CreateAdd(
556 LHS: Op, RHS: OffsetV, Name: GEP->getOperand(i_nocapture: 0)->getName() + ".add",
557 /*NUW=*/HasNUW: NW.hasNoUnsignedWrap(),
558 /*NSW=*/HasNSW: NW.hasNoUnsignedSignedWrap());
559 continue;
560 }
561 if (isa<PHINode>(Val))
562 continue;
563
564 llvm_unreachable("Unexpected instruction type");
565 }
566
567 // Add the incoming values to the PHI nodes.
568 for (Value *Val : Explored) {
569 if (Val == Base)
570 continue;
571 // All the instructions have been created, we can now add edges to the
572 // phi nodes.
573 if (auto *PHI = dyn_cast<PHINode>(Val)) {
574 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
575 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
576 Value *NewIncoming = PHI->getIncomingValue(i: I);
577
578 auto It = NewInsts.find(Val: NewIncoming);
579 if (It != NewInsts.end())
580 NewIncoming = It->second;
581
582 NewPhi->addIncoming(V: NewIncoming, BB: PHI->getIncomingBlock(i: I));
583 }
584 }
585 }
586
587 for (Value *Val : Explored) {
588 if (Val == Base)
589 continue;
590
591 setInsertionPoint(Builder, V: Val, Before: false);
592 // Create GEP for external users.
593 Value *NewVal = Builder.CreateGEP(Ty: Builder.getInt8Ty(), Ptr: Base, IdxList: NewInsts[Val],
594 Name: Val->getName() + ".ptr", NW);
595 IC.replaceInstUsesWith(I&: *cast<Instruction>(Val), V: NewVal);
596 // Add old instruction to worklist for DCE. We don't directly remove it
597 // here because the original compare is one of the users.
598 IC.addToWorklist(I: cast<Instruction>(Val));
599 }
600
601 return NewInsts[Start];
602}
603
604/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
605/// We can look through PHIs, GEPs and casts in order to determine a common base
606/// between GEPLHS and RHS.
607static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
608 CmpPredicate Cond,
609 const DataLayout &DL,
610 InstCombiner &IC) {
611 // FIXME: Support vector of pointers.
612 if (GEPLHS->getType()->isVectorTy())
613 return nullptr;
614
615 if (!GEPLHS->hasAllConstantIndices())
616 return nullptr;
617
618 APInt Offset(DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType()), 0);
619 Value *PtrBase =
620 GEPLHS->stripAndAccumulateConstantOffsets(DL, Offset,
621 /*AllowNonInbounds*/ false);
622
623 // Bail if we looked through addrspacecast.
624 if (PtrBase->getType() != GEPLHS->getType())
625 return nullptr;
626
627 // The set of nodes that will take part in this transformation.
628 SetVector<Value *> Nodes;
629 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
630 if (!canRewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes))
631 return nullptr;
632
633 // We know we can re-write this as
634 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
635 // Since we've only looked through inbouds GEPs we know that we
636 // can't have overflow on either side. We can therefore re-write
637 // this as:
638 // OFFSET1 cmp OFFSET2
639 Value *NewRHS = rewriteGEPAsOffset(Start: RHS, Base: PtrBase, NW, DL, Explored&: Nodes, IC);
640
641 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
642 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
643 // offset. Since Index is the offset of LHS to the base pointer, we will now
644 // compare the offsets instead of comparing the pointers.
645 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond),
646 IC.Builder.getInt(AI: Offset), NewRHS);
647}
648
649/// Fold comparisons between a GEP instruction and something else. At this point
650/// we know that the GEP is on the LHS of the comparison.
651Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
652 CmpPredicate Cond, Instruction &I) {
653 // Don't transform signed compares of GEPs into index compares. Even if the
654 // GEP is inbounds, the final add of the base pointer can have signed overflow
655 // and would change the result of the icmp.
656 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
657 // the maximum signed value for the pointer type.
658 if (ICmpInst::isSigned(Pred: Cond))
659 return nullptr;
660
661 // Look through bitcasts and addrspacecasts. We do not however want to remove
662 // 0 GEPs.
663 if (!isa<GetElementPtrInst>(Val: RHS))
664 RHS = RHS->stripPointerCasts();
665
666 auto CanFold = [Cond](GEPNoWrapFlags NW) {
667 if (ICmpInst::isEquality(P: Cond))
668 return true;
669
670 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
671 assert(ICmpInst::isUnsigned(Cond));
672 return NW != GEPNoWrapFlags::none();
673 };
674
675 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
676 if (!NW.hasNoUnsignedWrap()) {
677 // Convert signed to unsigned comparison.
678 return new ICmpInst(ICmpInst::getSignedPredicate(Pred: Cond), Op1, Op2);
679 }
680
681 auto *I = new ICmpInst(Cond, Op1, Op2);
682 I->setSameSign(NW.hasNoUnsignedSignedWrap());
683 return I;
684 };
685
686 CommonPointerBase Base = CommonPointerBase::compute(LHS: GEPLHS, RHS);
687 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
688 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
689 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
690 Value *Offset =
691 EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
692 return NewICmp(Base.LHSNW, Offset,
693 Constant::getNullValue(Ty: Offset->getType()));
694 }
695
696 if (GEPLHS->isInBounds() && ICmpInst::isEquality(P: Cond) &&
697 isa<ConstantPointerNull>(Val: RHS) &&
698 !NullPointerIsDefined(F: I.getFunction(),
699 AS: RHS->getType()->getPointerAddressSpace())) {
700 // For most address spaces, an allocation can't be placed at null, but null
701 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
702 // the only valid inbounds address derived from null, is null itself.
703 // Thus, we have four cases to consider:
704 // 1) Base == nullptr, Offset == 0 -> inbounds, null
705 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
706 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
707 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
708 //
709 // (Note if we're indexing a type of size 0, that simply collapses into one
710 // of the buckets above.)
711 //
712 // In general, we're allowed to make values less poison (i.e. remove
713 // sources of full UB), so in this case, we just select between the two
714 // non-poison cases (1 and 4 above).
715 //
716 // For vectors, we apply the same reasoning on a per-lane basis.
717 auto *Base = GEPLHS->getPointerOperand();
718 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
719 auto EC = cast<VectorType>(Val: GEPLHS->getType())->getElementCount();
720 Base = Builder.CreateVectorSplat(EC, V: Base);
721 }
722 return new ICmpInst(Cond, Base,
723 ConstantExpr::getPointerBitCastOrAddrSpaceCast(
724 C: cast<Constant>(Val: RHS), Ty: Base->getType()));
725 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(Val: RHS)) {
726 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
727
728 // If the base pointers are different, but the indices are the same, just
729 // compare the base pointer.
730 if (GEPLHS->getOperand(i_nocapture: 0) != GEPRHS->getOperand(i_nocapture: 0)) {
731 bool IndicesTheSame =
732 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
733 GEPLHS->getPointerOperand()->getType() ==
734 GEPRHS->getPointerOperand()->getType() &&
735 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
736 if (IndicesTheSame)
737 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
738 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
739 IndicesTheSame = false;
740 break;
741 }
742
743 // If all indices are the same, just compare the base pointers.
744 Type *BaseType = GEPLHS->getOperand(i_nocapture: 0)->getType();
745 if (IndicesTheSame &&
746 CmpInst::makeCmpResultType(opnd_type: BaseType) == I.getType() && CanFold(NW))
747 return new ICmpInst(Cond, GEPLHS->getOperand(i_nocapture: 0), GEPRHS->getOperand(i_nocapture: 0));
748
749 // If we're comparing GEPs with two base pointers that only differ in type
750 // and both GEPs have only constant indices or just one use, then fold
751 // the compare with the adjusted indices.
752 // FIXME: Support vector of pointers.
753 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
754 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
755 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
756 GEPLHS->getOperand(i_nocapture: 0)->stripPointerCasts() ==
757 GEPRHS->getOperand(i_nocapture: 0)->stripPointerCasts() &&
758 !GEPLHS->getType()->isVectorTy()) {
759 Value *LOffset = EmitGEPOffset(GEP: GEPLHS);
760 Value *ROffset = EmitGEPOffset(GEP: GEPRHS);
761
762 // If we looked through an addrspacecast between different sized address
763 // spaces, the LHS and RHS pointers are different sized
764 // integers. Truncate to the smaller one.
765 Type *LHSIndexTy = LOffset->getType();
766 Type *RHSIndexTy = ROffset->getType();
767 if (LHSIndexTy != RHSIndexTy) {
768 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
769 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
770 ROffset = Builder.CreateTrunc(V: ROffset, DestTy: LHSIndexTy);
771 } else
772 LOffset = Builder.CreateTrunc(V: LOffset, DestTy: RHSIndexTy);
773 }
774
775 Value *Cmp = Builder.CreateICmp(P: ICmpInst::getSignedPredicate(Pred: Cond),
776 LHS: LOffset, RHS: ROffset);
777 return replaceInstUsesWith(I, V: Cmp);
778 }
779 }
780
781 if (GEPLHS->getOperand(i_nocapture: 0) == GEPRHS->getOperand(i_nocapture: 0) &&
782 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
783 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
784 // If the GEPs only differ by one index, compare it.
785 unsigned NumDifferences = 0; // Keep track of # differences.
786 unsigned DiffOperand = 0; // The operand that differs.
787 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
788 if (GEPLHS->getOperand(i_nocapture: i) != GEPRHS->getOperand(i_nocapture: i)) {
789 Type *LHSType = GEPLHS->getOperand(i_nocapture: i)->getType();
790 Type *RHSType = GEPRHS->getOperand(i_nocapture: i)->getType();
791 // FIXME: Better support for vector of pointers.
792 if (LHSType->getPrimitiveSizeInBits() !=
793 RHSType->getPrimitiveSizeInBits() ||
794 (GEPLHS->getType()->isVectorTy() &&
795 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
796 // Irreconcilable differences.
797 NumDifferences = 2;
798 break;
799 }
800
801 if (NumDifferences++)
802 break;
803 DiffOperand = i;
804 }
805
806 if (NumDifferences == 0) // SAME GEP?
807 return replaceInstUsesWith(
808 I, // No comparison is needed here.
809 V: ConstantInt::get(Ty: I.getType(), V: ICmpInst::isTrueWhenEqual(predicate: Cond)));
810 // If two GEPs only differ by an index, compare them.
811 // Note that nowrap flags are always needed when comparing two indices.
812 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
813 Value *LHSV = GEPLHS->getOperand(i_nocapture: DiffOperand);
814 Value *RHSV = GEPRHS->getOperand(i_nocapture: DiffOperand);
815 return NewICmp(NW, LHSV, RHSV);
816 }
817 }
818
819 if (Base.Ptr && !Base.isExpensive()) {
820 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
821 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
822
823 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
824 // Without the flags, we can still fold if the offsets are constant and
825 // they cross the base's alignment boundary the same number of times, so
826 // either both arguments will wrap, or none of them will.
827 unsigned BW = DL.getIndexTypeSizeInBits(Ty: GEPLHS->getType());
828 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
829 APInt LOff(BW, 0);
830 APInt ROff(BW, 0);
831 if (GEPLHS->stripAndAccumulateConstantOffsets(
832 DL, Offset&: LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
833 RHS->stripAndAccumulateConstantOffsets(
834 DL, Offset&: ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
835 DoFold =
836 APIntOps::RoundingSDiv(A: LOff, B: Alignment, RM: APInt::Rounding::DOWN) ==
837 APIntOps::RoundingSDiv(A: ROff, B: Alignment, RM: APInt::Rounding::DOWN);
838 }
839
840 if (DoFold) {
841 Type *IdxTy = DL.getIndexType(PtrTy: GEPLHS->getType());
842 Value *L = EmitGEPOffsets(GEPs: Base.LHSGEPs, NW: Base.LHSNW, IdxTy,
843 /*RewriteGEP=*/RewriteGEPs: true);
844 Value *R = EmitGEPOffsets(GEPs: Base.RHSGEPs, NW: Base.RHSNW, IdxTy,
845 /*RewriteGEP=*/RewriteGEPs: true);
846 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
847 }
848 }
849 }
850
851 // Try convert this to an indexed compare by looking through PHIs/casts as a
852 // last resort.
853 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, IC&: *this);
854}
855
856bool InstCombinerImpl::foldAllocaCmp(AllocaInst *Alloca) {
857 // It would be tempting to fold away comparisons between allocas and any
858 // pointer not based on that alloca (e.g. an argument). However, even
859 // though such pointers cannot alias, they can still compare equal.
860 //
861 // But LLVM doesn't specify where allocas get their memory, so if the alloca
862 // doesn't escape we can argue that it's impossible to guess its value, and we
863 // can therefore act as if any such guesses are wrong.
864 //
865 // However, we need to ensure that this folding is consistent: We can't fold
866 // one comparison to false, and then leave a different comparison against the
867 // same value alone (as it might evaluate to true at runtime, leading to a
868 // contradiction). As such, this code ensures that all comparisons are folded
869 // at the same time, and there are no other escapes.
870
871 struct CmpCaptureTracker : public CaptureTracker {
872 AllocaInst *Alloca;
873 bool Captured = false;
874 /// The value of the map is a bit mask of which icmp operands the alloca is
875 /// used in.
876 SmallMapVector<ICmpInst *, unsigned, 4> ICmps;
877
878 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
879
880 void tooManyUses() override { Captured = true; }
881
882 Action captured(const Use *U, UseCaptureInfo CI) override {
883 // TODO(captures): Use UseCaptureInfo.
884 auto *ICmp = dyn_cast<ICmpInst>(Val: U->getUser());
885 // We need to check that U is based *only* on the alloca, and doesn't
886 // have other contributions from a select/phi operand.
887 // TODO: We could check whether getUnderlyingObjects() reduces to one
888 // object, which would allow looking through phi nodes.
889 if (ICmp && ICmp->isEquality() && getUnderlyingObject(V: *U) == Alloca) {
890 // Collect equality icmps of the alloca, and don't treat them as
891 // captures.
892 ICmps[ICmp] |= 1u << U->getOperandNo();
893 return Continue;
894 }
895
896 Captured = true;
897 return Stop;
898 }
899 };
900
901 CmpCaptureTracker Tracker(Alloca);
902 PointerMayBeCaptured(V: Alloca, Tracker: &Tracker);
903 if (Tracker.Captured)
904 return false;
905
906 bool Changed = false;
907 for (auto [ICmp, Operands] : Tracker.ICmps) {
908 switch (Operands) {
909 case 1:
910 case 2: {
911 // The alloca is only used in one icmp operand. Assume that the
912 // equality is false.
913 auto *Res = ConstantInt::get(Ty: ICmp->getType(),
914 V: ICmp->getPredicate() == ICmpInst::ICMP_NE);
915 replaceInstUsesWith(I&: *ICmp, V: Res);
916 eraseInstFromFunction(I&: *ICmp);
917 Changed = true;
918 break;
919 }
920 case 3:
921 // Both icmp operands are based on the alloca, so this is comparing
922 // pointer offsets, without leaking any information about the address
923 // of the alloca. Ignore such comparisons.
924 break;
925 default:
926 llvm_unreachable("Cannot happen");
927 }
928 }
929
930 return Changed;
931}
932
933/// Fold "icmp pred (X+C), X".
934Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
935 CmpPredicate Pred) {
936 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
937 // so the values can never be equal. Similarly for all other "or equals"
938 // operators.
939 assert(!!C && "C should not be zero!");
940
941 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
942 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
943 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
944 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
945 Constant *R =
946 ConstantInt::get(Ty: X->getType(), V: APInt::getMaxValue(numBits: C.getBitWidth()) - C);
947 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
948 }
949
950 // (X+1) >u X --> X <u (0-1) --> X != 255
951 // (X+2) >u X --> X <u (0-2) --> X <u 254
952 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
953 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
954 return new ICmpInst(ICmpInst::ICMP_ULT, X,
955 ConstantInt::get(Ty: X->getType(), V: -C));
956
957 APInt SMax = APInt::getSignedMaxValue(numBits: C.getBitWidth());
958
959 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
960 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
961 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
962 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
963 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
964 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
965 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
966 return new ICmpInst(ICmpInst::ICMP_SGT, X,
967 ConstantInt::get(Ty: X->getType(), V: SMax - C));
968
969 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
970 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
971 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
972 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
973 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
974 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
975
976 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
977 return new ICmpInst(ICmpInst::ICMP_SLT, X,
978 ConstantInt::get(Ty: X->getType(), V: SMax - (C - 1)));
979}
980
981/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
982/// (icmp eq/ne A, Log2(AP2/AP1)) ->
983/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
984Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
985 const APInt &AP1,
986 const APInt &AP2) {
987 assert(I.isEquality() && "Cannot fold icmp gt/lt");
988
989 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
990 if (I.getPredicate() == I.ICMP_NE)
991 Pred = CmpInst::getInversePredicate(pred: Pred);
992 return new ICmpInst(Pred, LHS, RHS);
993 };
994
995 // Don't bother doing any work for cases which InstSimplify handles.
996 if (AP2.isZero())
997 return nullptr;
998
999 bool IsAShr = isa<AShrOperator>(Val: I.getOperand(i_nocapture: 0));
1000 if (IsAShr) {
1001 if (AP2.isAllOnes())
1002 return nullptr;
1003 if (AP2.isNegative() != AP1.isNegative())
1004 return nullptr;
1005 if (AP2.sgt(RHS: AP1))
1006 return nullptr;
1007 }
1008
1009 if (!AP1)
1010 // 'A' must be large enough to shift out the highest set bit.
1011 return getICmp(I.ICMP_UGT, A,
1012 ConstantInt::get(Ty: A->getType(), V: AP2.logBase2()));
1013
1014 if (AP1 == AP2)
1015 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1016
1017 int Shift;
1018 if (IsAShr && AP1.isNegative())
1019 Shift = AP1.countl_one() - AP2.countl_one();
1020 else
1021 Shift = AP1.countl_zero() - AP2.countl_zero();
1022
1023 if (Shift > 0) {
1024 if (IsAShr && AP1 == AP2.ashr(ShiftAmt: Shift)) {
1025 // There are multiple solutions if we are comparing against -1 and the LHS
1026 // of the ashr is not a power of two.
1027 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1028 return getICmp(I.ICMP_UGE, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1029 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1030 } else if (AP1 == AP2.lshr(shiftAmt: Shift)) {
1031 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1032 }
1033 }
1034
1035 // Shifting const2 will never be equal to const1.
1036 // FIXME: This should always be handled by InstSimplify?
1037 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1038 return replaceInstUsesWith(I, V: TorF);
1039}
1040
1041/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1042/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1043Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
1044 const APInt &AP1,
1045 const APInt &AP2) {
1046 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1047
1048 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1049 if (I.getPredicate() == I.ICMP_NE)
1050 Pred = CmpInst::getInversePredicate(pred: Pred);
1051 return new ICmpInst(Pred, LHS, RHS);
1052 };
1053
1054 // Don't bother doing any work for cases which InstSimplify handles.
1055 if (AP2.isZero())
1056 return nullptr;
1057
1058 unsigned AP2TrailingZeros = AP2.countr_zero();
1059
1060 if (!AP1 && AP2TrailingZeros != 0)
1061 return getICmp(
1062 I.ICMP_UGE, A,
1063 ConstantInt::get(Ty: A->getType(), V: AP2.getBitWidth() - AP2TrailingZeros));
1064
1065 if (AP1 == AP2)
1066 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(Ty: A->getType()));
1067
1068 // Get the distance between the lowest bits that are set.
1069 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1070
1071 if (Shift > 0 && AP2.shl(shiftAmt: Shift) == AP1)
1072 return getICmp(I.ICMP_EQ, A, ConstantInt::get(Ty: A->getType(), V: Shift));
1073
1074 // Shifting const2 will never be equal to const1.
1075 // FIXME: This should always be handled by InstSimplify?
1076 auto *TorF = ConstantInt::get(Ty: I.getType(), V: I.getPredicate() == I.ICMP_NE);
1077 return replaceInstUsesWith(I, V: TorF);
1078}
1079
1080/// The caller has matched a pattern of the form:
1081/// I = icmp ugt (add (add A, B), CI2), CI1
1082/// If this is of the form:
1083/// sum = a + b
1084/// if (sum+128 >u 255)
1085/// Then replace it with llvm.sadd.with.overflow.i8.
1086///
1087static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
1088 ConstantInt *CI2, ConstantInt *CI1,
1089 InstCombinerImpl &IC) {
1090 // The transformation we're trying to do here is to transform this into an
1091 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1092 // with a narrower add, and discard the add-with-constant that is part of the
1093 // range check (if we can't eliminate it, this isn't profitable).
1094
1095 // In order to eliminate the add-with-constant, the compare can be its only
1096 // use.
1097 Instruction *AddWithCst = cast<Instruction>(Val: I.getOperand(i_nocapture: 0));
1098 if (!AddWithCst->hasOneUse())
1099 return nullptr;
1100
1101 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1102 if (!CI2->getValue().isPowerOf2())
1103 return nullptr;
1104 unsigned NewWidth = CI2->getValue().countr_zero();
1105 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1106 return nullptr;
1107
1108 // The width of the new add formed is 1 more than the bias.
1109 ++NewWidth;
1110
1111 // Check to see that CI1 is an all-ones value with NewWidth bits.
1112 if (CI1->getBitWidth() == NewWidth ||
1113 CI1->getValue() != APInt::getLowBitsSet(numBits: CI1->getBitWidth(), loBitsSet: NewWidth))
1114 return nullptr;
1115
1116 // This is only really a signed overflow check if the inputs have been
1117 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1118 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1119 if (IC.ComputeMaxSignificantBits(Op: A, CxtI: &I) > NewWidth ||
1120 IC.ComputeMaxSignificantBits(Op: B, CxtI: &I) > NewWidth)
1121 return nullptr;
1122
1123 // In order to replace the original add with a narrower
1124 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1125 // and truncates that discard the high bits of the add. Verify that this is
1126 // the case.
1127 Instruction *OrigAdd = cast<Instruction>(Val: AddWithCst->getOperand(i: 0));
1128 for (User *U : OrigAdd->users()) {
1129 if (U == AddWithCst)
1130 continue;
1131
1132 // Only accept truncates for now. We would really like a nice recursive
1133 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1134 // chain to see which bits of a value are actually demanded. If the
1135 // original add had another add which was then immediately truncated, we
1136 // could still do the transformation.
1137 TruncInst *TI = dyn_cast<TruncInst>(Val: U);
1138 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1139 return nullptr;
1140 }
1141
1142 // If the pattern matches, truncate the inputs to the narrower type and
1143 // use the sadd_with_overflow intrinsic to efficiently compute both the
1144 // result and the overflow bit.
1145 Type *NewType = IntegerType::get(C&: OrigAdd->getContext(), NumBits: NewWidth);
1146 Function *F = Intrinsic::getOrInsertDeclaration(
1147 M: I.getModule(), id: Intrinsic::sadd_with_overflow, OverloadTys: NewType);
1148
1149 InstCombiner::BuilderTy &Builder = IC.Builder;
1150
1151 // Put the new code above the original add, in case there are any uses of the
1152 // add between the add and the compare.
1153 Builder.SetInsertPoint(OrigAdd);
1154
1155 Value *TruncA = Builder.CreateTrunc(V: A, DestTy: NewType, Name: A->getName() + ".trunc");
1156 Value *TruncB = Builder.CreateTrunc(V: B, DestTy: NewType, Name: B->getName() + ".trunc");
1157 CallInst *Call = Builder.CreateCall(Callee: F, Args: {TruncA, TruncB}, Name: "sadd");
1158 Value *Add = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "sadd.result");
1159 Value *ZExt = Builder.CreateZExt(V: Add, DestTy: OrigAdd->getType());
1160
1161 // The inner add was the result of the narrow add, zero extended to the
1162 // wider type. Replace it with the result computed by the intrinsic.
1163 IC.replaceInstUsesWith(I&: *OrigAdd, V: ZExt);
1164 IC.eraseInstFromFunction(I&: *OrigAdd);
1165
1166 // The original icmp gets replaced with the overflow value.
1167 return ExtractValueInst::Create(Agg: Call, Idxs: 1, NameStr: "sadd.overflow");
1168}
1169
1170/// If we have:
1171/// icmp eq/ne (urem/srem %x, %y), 0
1172/// iff %y is a power-of-two, we can replace this with a bit test:
1173/// icmp eq/ne (and %x, (add %y, -1)), 0
1174Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
1175 // This fold is only valid for equality predicates.
1176 if (!I.isEquality())
1177 return nullptr;
1178 CmpPredicate Pred;
1179 Value *X, *Y, *Zero;
1180 if (!match(V: &I, P: m_ICmp(Pred, L: m_OneUse(SubPattern: m_IRem(L: m_Value(V&: X), R: m_Value(V&: Y))),
1181 R: m_CombineAnd(Ps: m_Zero(), Ps: m_Value(V&: Zero)))))
1182 return nullptr;
1183 if (!isKnownToBeAPowerOfTwo(V: Y, /*OrZero*/ true, CxtI: &I))
1184 return nullptr;
1185 // This may increase instruction count, we don't enforce that Y is a constant.
1186 Value *Mask = Builder.CreateAdd(LHS: Y, RHS: Constant::getAllOnesValue(Ty: Y->getType()));
1187 Value *Masked = Builder.CreateAnd(LHS: X, RHS: Mask);
1188 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Masked, S2: Zero);
1189}
1190
1191/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1192/// by one-less-than-bitwidth into a sign test on the original value.
1193Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
1194 Instruction *Val;
1195 CmpPredicate Pred;
1196 if (!I.isEquality() || !match(V: &I, P: m_ICmp(Pred, L: m_Instruction(I&: Val), R: m_Zero())))
1197 return nullptr;
1198
1199 Value *X;
1200 Type *XTy;
1201
1202 Constant *C;
1203 if (match(V: Val, P: m_TruncOrSelf(Op: m_Shr(L: m_Value(V&: X), R: m_Constant(C))))) {
1204 XTy = X->getType();
1205 unsigned XBitWidth = XTy->getScalarSizeInBits();
1206 if (!match(V: C, P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_EQ,
1207 Threshold: APInt(XBitWidth, XBitWidth - 1))))
1208 return nullptr;
1209 } else if (isa<BinaryOperator>(Val) &&
1210 (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
1211 Sh0: cast<BinaryOperator>(Val), SQ: SQ.getWithInstruction(I: Val),
1212 /*AnalyzeForSignBitExtraction=*/true))) {
1213 XTy = X->getType();
1214 } else
1215 return nullptr;
1216
1217 return ICmpInst::Create(Op: Instruction::ICmp,
1218 Pred: Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
1219 : ICmpInst::ICMP_SLT,
1220 S1: X, S2: ConstantInt::getNullValue(Ty: XTy));
1221}
1222
1223// Handle icmp pred X, 0
1224Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
1225 CmpInst::Predicate Pred = Cmp.getPredicate();
1226 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_Zero()))
1227 return nullptr;
1228
1229 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1230 if (Pred == ICmpInst::ICMP_SGT) {
1231 Value *A, *B;
1232 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_SMin(Op0: m_Value(V&: A), Op1: m_Value(V&: B)))) {
1233 if (isKnownPositive(V: A, SQ: SQ.getWithInstruction(I: &Cmp)))
1234 return new ICmpInst(Pred, B, Cmp.getOperand(i_nocapture: 1));
1235 if (isKnownPositive(V: B, SQ: SQ.getWithInstruction(I: &Cmp)))
1236 return new ICmpInst(Pred, A, Cmp.getOperand(i_nocapture: 1));
1237 }
1238 }
1239
1240 if (Instruction *New = foldIRemByPowerOfTwoToBitTest(I&: Cmp))
1241 return New;
1242
1243 // Given:
1244 // icmp eq/ne (urem %x, %y), 0
1245 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1246 // icmp eq/ne %x, 0
1247 Value *X, *Y;
1248 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_URem(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1249 ICmpInst::isEquality(P: Pred)) {
1250 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1251 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1252 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1253 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1254 }
1255
1256 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1257 // odd/non-zero/there is no overflow.
1258 if (match(V: Cmp.getOperand(i_nocapture: 0), P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
1259 ICmpInst::isEquality(P: Pred)) {
1260
1261 KnownBits XKnown = computeKnownBits(V: X, CxtI: &Cmp);
1262 // if X % 2 != 0
1263 // (icmp eq/ne Y)
1264 if (XKnown.countMaxTrailingZeros() == 0)
1265 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1266
1267 KnownBits YKnown = computeKnownBits(V: Y, CxtI: &Cmp);
1268 // if Y % 2 != 0
1269 // (icmp eq/ne X)
1270 if (YKnown.countMaxTrailingZeros() == 0)
1271 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1272
1273 auto *BO0 = cast<OverflowingBinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0));
1274 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1275 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
1276 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1277 // but to avoid unnecessary work, first just if this is an obvious case.
1278
1279 // if X non-zero and NoOverflow(X * Y)
1280 // (icmp eq/ne Y)
1281 if (!XKnown.One.isZero() || isKnownNonZero(V: X, Q))
1282 return new ICmpInst(Pred, Y, Cmp.getOperand(i_nocapture: 1));
1283
1284 // if Y non-zero and NoOverflow(X * Y)
1285 // (icmp eq/ne X)
1286 if (!YKnown.One.isZero() || isKnownNonZero(V: Y, Q))
1287 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
1288 }
1289 // Note, we are skipping cases:
1290 // if Y % 2 != 0 AND X % 2 != 0
1291 // (false/true)
1292 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1293 // (false/true)
1294 // Those can be simplified later as we would have already replaced the (icmp
1295 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1296 // will fold to a constant elsewhere.
1297 }
1298
1299 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1300 // where f(X) == 0 if and only if X == 0
1301 if (ICmpInst::isEquality(P: Pred))
1302 if (Value *Stripped = stripNullTest(V: Cmp.getOperand(i_nocapture: 0)))
1303 return new ICmpInst(Pred, Stripped,
1304 Constant::getNullValue(Ty: Stripped->getType()));
1305
1306 return nullptr;
1307}
1308
1309/// Fold icmp eq (num + mask) & ~mask, num
1310/// to
1311/// icmp eq (and num, mask), 0
1312/// Where mask is a low bit mask.
1313Instruction *InstCombinerImpl::foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp) {
1314 Value *Num;
1315 CmpPredicate Pred;
1316 const APInt *Mask, *Neg;
1317
1318 if (!match(V: &Cmp,
1319 P: m_c_ICmp(Pred, L: m_Value(V&: Num),
1320 R: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_c_Add(L: m_Deferred(V: Num),
1321 R: m_LowBitMask(V&: Mask))),
1322 R: m_APInt(Res&: Neg))))))
1323 return nullptr;
1324
1325 if (*Neg != ~*Mask)
1326 return nullptr;
1327
1328 if (!ICmpInst::isEquality(P: Pred))
1329 return nullptr;
1330
1331 // Create new icmp eq (num & mask), 0
1332 auto *NewAnd = Builder.CreateAnd(LHS: Num, RHS: *Mask);
1333 auto *Zero = Constant::getNullValue(Ty: Num->getType());
1334
1335 return new ICmpInst(Pred, NewAnd, Zero);
1336}
1337
1338/// Fold icmp Pred X, C.
1339/// TODO: This code structure does not make sense. The saturating add fold
1340/// should be moved to some other helper and extended as noted below (it is also
1341/// possible that code has been made unnecessary - do we canonicalize IR to
1342/// overflow/saturating intrinsics or not?).
1343Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
1344 // Match the following pattern, which is a common idiom when writing
1345 // overflow-safe integer arithmetic functions. The source performs an addition
1346 // in wider type and explicitly checks for overflow using comparisons against
1347 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1348 //
1349 // TODO: This could probably be generalized to handle other overflow-safe
1350 // operations if we worked out the formulas to compute the appropriate magic
1351 // constants.
1352 //
1353 // sum = a + b
1354 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1355 CmpInst::Predicate Pred = Cmp.getPredicate();
1356 Value *Op0 = Cmp.getOperand(i_nocapture: 0), *Op1 = Cmp.getOperand(i_nocapture: 1);
1357 Value *A, *B;
1358 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1359 if (Pred == ICmpInst::ICMP_UGT && match(V: Op1, P: m_ConstantInt(CI)) &&
1360 match(V: Op0, P: m_Add(L: m_Add(L: m_Value(V&: A), R: m_Value(V&: B)), R: m_ConstantInt(CI&: CI2))))
1361 if (Instruction *Res = processUGT_ADDCST_ADD(I&: Cmp, A, B, CI2, CI1: CI, IC&: *this))
1362 return Res;
1363
1364 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1365 Constant *C = dyn_cast<Constant>(Val: Op1);
1366 if (!C)
1367 return nullptr;
1368
1369 if (auto *Phi = dyn_cast<PHINode>(Val: Op0))
1370 if (all_of(Range: Phi->operands(), P: IsaPred<Constant>)) {
1371 SmallVector<Constant *> Ops;
1372 for (Value *V : Phi->incoming_values()) {
1373 Constant *Res =
1374 ConstantFoldCompareInstOperands(Predicate: Pred, LHS: cast<Constant>(Val: V), RHS: C, DL);
1375 if (!Res)
1376 return nullptr;
1377 Ops.push_back(Elt: Res);
1378 }
1379 Builder.SetInsertPoint(Phi);
1380 PHINode *NewPhi = Builder.CreatePHI(Ty: Cmp.getType(), NumReservedValues: Phi->getNumOperands());
1381 for (auto [V, Pred] : zip(t&: Ops, u: Phi->blocks()))
1382 NewPhi->addIncoming(V, BB: Pred);
1383 return replaceInstUsesWith(I&: Cmp, V: NewPhi);
1384 }
1385
1386 if (Instruction *R = tryFoldInstWithCtpopWithNot(I: &Cmp))
1387 return R;
1388
1389 return nullptr;
1390}
1391
1392/// Canonicalize icmp instructions based on dominating conditions.
1393Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
1394 // We already checked simple implication in InstSimplify, only handle complex
1395 // cases here.
1396 Value *X = Cmp.getOperand(i_nocapture: 0), *Y = Cmp.getOperand(i_nocapture: 1);
1397 const APInt *C;
1398 if (!match(V: Y, P: m_APInt(Res&: C)))
1399 return nullptr;
1400
1401 CmpInst::Predicate Pred = Cmp.getPredicate();
1402 ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
1403
1404 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1405 const APInt *DomC) -> Instruction * {
1406 // We have 2 compares of a variable with constants. Calculate the constant
1407 // ranges of those compares to see if we can transform the 2nd compare:
1408 // DomBB:
1409 // DomCond = icmp DomPred X, DomC
1410 // br DomCond, CmpBB, FalseBB
1411 // CmpBB:
1412 // Cmp = icmp Pred X, C
1413 ConstantRange DominatingCR =
1414 ConstantRange::makeExactICmpRegion(Pred: DomPred, Other: *DomC);
1415 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1416 ConstantRange Difference = DominatingCR.difference(CR);
1417 if (Intersection.isEmptySet())
1418 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
1419 if (Difference.isEmptySet())
1420 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
1421
1422 // Canonicalizing a sign bit comparison that gets used in a branch,
1423 // pessimizes codegen by generating branch on zero instruction instead
1424 // of a test and branch. So we avoid canonicalizing in such situations
1425 // because test and branch instruction has better branch displacement
1426 // than compare and branch instruction.
1427 bool UnusedBit;
1428 bool IsSignBit = isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: UnusedBit);
1429 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(I&: Cmp)))
1430 return nullptr;
1431
1432 // Avoid an infinite loop with min/max canonicalization.
1433 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1434 if (Cmp.hasOneUse() &&
1435 match(V: Cmp.user_back(), P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value())))
1436 return nullptr;
1437
1438 if (const APInt *EqC = Intersection.getSingleElement())
1439 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(AI: *EqC));
1440 if (const APInt *NeC = Difference.getSingleElement())
1441 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(AI: *NeC));
1442 return nullptr;
1443 };
1444
1445 for (CondBrInst *BI : DC.conditionsFor(V: X)) {
1446 CmpPredicate DomPred;
1447 const APInt *DomC;
1448 if (!match(V: BI->getCondition(),
1449 P: m_ICmp(Pred&: DomPred, L: m_Specific(V: X), R: m_APInt(Res&: DomC))))
1450 continue;
1451
1452 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(i: 0));
1453 if (DT.dominates(BBE: Edge0, BB: Cmp.getParent())) {
1454 if (auto *V = handleDomCond(DomPred, DomC))
1455 return V;
1456 } else {
1457 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(i: 1));
1458 if (DT.dominates(BBE: Edge1, BB: Cmp.getParent()))
1459 if (auto *V =
1460 handleDomCond(CmpInst::getInversePredicate(pred: DomPred), DomC))
1461 return V;
1462 }
1463 }
1464
1465 return nullptr;
1466}
1467
1468/// Fold icmp (trunc X), C.
1469Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
1470 TruncInst *Trunc,
1471 const APInt &C) {
1472 ICmpInst::Predicate Pred = Cmp.getPredicate();
1473 Value *X = Trunc->getOperand(i_nocapture: 0);
1474 Type *SrcTy = X->getType();
1475 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1476 SrcBits = SrcTy->getScalarSizeInBits();
1477
1478 // Match (icmp pred (trunc nuw/nsw X), C)
1479 // Which we can convert to (icmp pred X, (sext/zext C))
1480 if (shouldChangeType(From: Trunc->getType(), To: SrcTy)) {
1481 if (Trunc->hasNoSignedWrap())
1482 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.sext(width: SrcBits)));
1483 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1484 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits)));
1485 }
1486
1487 if (C.isOne() && C.getBitWidth() > 1) {
1488 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1489 Value *V = nullptr;
1490 if (Pred == ICmpInst::ICMP_SLT && match(V: X, P: m_Signum(V: m_Value(V))))
1491 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1492 ConstantInt::get(Ty: V->getType(), V: 1));
1493 }
1494
1495 // TODO: Handle non-equality predicates.
1496 Value *Y;
1497 const APInt *Pow2;
1498 if (Cmp.isEquality() && match(V: X, P: m_Shl(L: m_Power2(V&: Pow2), R: m_Value(V&: Y))) &&
1499 DstBits > Pow2->logBase2()) {
1500 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1501 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1502 // iff N > log2(Pow2)
1503 if (C.isZero()) {
1504 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1505 return new ICmpInst(NewPred, Y,
1506 ConstantInt::get(Ty: SrcTy, V: DstBits - Pow2->logBase2()));
1507 }
1508 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1509 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1510 if (C.isPowerOf2())
1511 return new ICmpInst(
1512 Pred, Y, ConstantInt::get(Ty: SrcTy, V: C.logBase2() - Pow2->logBase2()));
1513 }
1514
1515 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1516 // Canonicalize to a mask and wider compare if the wide type is suitable:
1517 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1518 if (!SrcTy->isVectorTy() && shouldChangeType(FromBitWidth: DstBits, ToBitWidth: SrcBits)) {
1519 Constant *Mask =
1520 ConstantInt::get(Ty: SrcTy, V: APInt::getLowBitsSet(numBits: SrcBits, loBitsSet: DstBits));
1521 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(LHS: X, RHS: Mask);
1522 Constant *WideC = ConstantInt::get(Ty: SrcTy, V: C.zext(width: SrcBits));
1523 return new ICmpInst(Pred, And, WideC);
1524 }
1525
1526 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1527 // of the high bits truncated out of x are known.
1528 KnownBits Known = computeKnownBits(V: X, CxtI: &Cmp);
1529
1530 // If all the high bits are known, we can do this xform.
1531 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1532 // Pull in the high bits from known-ones set.
1533 APInt NewRHS = C.zext(width: SrcBits);
1534 NewRHS |= Known.One & APInt::getHighBitsSet(numBits: SrcBits, hiBitsSet: SrcBits - DstBits);
1535 return new ICmpInst(Pred, X, ConstantInt::get(Ty: SrcTy, V: NewRHS));
1536 }
1537 }
1538
1539 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1540 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1541 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1542 Value *ShOp;
1543 uint64_t ShAmt;
1544 bool TrueIfSigned;
1545 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
1546 match(V: X, P: m_Shr(L: m_Value(V&: ShOp), R: m_ConstantInt(V&: ShAmt))) &&
1547 DstBits == SrcBits - ShAmt) {
1548 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1549 ConstantInt::getNullValue(Ty: SrcTy))
1550 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1551 ConstantInt::getAllOnesValue(Ty: SrcTy));
1552 }
1553
1554 return nullptr;
1555}
1556
1557/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1558/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1559Instruction *
1560InstCombinerImpl::foldICmpTruncWithTruncOrExt(ICmpInst &Cmp,
1561 const SimplifyQuery &Q) {
1562 Value *X, *Y;
1563 CmpPredicate Pred;
1564 bool YIsSExt = false;
1565 // Try to match icmp (trunc X), (trunc Y)
1566 if (match(V: &Cmp, P: m_ICmp(Pred, L: m_Trunc(Op: m_Value(V&: X)), R: m_Trunc(Op: m_Value(V&: Y))))) {
1567 unsigned NoWrapFlags = cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0))->getNoWrapKind() &
1568 cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 1))->getNoWrapKind();
1569 if (Cmp.isSigned()) {
1570 // For signed comparisons, both truncs must be nsw.
1571 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1572 return nullptr;
1573 } else {
1574 // For unsigned and equality comparisons, either both must be nuw or
1575 // both must be nsw, we don't care which.
1576 if (!NoWrapFlags)
1577 return nullptr;
1578 }
1579
1580 if (X->getType() != Y->getType() &&
1581 (!Cmp.getOperand(i_nocapture: 0)->hasOneUse() || !Cmp.getOperand(i_nocapture: 1)->hasOneUse()))
1582 return nullptr;
1583 if (!isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()) &&
1584 isDesirableIntType(BitWidth: Y->getType()->getScalarSizeInBits())) {
1585 std::swap(a&: X, b&: Y);
1586 Pred = Cmp.getSwappedPredicate(pred: Pred);
1587 }
1588 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1589 }
1590 // Try to match icmp (trunc nuw X), (zext Y)
1591 else if (!Cmp.isSigned() &&
1592 match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NUWTrunc(Op: m_Value(V&: X)),
1593 R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y)))))) {
1594 // Can fold trunc nuw + zext for unsigned and equality predicates.
1595 }
1596 // Try to match icmp (trunc nsw X), (sext Y)
1597 else if (match(V: &Cmp, P: m_c_ICmp(Pred, L: m_NSWTrunc(Op: m_Value(V&: X)),
1598 R: m_OneUse(SubPattern: m_ZExtOrSExt(Op: m_Value(V&: Y)))))) {
1599 // Can fold trunc nsw + zext/sext for all predicates.
1600 YIsSExt =
1601 isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 0)) || isa<SExtInst>(Val: Cmp.getOperand(i_nocapture: 1));
1602 } else
1603 return nullptr;
1604
1605 Type *TruncTy = Cmp.getOperand(i_nocapture: 0)->getType();
1606 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1607
1608 // If this transform will end up changing from desirable types -> undesirable
1609 // types skip it.
1610 if (isDesirableIntType(BitWidth: TruncBits) &&
1611 !isDesirableIntType(BitWidth: X->getType()->getScalarSizeInBits()))
1612 return nullptr;
1613
1614 Value *NewY = Builder.CreateIntCast(V: Y, DestTy: X->getType(), isSigned: YIsSExt);
1615 return new ICmpInst(Pred, X, NewY);
1616}
1617
1618/// Fold icmp (xor X, Y), C.
1619Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
1620 BinaryOperator *Xor,
1621 const APInt &C) {
1622 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1623 return I;
1624
1625 Value *X = Xor->getOperand(i_nocapture: 0);
1626 Value *Y = Xor->getOperand(i_nocapture: 1);
1627 const APInt *XorC;
1628 if (!match(V: Y, P: m_APInt(Res&: XorC)))
1629 return nullptr;
1630
1631 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1632 // fold the xor.
1633 ICmpInst::Predicate Pred = Cmp.getPredicate();
1634 bool TrueIfSigned = false;
1635 if (isSignBitCheck(Pred: Cmp.getPredicate(), RHS: C, TrueIfSigned)) {
1636
1637 // If the sign bit of the XorCst is not set, there is no change to
1638 // the operation, just stop using the Xor.
1639 if (!XorC->isNegative())
1640 return replaceOperand(I&: Cmp, OpNum: 0, V: X);
1641
1642 // Emit the opposite comparison.
1643 if (TrueIfSigned)
1644 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1645 ConstantInt::getAllOnesValue(Ty: X->getType()));
1646 else
1647 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1648 ConstantInt::getNullValue(Ty: X->getType()));
1649 }
1650
1651 if (Xor->hasOneUse()) {
1652 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1653 if (!Cmp.isEquality() && XorC->isSignMask()) {
1654 Pred = Cmp.getFlippedSignednessPredicate();
1655 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1656 }
1657
1658 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1659 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1660 Pred = Cmp.getFlippedSignednessPredicate();
1661 Pred = Cmp.getSwappedPredicate(pred: Pred);
1662 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: C ^ *XorC));
1663 }
1664 }
1665
1666 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1667 if (Pred == ICmpInst::ICMP_UGT) {
1668 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1669 if (*XorC == ~C && (C + 1).isPowerOf2())
1670 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1671 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1672 if (*XorC == C && (C + 1).isPowerOf2())
1673 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1674 }
1675 if (Pred == ICmpInst::ICMP_ULT) {
1676 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1677 if (*XorC == -C && C.isPowerOf2())
1678 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1679 ConstantInt::get(Ty: X->getType(), V: ~C));
1680 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1681 if (*XorC == C && (-C).isPowerOf2())
1682 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1683 ConstantInt::get(Ty: X->getType(), V: ~C));
1684 }
1685 return nullptr;
1686}
1687
1688/// For power-of-2 C:
1689/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1690/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1691Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
1692 BinaryOperator *Xor,
1693 const APInt &C) {
1694 CmpInst::Predicate Pred = Cmp.getPredicate();
1695 APInt PowerOf2;
1696 if (Pred == ICmpInst::ICMP_ULT)
1697 PowerOf2 = C;
1698 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1699 PowerOf2 = C + 1;
1700 else
1701 return nullptr;
1702 if (!PowerOf2.isPowerOf2())
1703 return nullptr;
1704 Value *X;
1705 const APInt *ShiftC;
1706 if (!match(V: Xor, P: m_OneUse(SubPattern: m_c_Xor(L: m_Value(V&: X),
1707 R: m_AShr(L: m_Deferred(V: X), R: m_APInt(Res&: ShiftC))))))
1708 return nullptr;
1709 uint64_t Shift = ShiftC->getLimitedValue();
1710 Type *XType = X->getType();
1711 if (Shift == 0 || PowerOf2.isMinSignedValue())
1712 return nullptr;
1713 Value *Add = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: PowerOf2));
1714 APInt Bound =
1715 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1716 return new ICmpInst(Pred, Add, ConstantInt::get(Ty: XType, V: Bound));
1717}
1718
1719/// Fold icmp (and (sh X, Y), C2), C1.
1720Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
1721 BinaryOperator *And,
1722 const APInt &C1,
1723 const APInt &C2) {
1724 BinaryOperator *Shift = dyn_cast<BinaryOperator>(Val: And->getOperand(i_nocapture: 0));
1725 if (!Shift || !Shift->isShift())
1726 return nullptr;
1727
1728 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1729 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1730 // code produced by the clang front-end, for bitfield access.
1731 // This seemingly simple opportunity to fold away a shift turns out to be
1732 // rather complicated. See PR17827 for details.
1733 unsigned ShiftOpcode = Shift->getOpcode();
1734 bool IsShl = ShiftOpcode == Instruction::Shl;
1735 const APInt *C3;
1736 if (match(V: Shift->getOperand(i_nocapture: 1), P: m_APInt(Res&: C3))) {
1737 APInt NewAndCst, NewCmpCst;
1738 bool AnyCmpCstBitsShiftedOut;
1739 if (ShiftOpcode == Instruction::Shl) {
1740 // For a left shift, we can fold if the comparison is not signed. We can
1741 // also fold a signed comparison if the mask value and comparison value
1742 // are not negative. These constraints may not be obvious, but we can
1743 // prove that they are correct using an SMT solver.
1744 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1745 return nullptr;
1746
1747 NewCmpCst = C1.lshr(ShiftAmt: *C3);
1748 NewAndCst = C2.lshr(ShiftAmt: *C3);
1749 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(ShiftAmt: *C3) != C1;
1750 } else if (ShiftOpcode == Instruction::LShr) {
1751 // For a logical right shift, we can fold if the comparison is not signed.
1752 // We can also fold a signed comparison if the shifted mask value and the
1753 // shifted comparison value are not negative. These constraints may not be
1754 // obvious, but we can prove that they are correct using an SMT solver.
1755 NewCmpCst = C1.shl(ShiftAmt: *C3);
1756 NewAndCst = C2.shl(ShiftAmt: *C3);
1757 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(ShiftAmt: *C3) != C1;
1758 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1759 return nullptr;
1760 } else {
1761 // For an arithmetic shift, check that both constants don't use (in a
1762 // signed sense) the top bits being shifted out.
1763 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1764 NewCmpCst = C1.shl(ShiftAmt: *C3);
1765 NewAndCst = C2.shl(ShiftAmt: *C3);
1766 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(ShiftAmt: *C3) != C1;
1767 if (NewAndCst.ashr(ShiftAmt: *C3) != C2)
1768 return nullptr;
1769 }
1770
1771 if (AnyCmpCstBitsShiftedOut) {
1772 // If we shifted bits out, the fold is not going to work out. As a
1773 // special case, check to see if this means that the result is always
1774 // true or false now.
1775 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1776 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getFalse(Ty: Cmp.getType()));
1777 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1778 return replaceInstUsesWith(I&: Cmp, V: ConstantInt::getTrue(Ty: Cmp.getType()));
1779 } else {
1780 Value *NewAnd = Builder.CreateAnd(
1781 LHS: Shift->getOperand(i_nocapture: 0), RHS: ConstantInt::get(Ty: And->getType(), V: NewAndCst));
1782 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1783 ConstantInt::get(Ty: And->getType(), V: NewCmpCst));
1784 }
1785 }
1786
1787 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1788 // preferable because it allows the C2 << Y expression to be hoisted out of a
1789 // loop if Y is invariant and X is not.
1790 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1791 !Shift->isArithmeticShift() &&
1792 ((!IsShl && C2.isOne()) || !isa<Constant>(Val: Shift->getOperand(i_nocapture: 0)))) {
1793 // Compute C2 << Y.
1794 Value *NewShift =
1795 IsShl ? Builder.CreateLShr(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1))
1796 : Builder.CreateShl(LHS: And->getOperand(i_nocapture: 1), RHS: Shift->getOperand(i_nocapture: 1));
1797
1798 // Compute X & (C2 << Y).
1799 Value *NewAnd = Builder.CreateAnd(LHS: Shift->getOperand(i_nocapture: 0), RHS: NewShift);
1800 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1801 }
1802
1803 return nullptr;
1804}
1805
1806/// Fold icmp (and X, C2), C1.
1807Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
1808 BinaryOperator *And,
1809 const APInt &C1) {
1810 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1811
1812 // icmp ne (and X, 1), 0 --> trunc X to i1
1813 if (isICMP_NE && C1.isZero() && match(V: And->getOperand(i_nocapture: 1), P: m_One()))
1814 return new TruncInst(And->getOperand(i_nocapture: 0), Cmp.getType());
1815
1816 const APInt *C2;
1817 Value *X;
1818 if (!match(V: And, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C2))))
1819 return nullptr;
1820
1821 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1822 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(RHS: ~*C2) &&
1823 C2->isNegatedPowerOf2())
1824 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1825 ConstantInt::get(Ty: X->getType(), V: ~*C2));
1826 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1827 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1828 (C1 - 1).ule(RHS: ~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1829 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1830 ConstantInt::get(Ty: X->getType(), V: -*C2));
1831
1832 // Don't perform the following transforms if the AND has multiple uses
1833 if (!And->hasOneUse())
1834 return nullptr;
1835
1836 if (Cmp.isEquality() && C1.isZero()) {
1837 // Restrict this fold to single-use 'and' (PR10267).
1838 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1839 if (C2->isSignMask()) {
1840 Constant *Zero = Constant::getNullValue(Ty: X->getType());
1841 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1842 return new ICmpInst(NewPred, X, Zero);
1843 }
1844
1845 APInt NewC2 = *C2;
1846 KnownBits Know = computeKnownBits(V: And->getOperand(i_nocapture: 0), CxtI: And);
1847 // Set high zeros of C2 to allow matching negated power-of-2.
1848 NewC2 = *C2 | APInt::getHighBitsSet(numBits: C2->getBitWidth(),
1849 hiBitsSet: Know.countMinLeadingZeros());
1850
1851 // Restrict this fold only for single-use 'and' (PR10267).
1852 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1853 if (NewC2.isNegatedPowerOf2()) {
1854 Constant *NegBOC = ConstantInt::get(Ty: And->getType(), V: -NewC2);
1855 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1856 return new ICmpInst(NewPred, X, NegBOC);
1857 }
1858 }
1859
1860 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1861 // the input width without changing the value produced, eliminate the cast:
1862 //
1863 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1864 //
1865 // We can do this transformation if the constants do not have their sign bits
1866 // set or if it is an equality comparison. Extending a relational comparison
1867 // when we're checking the sign bit would not work.
1868 Value *W;
1869 if (match(V: And->getOperand(i_nocapture: 0), P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: W)))) &&
1870 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1871 // TODO: Is this a good transform for vectors? Wider types may reduce
1872 // throughput. Should this transform be limited (even for scalars) by using
1873 // shouldChangeType()?
1874 if (!Cmp.getType()->isVectorTy()) {
1875 Type *WideType = W->getType();
1876 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1877 Constant *ZextC1 = ConstantInt::get(Ty: WideType, V: C1.zext(width: WideScalarBits));
1878 Constant *ZextC2 = ConstantInt::get(Ty: WideType, V: C2->zext(width: WideScalarBits));
1879 Value *NewAnd = Builder.CreateAnd(LHS: W, RHS: ZextC2, Name: And->getName());
1880 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1881 }
1882 }
1883
1884 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, C2: *C2))
1885 return I;
1886
1887 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1888 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1889 //
1890 // iff pred isn't signed
1891 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(i_nocapture: 0)->hasOneUse() &&
1892 match(V: And->getOperand(i_nocapture: 1), P: m_One())) {
1893 Constant *One = cast<Constant>(Val: And->getOperand(i_nocapture: 1));
1894 Value *Or = And->getOperand(i_nocapture: 0);
1895 Value *A, *B, *LShr;
1896 if (match(V: Or, P: m_Or(L: m_Value(V&: LShr), R: m_Value(V&: A))) &&
1897 match(V: LShr, P: m_LShr(L: m_Specific(V: A), R: m_Value(V&: B)))) {
1898 unsigned UsesRemoved = 0;
1899 if (And->hasOneUse())
1900 ++UsesRemoved;
1901 if (Or->hasOneUse())
1902 ++UsesRemoved;
1903 if (LShr->hasOneUse())
1904 ++UsesRemoved;
1905
1906 // Compute A & ((1 << B) | 1)
1907 unsigned RequireUsesRemoved = match(V: B, P: m_ImmConstant()) ? 1 : 3;
1908 if (UsesRemoved >= RequireUsesRemoved) {
1909 Value *NewOr =
1910 Builder.CreateOr(LHS: Builder.CreateShl(LHS: One, RHS: B, Name: LShr->getName(),
1911 /*HasNUW=*/true),
1912 RHS: One, Name: Or->getName());
1913 Value *NewAnd = Builder.CreateAnd(LHS: A, RHS: NewOr, Name: And->getName());
1914 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(i_nocapture: 1));
1915 }
1916 }
1917 }
1918
1919 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1920 // llvm.is.fpclass(X, fcInf|fcNan)
1921 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1922 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1923 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1924 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1925 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1926 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1927 Value *V;
1928 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1929 Kind: Attribute::NoImplicitFloat) &&
1930 Cmp.isEquality() &&
1931 match(V: X, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V))))) {
1932 Type *FPType = V->getType()->getScalarType();
1933 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1934 APInt ExponentMask =
1935 APFloat::getInf(Sem: FPType->getFltSemantics()).bitcastToAPInt();
1936 if (*C2 == ExponentMask) {
1937 unsigned Mask = C1.isZero()
1938 ? FPClassTest::fcZero | FPClassTest::fcSubnormal
1939 : FPClassTest::fcNan | FPClassTest::fcInf;
1940 if (isICMP_NE)
1941 Mask = ~Mask & fcAllFlags;
1942 return replaceInstUsesWith(I&: Cmp, V: Builder.createIsFPClass(FPNum: V, Test: Mask));
1943 }
1944 }
1945 }
1946
1947 return nullptr;
1948}
1949
1950/// Fold icmp (and X, Y), C.
1951Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
1952 BinaryOperator *And,
1953 const APInt &C) {
1954 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C1: C))
1955 return I;
1956
1957 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1958 bool TrueIfNeg;
1959 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned&: TrueIfNeg)) {
1960 // ((X - 1) & ~X) < 0 --> X == 0
1961 // ((X - 1) & ~X) >= 0 --> X != 0
1962 Value *X;
1963 if (match(V: And->getOperand(i_nocapture: 0), P: m_Add(L: m_Value(V&: X), R: m_AllOnes())) &&
1964 match(V: And->getOperand(i_nocapture: 1), P: m_Not(V: m_Specific(V: X)))) {
1965 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1966 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(Ty: X->getType()));
1967 }
1968 // (X & -X) < 0 --> X == MinSignedC
1969 // (X & -X) > -1 --> X != MinSignedC
1970 if (match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
1971 Constant *MinSignedC = ConstantInt::get(
1972 Ty: X->getType(),
1973 V: APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits()));
1974 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1975 return new ICmpInst(NewPred, X, MinSignedC);
1976 }
1977 }
1978
1979 // TODO: These all require that Y is constant too, so refactor with the above.
1980
1981 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1982 Value *X = And->getOperand(i_nocapture: 0);
1983 Value *Y = And->getOperand(i_nocapture: 1);
1984 if (auto *C2 = dyn_cast<ConstantInt>(Val: Y))
1985 if (auto *LI = dyn_cast<LoadInst>(Val: X))
1986 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LI->getOperand(i_nocapture: 0)))
1987 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, ICI&: Cmp, AndCst: C2))
1988 return Res;
1989
1990 if (!Cmp.isEquality())
1991 return nullptr;
1992
1993 // (X & -X) == 0 --> X == 0
1994 // (X & -X) != 0 --> X != 0
1995 // (X & -X) == 1 --> trunc X to i1
1996 // (X & -X) != 1 --> !(trunc X to i1)
1997 // Cmp is == or != by the check above.
1998 Value *MatchedX;
1999 // Match X & -X in either operand order.
2000 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2001 match(V: And, P: m_c_And(L: m_Neg(V: m_Value(V&: MatchedX)), R: m_Deferred(V: MatchedX)))) {
2002 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2003 if (C.isZero())
2004 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(i_nocapture: 1));
2005
2006 // (X & -X) == 1 iff the low bit of X is set.
2007 if (Pred == CmpInst::ICMP_EQ)
2008 return new TruncInst(MatchedX, Cmp.getType());
2009
2010 // The remaining case needs a trunc and not. Require the original and
2011 // to become dead to avoid increasing the instruction count.
2012 if (And->hasOneUse()) {
2013 Value *Trunc = Builder.CreateTrunc(V: MatchedX, DestTy: Cmp.getType());
2014 return BinaryOperator::CreateNot(Op: Trunc);
2015 }
2016 }
2017
2018 // X & -C == -C -> X > u ~C
2019 // X & -C != -C -> X <= u ~C
2020 // iff C is a power of 2
2021 if (Cmp.getOperand(i_nocapture: 1) == Y && C.isNegatedPowerOf2()) {
2022 auto NewPred =
2023 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
2024 return new ICmpInst(NewPred, X, SubOne(C: cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1))));
2025 }
2026
2027 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2028 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2029 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2030 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2031 if (match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: X))), R: m_Value(V&: Y)))) &&
2032 X->getType()->isIntOrIntVectorTy(BitWidth: 1) && (C.isZero() || C.isOne())) {
2033 Value *TruncY = Builder.CreateTrunc(V: Y, DestTy: X->getType());
2034 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2035 Value *And = Builder.CreateAnd(LHS: TruncY, RHS: X);
2036 return BinaryOperator::CreateNot(Op: And);
2037 }
2038 return BinaryOperator::CreateAnd(V1: TruncY, V2: X);
2039 }
2040
2041 // (icmp eq/ne (and (shl -1, X), Y), 0)
2042 // -> (icmp eq/ne (lshr Y, X), 0)
2043 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2044 // highly unlikely the non-zero case will ever show up in code.
2045 if (C.isZero() &&
2046 match(V: And, P: m_OneUse(SubPattern: m_c_And(L: m_OneUse(SubPattern: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))),
2047 R: m_Value(V&: Y))))) {
2048 Value *LShr = Builder.CreateLShr(LHS: Y, RHS: X);
2049 return new ICmpInst(Pred, LShr, Constant::getNullValue(Ty: LShr->getType()));
2050 }
2051
2052 // (icmp eq/ne (and (add A, Addend), Msk), C)
2053 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2054 {
2055 Value *A;
2056 const APInt *Addend, *Msk;
2057 if (match(V: And, P: m_OneUse(SubPattern: m_And(L: m_OneUse(SubPattern: m_Add(L: m_Value(V&: A), R: m_APInt(Res&: Addend))),
2058 R: m_LowBitMask(V&: Msk)))) &&
2059 C.ule(RHS: *Msk)) {
2060 APInt NewComperand = (C - *Addend) & *Msk;
2061 Value *MaskA = Builder.CreateAnd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: *Msk));
2062 return new ICmpInst(Pred, MaskA,
2063 ConstantInt::get(Ty: MaskA->getType(), V: NewComperand));
2064 }
2065 }
2066
2067 return nullptr;
2068}
2069
2070/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2071static Value *foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or,
2072 InstCombiner::BuilderTy &Builder) {
2073 // Are we using xors or subs to bitwise check for a pair or pairs of
2074 // (in)equalities? Convert to a shorter form that has more potential to be
2075 // folded even further.
2076 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2077 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2078 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2079 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2080 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2081 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2082 SmallVector<std::pair<Value *, Value *>, 2> CmpValues;
2083 SmallVector<Value *, 16> WorkList(1, Or);
2084
2085 while (!WorkList.empty()) {
2086 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2087 Value *Lhs, *Rhs;
2088
2089 if (match(V: OrOperatorArgument,
2090 P: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2091 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2092 return;
2093 }
2094
2095 if (match(V: OrOperatorArgument,
2096 P: m_OneUse(SubPattern: m_Sub(L: m_Value(V&: Lhs), R: m_Value(V&: Rhs))))) {
2097 CmpValues.emplace_back(Args&: Lhs, Args&: Rhs);
2098 return;
2099 }
2100
2101 WorkList.push_back(Elt: OrOperatorArgument);
2102 };
2103
2104 Value *CurrentValue = WorkList.pop_back_val();
2105 Value *OrOperatorLhs, *OrOperatorRhs;
2106
2107 if (!match(V: CurrentValue,
2108 P: m_Or(L: m_Value(V&: OrOperatorLhs), R: m_Value(V&: OrOperatorRhs)))) {
2109 return nullptr;
2110 }
2111
2112 MatchOrOperatorArgument(OrOperatorRhs);
2113 MatchOrOperatorArgument(OrOperatorLhs);
2114 }
2115
2116 ICmpInst::Predicate Pred = Cmp.getPredicate();
2117 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2118 Value *LhsCmp = Builder.CreateICmp(P: Pred, LHS: CmpValues.rbegin()->first,
2119 RHS: CmpValues.rbegin()->second);
2120
2121 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2122 Value *RhsCmp = Builder.CreateICmp(P: Pred, LHS: It->first, RHS: It->second);
2123 LhsCmp = Builder.CreateBinOp(Opc: BOpc, LHS: LhsCmp, RHS: RhsCmp);
2124 }
2125
2126 return LhsCmp;
2127}
2128
2129/// Fold icmp (or X, Y), C.
2130Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
2131 BinaryOperator *Or,
2132 const APInt &C) {
2133 ICmpInst::Predicate Pred = Cmp.getPredicate();
2134 if (C.isOne()) {
2135 // icmp slt signum(V) 1 --> icmp slt V, 1
2136 Value *V = nullptr;
2137 if (Pred == ICmpInst::ICMP_SLT && match(V: Or, P: m_Signum(V: m_Value(V))))
2138 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2139 ConstantInt::get(Ty: V->getType(), V: 1));
2140 }
2141
2142 Value *OrOp0 = Or->getOperand(i_nocapture: 0), *OrOp1 = Or->getOperand(i_nocapture: 1);
2143
2144 // (icmp eq/ne (or disjoint x, C0), C1)
2145 // -> (icmp eq/ne x, C0^C1)
2146 if (Cmp.isEquality() && match(V: OrOp1, P: m_ImmConstant()) &&
2147 cast<PossiblyDisjointInst>(Val: Or)->isDisjoint()) {
2148 Value *NewC =
2149 Builder.CreateXor(LHS: OrOp1, RHS: ConstantInt::get(Ty: OrOp1->getType(), V: C));
2150 return new ICmpInst(Pred, OrOp0, NewC);
2151 }
2152
2153 const APInt *MaskC;
2154 if (match(V: OrOp1, P: m_APInt(Res&: MaskC)) && Cmp.isEquality()) {
2155 if (*MaskC == C && (C + 1).isPowerOf2()) {
2156 // X | C == C --> X <=u C
2157 // X | C != C --> X >u C
2158 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2159 Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
2160 return new ICmpInst(Pred, OrOp0, OrOp1);
2161 }
2162
2163 // More general: canonicalize 'equality with set bits mask' to
2164 // 'equality with clear bits mask'.
2165 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2166 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2167 if (Or->hasOneUse()) {
2168 Value *And = Builder.CreateAnd(LHS: OrOp0, RHS: ~(*MaskC));
2169 Constant *NewC = ConstantInt::get(Ty: Or->getType(), V: C ^ (*MaskC));
2170 return new ICmpInst(Pred, And, NewC);
2171 }
2172 }
2173
2174 // (X | (X-1)) s< 0 --> X s< 1
2175 // (X | (X-1)) s> -1 --> X s> 0
2176 Value *X;
2177 bool TrueIfSigned;
2178 if (isSignBitCheck(Pred, RHS: C, TrueIfSigned) &&
2179 match(V: Or, P: m_c_Or(L: m_Add(L: m_Value(V&: X), R: m_AllOnes()), R: m_Deferred(V: X)))) {
2180 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2181 Constant *NewC = ConstantInt::get(Ty: X->getType(), V: TrueIfSigned ? 1 : 0);
2182 return new ICmpInst(NewPred, X, NewC);
2183 }
2184
2185 const APInt *OrC;
2186 // icmp(X | OrC, C) --> icmp(X, 0)
2187 if (C.isNonNegative() && match(V: Or, P: m_Or(L: m_Value(V&: X), R: m_APInt(Res&: OrC)))) {
2188 switch (Pred) {
2189 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2190 case ICmpInst::ICMP_SLT:
2191 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2192 case ICmpInst::ICMP_SGE:
2193 if (OrC->sge(RHS: C))
2194 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
2195 break;
2196 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2197 case ICmpInst::ICMP_SLE:
2198 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2199 case ICmpInst::ICMP_SGT:
2200 if (OrC->sgt(RHS: C))
2201 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), X,
2202 ConstantInt::getNullValue(Ty: X->getType()));
2203 break;
2204 default:
2205 break;
2206 }
2207 }
2208
2209 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2210 return nullptr;
2211
2212 Value *P, *Q;
2213 if (match(V: Or, P: m_Or(L: m_PtrToInt(Op: m_Value(V&: P)), R: m_PtrToInt(Op: m_Value(V&: Q))))) {
2214 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2215 // -> and (icmp eq P, null), (icmp eq Q, null).
2216 Value *CmpP =
2217 Builder.CreateICmp(P: Pred, LHS: P, RHS: ConstantInt::getNullValue(Ty: P->getType()));
2218 Value *CmpQ =
2219 Builder.CreateICmp(P: Pred, LHS: Q, RHS: ConstantInt::getNullValue(Ty: Q->getType()));
2220 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2221 return BinaryOperator::Create(Op: BOpc, S1: CmpP, S2: CmpQ);
2222 }
2223
2224 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2225 return replaceInstUsesWith(I&: Cmp, V);
2226
2227 return nullptr;
2228}
2229
2230/// Fold icmp (mul X, Y), C.
2231Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
2232 BinaryOperator *Mul,
2233 const APInt &C) {
2234 ICmpInst::Predicate Pred = Cmp.getPredicate();
2235 Type *MulTy = Mul->getType();
2236 Value *X = Mul->getOperand(i_nocapture: 0);
2237
2238 // If comparing a square with a constant, try simplifying to comparing square
2239 // roots.
2240 if (X == Mul->getOperand(i_nocapture: 1) && !Cmp.isSigned()) {
2241 APInt R = C.sqrtFloor();
2242 bool IsSqr = C == R * R;
2243
2244 // X * X eq/ne C
2245 if (Cmp.isEquality() &&
2246 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2247
2248 // If constant is not a square, eq/ne is false/true respectively
2249 if (!IsSqr)
2250 return replaceInstUsesWith(
2251 I&: Cmp,
2252 V: ConstantInt::getBool(Ty: Cmp.getType(), V: Pred == ICmpInst::ICMP_NE));
2253
2254 return new ICmpInst(Pred, X, ConstantInt::get(Ty: MulTy, V: R));
2255 }
2256
2257 // If the multiply does not wrap
2258 // X * X pred C --> X pred R
2259 if (Mul->hasNoUnsignedWrap()) {
2260
2261 if (IsSqr)
2262 return new ICmpInst(Pred, X, ConstantInt::get(Ty: MulTy, V: R));
2263
2264 // If C is not a square, we use floor/ceil of sqrt(C).
2265 //
2266 // If LT or LE, we need R to be an overestimate of sqrt(C),
2267 // then use the strict predicate (LT->LT, LE->LT).
2268 //
2269 // If GT or GE, we need R to be an underestimate of sqrt(C),
2270 // then use the strict predicate (GT->GT, GE->GT).
2271 //
2272 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2273 if (ICmpInst::isLT(P: Pred) || ICmpInst::isLE(P: Pred))
2274 ++R;
2275
2276 return new ICmpInst(Cmp.getStrictPredicate(), X,
2277 ConstantInt::get(Ty: MulTy, V: R));
2278 }
2279 }
2280
2281 const APInt *MulC;
2282 if (!match(V: Mul->getOperand(i_nocapture: 1), P: m_APInt(Res&: MulC)))
2283 return nullptr;
2284
2285 // If this is a test of the sign bit and the multiply is sign-preserving with
2286 // a constant operand, use the multiply LHS operand instead:
2287 // (X * +MulC) < 0 --> X < 0
2288 // (X * -MulC) < 0 --> X > 0
2289 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2290 if (MulC->isNegative())
2291 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2292 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: MulTy));
2293 }
2294
2295 if (MulC->isZero())
2296 return nullptr;
2297
2298 // If the multiply does not wrap or the constant is odd, try to divide the
2299 // compare constant by the multiplication factor.
2300 if (Cmp.isEquality()) {
2301 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2302 if (Mul->hasNoSignedWrap() && C.srem(RHS: *MulC).isZero()) {
2303 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.sdiv(RHS: *MulC));
2304 return new ICmpInst(Pred, X, NewC);
2305 }
2306
2307 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2308 // correct to transform if MulC * N == C including overflow. I.e with i8
2309 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2310 // miss that case.
2311 if (C.urem(RHS: *MulC).isZero()) {
2312 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2313 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2314 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2315 Constant *NewC = ConstantInt::get(Ty: MulTy, V: C.udiv(RHS: *MulC));
2316 return new ICmpInst(Pred, X, NewC);
2317 }
2318 }
2319 }
2320
2321 // With a matching no-overflow guarantee, fold the constants:
2322 // (X * MulC) < C --> X < (C / MulC)
2323 // (X * MulC) > C --> X > (C / MulC)
2324 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2325 Constant *NewC = nullptr;
2326 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2327 // MININT / -1 --> overflow.
2328 if (C.isMinSignedValue() && MulC->isAllOnes())
2329 return nullptr;
2330 if (MulC->isNegative())
2331 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2332
2333 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2334 NewC = ConstantInt::get(
2335 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2336 } else {
2337 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2338 "Unexpected predicate");
2339 NewC = ConstantInt::get(
2340 Ty: MulTy, V: APIntOps::RoundingSDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2341 }
2342 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2343 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2344 NewC = ConstantInt::get(
2345 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::UP));
2346 } else {
2347 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2348 "Unexpected predicate");
2349 NewC = ConstantInt::get(
2350 Ty: MulTy, V: APIntOps::RoundingUDiv(A: C, B: *MulC, RM: APInt::Rounding::DOWN));
2351 }
2352 }
2353
2354 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2355}
2356
2357/// Fold icmp (shl nuw C2, Y), C.
2358static Instruction *foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl,
2359 const APInt &C) {
2360 Value *Y;
2361 const APInt *C2;
2362 if (!match(V: Shl, P: m_NUWShl(L: m_APInt(Res&: C2), R: m_Value(V&: Y))))
2363 return nullptr;
2364
2365 Type *ShiftType = Shl->getType();
2366 unsigned TypeBits = C.getBitWidth();
2367 ICmpInst::Predicate Pred = Cmp.getPredicate();
2368 if (Cmp.isUnsigned()) {
2369 if (C2->isZero() || C2->ugt(RHS: C))
2370 return nullptr;
2371 APInt Div, Rem;
2372 APInt::udivrem(LHS: C, RHS: *C2, Quotient&: Div, Remainder&: Rem);
2373 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2374
2375 // (1 << Y) pred C -> Y pred Log2(C)
2376 if (!CIsPowerOf2) {
2377 // (1 << Y) < 30 -> Y <= 4
2378 // (1 << Y) <= 30 -> Y <= 4
2379 // (1 << Y) >= 30 -> Y > 4
2380 // (1 << Y) > 30 -> Y > 4
2381 if (Pred == ICmpInst::ICMP_ULT)
2382 Pred = ICmpInst::ICMP_ULE;
2383 else if (Pred == ICmpInst::ICMP_UGE)
2384 Pred = ICmpInst::ICMP_UGT;
2385 }
2386
2387 unsigned CLog2 = Div.logBase2();
2388 return new ICmpInst(Pred, Y, ConstantInt::get(Ty: ShiftType, V: CLog2));
2389 } else if (Cmp.isSigned() && C2->isOne()) {
2390 Constant *BitWidthMinusOne = ConstantInt::get(Ty: ShiftType, V: TypeBits - 1);
2391 // (1 << Y) > 0 -> Y != 31
2392 // (1 << Y) > C -> Y != 31 if C is negative.
2393 if (Pred == ICmpInst::ICMP_SGT && C.sle(RHS: 0))
2394 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2395
2396 // (1 << Y) < 0 -> Y == 31
2397 // (1 << Y) < 1 -> Y == 31
2398 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2399 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2400 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(RHS: 0))
2401 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2402 }
2403
2404 return nullptr;
2405}
2406
2407/// Fold icmp (shl X, Y), C.
2408Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
2409 BinaryOperator *Shl,
2410 const APInt &C) {
2411 const APInt *ShiftVal;
2412 if (Cmp.isEquality() && match(V: Shl->getOperand(i_nocapture: 0), P: m_APInt(Res&: ShiftVal)))
2413 return foldICmpShlConstConst(I&: Cmp, A: Shl->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftVal);
2414
2415 ICmpInst::Predicate Pred = Cmp.getPredicate();
2416 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2417 // -> (icmp pred X, Csle0)
2418 //
2419 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2420 // so X's must be what is used.
2421 if (C.sle(RHS: 0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2422 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2423
2424 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2425 // -> (icmp eq/ne X, 0)
2426 if (ICmpInst::isEquality(P: Pred) && C.isZero() &&
2427 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2428 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2429
2430 // (icmp slt (shl nsw X, Y), 0/1)
2431 // -> (icmp slt X, 0/1)
2432 // (icmp sgt (shl nsw X, Y), 0/-1)
2433 // -> (icmp sgt X, 0/-1)
2434 //
2435 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2436 if (Shl->hasNoSignedWrap() &&
2437 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2438 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2439 return new ICmpInst(Pred, Shl->getOperand(i_nocapture: 0), Cmp.getOperand(i_nocapture: 1));
2440
2441 const APInt *ShiftAmt;
2442 if (!match(V: Shl->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmt)))
2443 return foldICmpShlLHSC(Cmp, Shl, C);
2444
2445 // Check that the shift amount is in range. If not, don't perform undefined
2446 // shifts. When the shift is visited, it will be simplified.
2447 unsigned TypeBits = C.getBitWidth();
2448 if (ShiftAmt->uge(RHS: TypeBits))
2449 return nullptr;
2450
2451 Value *X = Shl->getOperand(i_nocapture: 0);
2452 Type *ShType = Shl->getType();
2453
2454 // NSW guarantees that we are only shifting out sign bits from the high bits,
2455 // so we can ASHR the compare constant without needing a mask and eliminate
2456 // the shift.
2457 if (Shl->hasNoSignedWrap()) {
2458 if (Pred == ICmpInst::ICMP_SGT) {
2459 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2460 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2461 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2462 }
2463 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2464 C.ashr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2465 APInt ShiftedC = C.ashr(ShiftAmt: *ShiftAmt);
2466 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2467 }
2468 if (Pred == ICmpInst::ICMP_SLT) {
2469 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2470 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2471 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2472 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2473 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2474 APInt ShiftedC = (C - 1).ashr(ShiftAmt: *ShiftAmt) + 1;
2475 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2476 }
2477 }
2478
2479 // NUW guarantees that we are only shifting out zero bits from the high bits,
2480 // so we can LSHR the compare constant without needing a mask and eliminate
2481 // the shift.
2482 if (Shl->hasNoUnsignedWrap()) {
2483 if (Pred == ICmpInst::ICMP_UGT) {
2484 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2485 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2486 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2487 }
2488 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2489 C.lshr(ShiftAmt: *ShiftAmt).shl(ShiftAmt: *ShiftAmt) == C) {
2490 APInt ShiftedC = C.lshr(ShiftAmt: *ShiftAmt);
2491 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2492 }
2493 if (Pred == ICmpInst::ICMP_ULT) {
2494 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2495 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2496 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2497 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2498 assert(C.ugt(0) && "ult 0 should have been eliminated");
2499 APInt ShiftedC = (C - 1).lshr(ShiftAmt: *ShiftAmt) + 1;
2500 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShType, V: ShiftedC));
2501 }
2502 }
2503
2504 if (Cmp.isEquality() && Shl->hasOneUse()) {
2505 // Strength-reduce the shift into an 'and'.
2506 Constant *Mask = ConstantInt::get(
2507 Ty: ShType,
2508 V: APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShiftAmt->getZExtValue()));
2509 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2510 Constant *LShrC = ConstantInt::get(Ty: ShType, V: C.lshr(ShiftAmt: *ShiftAmt));
2511 return new ICmpInst(Pred, And, LShrC);
2512 }
2513
2514 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2515 bool TrueIfSigned = false;
2516 if (Shl->hasOneUse() && isSignBitCheck(Pred, RHS: C, TrueIfSigned)) {
2517 // (X << 31) <s 0 --> (X & 1) != 0
2518 Constant *Mask = ConstantInt::get(
2519 Ty: ShType,
2520 V: APInt::getOneBitSet(numBits: TypeBits, BitNo: TypeBits - ShiftAmt->getZExtValue() - 1));
2521 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shl->getName() + ".mask");
2522 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2523 And, Constant::getNullValue(Ty: ShType));
2524 }
2525
2526 // Simplify 'shl' inequality test into 'and' equality test.
2527 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2528 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2529 if ((C + 1).isPowerOf2() &&
2530 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2531 Value *And = Builder.CreateAnd(LHS: X, RHS: (~C).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2532 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2533 : ICmpInst::ICMP_NE,
2534 And, Constant::getNullValue(Ty: ShType));
2535 }
2536 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2537 if (C.isPowerOf2() &&
2538 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2539 Value *And =
2540 Builder.CreateAnd(LHS: X, RHS: (~(C - 1)).lshr(shiftAmt: ShiftAmt->getZExtValue()));
2541 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2542 : ICmpInst::ICMP_NE,
2543 And, Constant::getNullValue(Ty: ShType));
2544 }
2545 }
2546
2547 // Transform (icmp pred iM (shl iM %v, N), C)
2548 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2549 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2550 // This enables us to get rid of the shift in favor of a trunc that may be
2551 // free on the target. It has the additional benefit of comparing to a
2552 // smaller constant that may be more target-friendly.
2553 unsigned Amt = ShiftAmt->getLimitedValue(Limit: TypeBits - 1);
2554 if (Shl->hasOneUse() && Amt != 0 &&
2555 shouldChangeType(FromBitWidth: ShType->getScalarSizeInBits(), ToBitWidth: TypeBits - Amt)) {
2556 ICmpInst::Predicate CmpPred = Pred;
2557 APInt RHSC = C;
2558
2559 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(predicate: CmpPred)) {
2560 // Try the flipped strictness predicate.
2561 // e.g.:
2562 // icmp ult i64 (shl X, 32), 8589934593 ->
2563 // icmp ule i64 (shl X, 32), 8589934592 ->
2564 // icmp ule i32 (trunc X, i32), 2 ->
2565 // icmp ult i32 (trunc X, i32), 3
2566 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2567 Pred, C: ConstantInt::get(Context&: ShType->getContext(), V: C))) {
2568 CmpPred = FlippedStrictness->first;
2569 RHSC = cast<ConstantInt>(Val: FlippedStrictness->second)->getValue();
2570 }
2571 }
2572
2573 if (RHSC.countr_zero() >= Amt) {
2574 Type *TruncTy = ShType->getWithNewBitWidth(NewBitWidth: TypeBits - Amt);
2575 Constant *NewC =
2576 ConstantInt::get(Ty: TruncTy, V: RHSC.ashr(ShiftAmt: *ShiftAmt).trunc(width: TypeBits - Amt));
2577 return new ICmpInst(CmpPred,
2578 Builder.CreateTrunc(V: X, DestTy: TruncTy, Name: "", /*IsNUW=*/false,
2579 IsNSW: Shl->hasNoSignedWrap()),
2580 NewC);
2581 }
2582 }
2583
2584 return nullptr;
2585}
2586
2587/// Fold icmp ({al}shr X, Y), C.
2588Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
2589 BinaryOperator *Shr,
2590 const APInt &C) {
2591 // An exact shr only shifts out zero bits, so:
2592 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2593 Value *X = Shr->getOperand(i_nocapture: 0);
2594 CmpInst::Predicate Pred = Cmp.getPredicate();
2595 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2596 return new ICmpInst(Pred, X, Cmp.getOperand(i_nocapture: 1));
2597
2598 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2599 const APInt *ShiftValC;
2600 if (match(V: X, P: m_APInt(Res&: ShiftValC))) {
2601 if (Cmp.isEquality())
2602 return foldICmpShrConstConst(I&: Cmp, A: Shr->getOperand(i_nocapture: 1), AP1: C, AP2: *ShiftValC);
2603
2604 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2605 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2606 bool TrueIfSigned;
2607 if (!IsAShr && ShiftValC->isNegative() &&
2608 isSignBitCheck(Pred, RHS: C, TrueIfSigned))
2609 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2610 Shr->getOperand(i_nocapture: 1),
2611 ConstantInt::getNullValue(Ty: X->getType()));
2612
2613 // If the shifted constant is a power-of-2, test the shift amount directly:
2614 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2615 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2616 if (!IsAShr && ShiftValC->isPowerOf2() &&
2617 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2618 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2619 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2620 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2621
2622 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2623 unsigned ShiftLZ = ShiftValC->countl_zero();
2624 Constant *NewC = ConstantInt::get(Ty: Shr->getType(), V: CmpLZ - ShiftLZ);
2625 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2626 return new ICmpInst(NewPred, Shr->getOperand(i_nocapture: 1), NewC);
2627 }
2628 }
2629
2630 const APInt *ShiftAmtC;
2631 if (!match(V: Shr->getOperand(i_nocapture: 1), P: m_APInt(Res&: ShiftAmtC)))
2632 return nullptr;
2633
2634 // Check that the shift amount is in range. If not, don't perform undefined
2635 // shifts. When the shift is visited it will be simplified.
2636 unsigned TypeBits = C.getBitWidth();
2637 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(Limit: TypeBits);
2638 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2639 return nullptr;
2640
2641 bool IsExact = Shr->isExact();
2642 Type *ShrTy = Shr->getType();
2643 // TODO: If we could guarantee that InstSimplify would handle all of the
2644 // constant-value-based preconditions in the folds below, then we could assert
2645 // those conditions rather than checking them. This is difficult because of
2646 // undef/poison (PR34838).
2647 if (IsAShr && Shr->hasOneUse()) {
2648 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2649 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2650 // When C - 1 is a power of two and the transform can be legally
2651 // performed, prefer this form so the produced constant is close to a
2652 // power of two.
2653 // icmp slt/ult (ashr exact X, ShAmtC), C
2654 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2655 APInt ShiftedC = (C - 1).shl(shiftAmt: ShAmtVal) + 1;
2656 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2657 }
2658 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2659 // When ShAmtC can be shifted losslessly:
2660 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2661 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2662 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2663 if (ShiftedC.ashr(ShiftAmt: ShAmtVal) == C)
2664 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2665 }
2666 if (Pred == CmpInst::ICMP_SGT) {
2667 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2668 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2669 if (!C.isMaxSignedValue() && !(C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue() &&
2670 (ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1))
2671 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2672 }
2673 if (Pred == CmpInst::ICMP_UGT) {
2674 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2675 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2676 // clause accounts for that pattern.
2677 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2678 if ((ShiftedC + 1).ashr(ShiftAmt: ShAmtVal) == (C + 1) ||
2679 (C + 1).shl(shiftAmt: ShAmtVal).isMinSignedValue())
2680 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2681 }
2682
2683 // If the compare constant has significant bits above the lowest sign-bit,
2684 // then convert an unsigned cmp to a test of the sign-bit:
2685 // (ashr X, ShiftC) u> C --> X s< 0
2686 // (ashr X, ShiftC) u< C --> X s> -1
2687 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2688 if (Pred == CmpInst::ICMP_UGT) {
2689 return new ICmpInst(CmpInst::ICMP_SLT, X,
2690 ConstantInt::getNullValue(Ty: ShrTy));
2691 }
2692 if (Pred == CmpInst::ICMP_ULT) {
2693 return new ICmpInst(CmpInst::ICMP_SGT, X,
2694 ConstantInt::getAllOnesValue(Ty: ShrTy));
2695 }
2696 }
2697 } else if (!IsAShr) {
2698 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2699 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2700 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2701 APInt ShiftedC = C.shl(shiftAmt: ShAmtVal);
2702 if (ShiftedC.lshr(shiftAmt: ShAmtVal) == C)
2703 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2704 }
2705 if (Pred == CmpInst::ICMP_UGT) {
2706 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2707 APInt ShiftedC = (C + 1).shl(shiftAmt: ShAmtVal) - 1;
2708 if ((ShiftedC + 1).lshr(shiftAmt: ShAmtVal) == (C + 1))
2709 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: ShiftedC));
2710 }
2711 }
2712
2713 if (!Cmp.isEquality())
2714 return nullptr;
2715
2716 // Handle equality comparisons of shift-by-constant.
2717
2718 // If the comparison constant changes with the shift, the comparison cannot
2719 // succeed (bits of the comparison constant cannot match the shifted value).
2720 // This should be known by InstSimplify and already be folded to true/false.
2721 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2722 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2723 "Expected icmp+shr simplify did not occur.");
2724
2725 // If the bits shifted out are known zero, compare the unshifted value:
2726 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2727 if (Shr->isExact())
2728 return new ICmpInst(Pred, X, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2729
2730 if (Shr->hasOneUse()) {
2731 // Canonicalize the shift into an 'and':
2732 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2733 APInt Val(APInt::getHighBitsSet(numBits: TypeBits, hiBitsSet: TypeBits - ShAmtVal));
2734 Constant *Mask = ConstantInt::get(Ty: ShrTy, V: Val);
2735 Value *And = Builder.CreateAnd(LHS: X, RHS: Mask, Name: Shr->getName() + ".mask");
2736 return new ICmpInst(Pred, And, ConstantInt::get(Ty: ShrTy, V: C << ShAmtVal));
2737 }
2738
2739 return nullptr;
2740}
2741
2742Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
2743 BinaryOperator *SRem,
2744 const APInt &C) {
2745 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2746 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2747 // Canonicalize unsigned predicates to signed:
2748 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2749 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2750 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2751 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2752
2753 const APInt *DivisorC;
2754 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_APInt(Res&: DivisorC)))
2755 return nullptr;
2756 if (DivisorC->isZero())
2757 return nullptr;
2758
2759 APInt NormalizedC = C;
2760 if (Pred == ICmpInst::ICMP_ULT) {
2761 assert(!NormalizedC.isZero() &&
2762 "ult X, 0 should have been simplified already.");
2763 --NormalizedC;
2764 }
2765 if (C.isNegative())
2766 NormalizedC.flipAllBits();
2767 if (!NormalizedC.uge(RHS: DivisorC->abs() - 1))
2768 return nullptr;
2769
2770 Type *Ty = SRem->getType();
2771 if (Pred == ICmpInst::ICMP_UGT)
2772 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2773 ConstantInt::getNullValue(Ty));
2774 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2775 ConstantInt::getAllOnesValue(Ty));
2776 }
2777 // Match an 'is positive' or 'is negative' comparison of remainder by a
2778 // constant power-of-2 value:
2779 // (X % pow2C) sgt/slt 0
2780 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2781 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2782 return nullptr;
2783
2784 // TODO: The one-use check is standard because we do not typically want to
2785 // create longer instruction sequences, but this might be a special-case
2786 // because srem is not good for analysis or codegen.
2787 if (!SRem->hasOneUse())
2788 return nullptr;
2789
2790 const APInt *DivisorC;
2791 if (!match(V: SRem->getOperand(i_nocapture: 1), P: m_Power2(V&: DivisorC)))
2792 return nullptr;
2793
2794 // For cmp_sgt/cmp_slt only zero valued C is handled.
2795 // For cmp_eq/cmp_ne only positive valued C is handled.
2796 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2797 !C.isZero()) ||
2798 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2799 !C.isStrictlyPositive()))
2800 return nullptr;
2801
2802 // Mask off the sign bit and the modulo bits (low-bits).
2803 Type *Ty = SRem->getType();
2804 APInt SignMask = APInt::getSignMask(BitWidth: Ty->getScalarSizeInBits());
2805 Constant *MaskC = ConstantInt::get(Ty, V: SignMask | (*DivisorC - 1));
2806 Value *And = Builder.CreateAnd(LHS: SRem->getOperand(i_nocapture: 0), RHS: MaskC);
2807
2808 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2809 return new ICmpInst(Pred, And, ConstantInt::get(Ty, V: C));
2810
2811 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2812 // bit is set. Example:
2813 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2814 if (Pred == ICmpInst::ICMP_SGT)
2815 return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
2816
2817 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2818 // bit is set. Example:
2819 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2820 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, V: SignMask));
2821}
2822
2823/// Fold icmp (udiv X, Y), C.
2824Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
2825 BinaryOperator *UDiv,
2826 const APInt &C) {
2827 ICmpInst::Predicate Pred = Cmp.getPredicate();
2828 Value *X = UDiv->getOperand(i_nocapture: 0);
2829 Value *Y = UDiv->getOperand(i_nocapture: 1);
2830 Type *Ty = UDiv->getType();
2831
2832 const APInt *C2;
2833 if (!match(V: X, P: m_APInt(Res&: C2)))
2834 return nullptr;
2835
2836 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2837
2838 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2839 if (Pred == ICmpInst::ICMP_UGT) {
2840 assert(!C.isMaxValue() &&
2841 "icmp ugt X, UINT_MAX should have been simplified already.");
2842 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2843 ConstantInt::get(Ty, V: C2->udiv(RHS: C + 1)));
2844 }
2845
2846 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2847 if (Pred == ICmpInst::ICMP_ULT) {
2848 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2849 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2850 ConstantInt::get(Ty, V: C2->udiv(RHS: C)));
2851 }
2852
2853 return nullptr;
2854}
2855
2856/// Fold icmp ({su}div X, Y), C.
2857Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
2858 BinaryOperator *Div,
2859 const APInt &C) {
2860 ICmpInst::Predicate Pred = Cmp.getPredicate();
2861 Value *X = Div->getOperand(i_nocapture: 0);
2862 Value *Y = Div->getOperand(i_nocapture: 1);
2863 Type *Ty = Div->getType();
2864 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2865
2866 // If unsigned division and the compare constant is bigger than
2867 // UMAX/2 (negative), there's only one pair of values that satisfies an
2868 // equality check, so eliminate the division:
2869 // (X u/ Y) == C --> (X == C) && (Y == 1)
2870 // (X u/ Y) != C --> (X != C) || (Y != 1)
2871 // Similarly, if signed division and the compare constant is exactly SMIN:
2872 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2873 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2874 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2875 (!DivIsSigned || C.isMinSignedValue())) {
2876 Value *XBig = Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty, V: C));
2877 Value *YOne = Builder.CreateICmp(P: Pred, LHS: Y, RHS: ConstantInt::get(Ty, V: 1));
2878 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2879 return BinaryOperator::Create(Op: Logic, S1: XBig, S2: YOne);
2880 }
2881
2882 // Fold: icmp pred ([us]div X, C2), C -> range test
2883 // Fold this div into the comparison, producing a range check.
2884 // Determine, based on the divide type, what the range is being
2885 // checked. If there is an overflow on the low or high side, remember
2886 // it, otherwise compute the range [low, hi) bounding the new value.
2887 // See: InsertRangeTest above for the kinds of replacements possible.
2888 const APInt *C2;
2889 if (!match(V: Y, P: m_APInt(Res&: C2)))
2890 return nullptr;
2891
2892 // FIXME: If the operand types don't match the type of the divide
2893 // then don't attempt this transform. The code below doesn't have the
2894 // logic to deal with a signed divide and an unsigned compare (and
2895 // vice versa). This is because (x /s C2) <s C produces different
2896 // results than (x /s C2) <u C or (x /u C2) <s C or even
2897 // (x /u C2) <u C. Simply casting the operands and result won't
2898 // work. :( The if statement below tests that condition and bails
2899 // if it finds it.
2900 // However, when the divisor is a positive constant and the dividend is
2901 // known non-negative, sdiv is equivalent to udiv, so we can lower
2902 // DivIsSigned and proceed through the unsigned path.
2903 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2904 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2905 !isKnownNonNegative(V: X, SQ: SQ.getWithInstruction(I: &Cmp)))
2906 return nullptr;
2907 DivIsSigned = false;
2908 }
2909
2910 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2911 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2912 // division-by-constant cases should be present, we can not assert that they
2913 // have happened before we reach this icmp instruction.
2914 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2915 return nullptr;
2916
2917 // Compute Prod = C * C2. We are essentially solving an equation of
2918 // form X / C2 = C. We solve for X by multiplying C2 and C.
2919 // By solving for X, we can turn this into a range check instead of computing
2920 // a divide.
2921 APInt Prod = C * *C2;
2922
2923 // Determine if the product overflows by seeing if the product is not equal to
2924 // the divide. Make sure we do the same kind of divide as in the LHS
2925 // instruction that we're folding.
2926 bool ProdOV = (DivIsSigned ? Prod.sdiv(RHS: *C2) : Prod.udiv(RHS: *C2)) != C;
2927
2928 // If the division is known to be exact, then there is no remainder from the
2929 // divide, so the covered range size is unit, otherwise it is the divisor.
2930 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2931
2932 // Figure out the interval that is being checked. For example, a comparison
2933 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2934 // Compute this interval based on the constants involved and the signedness of
2935 // the compare/divide. This computes a half-open interval, keeping track of
2936 // whether either value in the interval overflows. After analysis each
2937 // overflow variable is set to 0 if it's corresponding bound variable is valid
2938 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2939 int LoOverflow = 0, HiOverflow = 0;
2940 APInt LoBound, HiBound;
2941
2942 if (!DivIsSigned) { // udiv
2943 // e.g. X/5 op 3 --> [15, 20)
2944 LoBound = Prod;
2945 HiOverflow = LoOverflow = ProdOV;
2946 if (!HiOverflow) {
2947 // If this is not an exact divide, then many values in the range collapse
2948 // to the same result value.
2949 HiOverflow = addWithOverflow(Result&: HiBound, In1: LoBound, In2: RangeSize, IsSigned: false);
2950 }
2951 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2952 if (C.isZero()) { // (X / pos) op 0
2953 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2954 LoBound = -(RangeSize - 1);
2955 HiBound = RangeSize;
2956 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2957 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2958 HiOverflow = LoOverflow = ProdOV;
2959 if (!HiOverflow)
2960 HiOverflow = addWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2961 } else { // (X / pos) op neg
2962 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2963 HiBound = Prod + 1;
2964 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2965 if (!LoOverflow) {
2966 APInt DivNeg = -RangeSize;
2967 LoOverflow = addWithOverflow(Result&: LoBound, In1: HiBound, In2: DivNeg, IsSigned: true) ? -1 : 0;
2968 }
2969 }
2970 } else if (C2->isNegative()) { // Divisor is < 0.
2971 if (Div->isExact())
2972 RangeSize.negate();
2973 if (C.isZero()) { // (X / neg) op 0
2974 // e.g. X/-5 op 0 --> [-4, 5)
2975 LoBound = RangeSize + 1;
2976 HiBound = -RangeSize;
2977 if (HiBound == *C2) { // -INTMIN = INTMIN
2978 HiOverflow = 1; // [INTMIN+1, overflow)
2979 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2980 }
2981 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2982 // e.g. X/-5 op 3 --> [-19, -14)
2983 HiBound = Prod + 1;
2984 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2985 if (!LoOverflow)
2986 LoOverflow =
2987 addWithOverflow(Result&: LoBound, In1: HiBound, In2: RangeSize, IsSigned: true) ? -1 : 0;
2988 } else { // (X / neg) op neg
2989 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2990 LoOverflow = HiOverflow = ProdOV;
2991 if (!HiOverflow)
2992 HiOverflow = subWithOverflow(Result&: HiBound, In1: Prod, In2: RangeSize, IsSigned: true);
2993 }
2994
2995 // Dividing by a negative swaps the condition. LT <-> GT
2996 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
2997 }
2998
2999 switch (Pred) {
3000 default:
3001 llvm_unreachable("Unhandled icmp predicate!");
3002 case ICmpInst::ICMP_EQ:
3003 if (LoOverflow && HiOverflow)
3004 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3005 if (HiOverflow)
3006 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3007 X, ConstantInt::get(Ty, V: LoBound));
3008 if (LoOverflow)
3009 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3010 X, ConstantInt::get(Ty, V: HiBound));
3011 return replaceInstUsesWith(
3012 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: true));
3013 case ICmpInst::ICMP_NE:
3014 if (LoOverflow && HiOverflow)
3015 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3016 if (HiOverflow)
3017 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3018 X, ConstantInt::get(Ty, V: LoBound));
3019 if (LoOverflow)
3020 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3021 X, ConstantInt::get(Ty, V: HiBound));
3022 return replaceInstUsesWith(
3023 I&: Cmp, V: insertRangeTest(V: X, Lo: LoBound, Hi: HiBound, isSigned: DivIsSigned, Inside: false));
3024 case ICmpInst::ICMP_ULT:
3025 case ICmpInst::ICMP_SLT:
3026 if (LoOverflow == +1) // Low bound is greater than input range.
3027 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3028 if (LoOverflow == -1) // Low bound is less than input range.
3029 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3030 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: LoBound));
3031 case ICmpInst::ICMP_UGT:
3032 case ICmpInst::ICMP_SGT:
3033 if (HiOverflow == +1) // High bound greater than input range.
3034 return replaceInstUsesWith(I&: Cmp, V: Builder.getFalse());
3035 if (HiOverflow == -1) // High bound less than input range.
3036 return replaceInstUsesWith(I&: Cmp, V: Builder.getTrue());
3037 if (Pred == ICmpInst::ICMP_UGT)
3038 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: HiBound));
3039 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: HiBound));
3040 }
3041
3042 return nullptr;
3043}
3044
3045/// Fold icmp (sub X, Y), C.
3046Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
3047 BinaryOperator *Sub,
3048 const APInt &C) {
3049 Value *X = Sub->getOperand(i_nocapture: 0), *Y = Sub->getOperand(i_nocapture: 1);
3050 ICmpInst::Predicate Pred = Cmp.getPredicate();
3051 Type *Ty = Sub->getType();
3052
3053 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3054 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3055 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3056 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3057 const APInt *D;
3058 if (match(V: Y, P: m_URem(L: m_Specific(V: X), R: m_APInt(Res&: D))) && !D->isZero()) {
3059 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: *D))
3060 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: *D - 1));
3061 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(RHS: *D))
3062 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: *D));
3063 }
3064
3065 // (SubC - Y) == C) --> Y == (SubC - C)
3066 // (SubC - Y) != C) --> Y != (SubC - C)
3067 Constant *SubC;
3068 if (Cmp.isEquality() && match(V: X, P: m_ImmConstant(C&: SubC))) {
3069 return new ICmpInst(Pred, Y,
3070 ConstantExpr::getSub(C1: SubC, C2: ConstantInt::get(Ty, V: C)));
3071 }
3072
3073 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3074 const APInt *C2;
3075 APInt SubResult;
3076 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3077 bool HasNSW = Sub->hasNoSignedWrap();
3078 bool HasNUW = Sub->hasNoUnsignedWrap();
3079 if (match(V: X, P: m_APInt(Res&: C2)) &&
3080 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3081 !subWithOverflow(Result&: SubResult, In1: *C2, In2: C, IsSigned: Cmp.isSigned()))
3082 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, V: SubResult));
3083
3084 // X - Y == 0 --> X == Y.
3085 // X - Y != 0 --> X != Y.
3086 // TODO: We allow this with multiple uses as long as the other uses are not
3087 // in phis. The phi use check is guarding against a codegen regression
3088 // for a loop test. If the backend could undo this (and possibly
3089 // subsequent transforms), we would not need this hack.
3090 if (Cmp.isEquality() && C.isZero() &&
3091 none_of(Range: (Sub->users()), P: [](const User *U) { return isa<PHINode>(Val: U); }))
3092 return new ICmpInst(Pred, X, Y);
3093
3094 // The following transforms are only worth it if the only user of the subtract
3095 // is the icmp.
3096 // TODO: This is an artificial restriction for all of the transforms below
3097 // that only need a single replacement icmp. Can these use the phi test
3098 // like the transform above here?
3099 if (!Sub->hasOneUse())
3100 return nullptr;
3101
3102 if (Sub->hasNoSignedWrap()) {
3103 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3104 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3105 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3106
3107 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3108 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3109 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3110
3111 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3112 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3113 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3114
3115 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3116 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3117 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3118 }
3119
3120 if (!match(V: X, P: m_APInt(Res&: C2)))
3121 return nullptr;
3122
3123 // C2 - Y <u C -> (Y | (C - 1)) == C2
3124 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3125 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3126 (*C2 & (C - 1)) == (C - 1))
3127 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(LHS: Y, RHS: C - 1), X);
3128
3129 // C2 - Y >u C -> (Y | C) != C2
3130 // iff C2 & C == C and C + 1 is a power of 2
3131 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3132 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(LHS: Y, RHS: C), X);
3133
3134 // We have handled special cases that reduce.
3135 // Canonicalize any remaining sub to add as:
3136 // (C2 - Y) > C --> (Y + ~C2) < ~C
3137 Value *Add = Builder.CreateAdd(LHS: Y, RHS: ConstantInt::get(Ty, V: ~(*C2)), Name: "notsub",
3138 HasNUW, HasNSW);
3139 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, V: ~C));
3140}
3141
3142static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3143 Value *Op1, IRBuilderBase &Builder,
3144 bool HasOneUse) {
3145 auto FoldConstant = [&](bool Val) {
3146 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3147 if (Op0->getType()->isVectorTy())
3148 Res = ConstantVector::getSplat(
3149 EC: cast<VectorType>(Val: Op0->getType())->getElementCount(), Elt: Res);
3150 return Res;
3151 };
3152
3153 switch (Table.to_ulong()) {
3154 case 0: // 0 0 0 0
3155 return FoldConstant(false);
3156 case 1: // 0 0 0 1
3157 return HasOneUse ? Builder.CreateNot(V: Builder.CreateOr(LHS: Op0, RHS: Op1)) : nullptr;
3158 case 2: // 0 0 1 0
3159 return HasOneUse ? Builder.CreateAnd(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3160 case 3: // 0 0 1 1
3161 return Builder.CreateNot(V: Op0);
3162 case 4: // 0 1 0 0
3163 return HasOneUse ? Builder.CreateAnd(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3164 case 5: // 0 1 0 1
3165 return Builder.CreateNot(V: Op1);
3166 case 6: // 0 1 1 0
3167 return Builder.CreateXor(LHS: Op0, RHS: Op1);
3168 case 7: // 0 1 1 1
3169 return HasOneUse ? Builder.CreateNot(V: Builder.CreateAnd(LHS: Op0, RHS: Op1)) : nullptr;
3170 case 8: // 1 0 0 0
3171 return Builder.CreateAnd(LHS: Op0, RHS: Op1);
3172 case 9: // 1 0 0 1
3173 return HasOneUse ? Builder.CreateNot(V: Builder.CreateXor(LHS: Op0, RHS: Op1)) : nullptr;
3174 case 10: // 1 0 1 0
3175 return Op1;
3176 case 11: // 1 0 1 1
3177 return HasOneUse ? Builder.CreateOr(LHS: Builder.CreateNot(V: Op0), RHS: Op1) : nullptr;
3178 case 12: // 1 1 0 0
3179 return Op0;
3180 case 13: // 1 1 0 1
3181 return HasOneUse ? Builder.CreateOr(LHS: Op0, RHS: Builder.CreateNot(V: Op1)) : nullptr;
3182 case 14: // 1 1 1 0
3183 return Builder.CreateOr(LHS: Op0, RHS: Op1);
3184 case 15: // 1 1 1 1
3185 return FoldConstant(true);
3186 default:
3187 llvm_unreachable("Invalid Operation");
3188 }
3189 return nullptr;
3190}
3191
3192Instruction *InstCombinerImpl::foldICmpBinOpWithConstantViaTruthTable(
3193 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3194 Value *A, *B;
3195 Constant *C1, *C2, *C3, *C4;
3196 if (!match(V: BO->getOperand(i_nocapture: 0),
3197 P: m_SelectLike(C: m_Value(V&: A), TrueC: m_Constant(C&: C1), FalseC: m_Constant(C&: C2))) ||
3198 !match(V: BO->getOperand(i_nocapture: 1),
3199 P: m_SelectLike(C: m_Value(V&: B), TrueC: m_Constant(C&: C3), FalseC: m_Constant(C&: C4))) ||
3200 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3201 return nullptr;
3202
3203 std::bitset<4> Table;
3204 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3205 Constant *L = First ? C1 : C2;
3206 Constant *R = Second ? C3 : C4;
3207 if (auto *Res = ConstantFoldBinaryOpOperands(Opcode: BO->getOpcode(), LHS: L, RHS: R, DL)) {
3208 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3209 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3210 return ICmpInst::compare(LHS: CI->getValue(), RHS: C, Pred: Cmp.getPredicate());
3211 }
3212 return std::nullopt;
3213 };
3214
3215 for (unsigned I = 0; I < 4; ++I) {
3216 bool First = (I >> 1) & 1;
3217 bool Second = I & 1;
3218 if (auto Res = ComputeTable(First, Second))
3219 Table[I] = *Res;
3220 else
3221 return nullptr;
3222 }
3223
3224 // Synthesize optimal logic.
3225 if (auto *Cond = createLogicFromTable(Table, Op0: A, Op1: B, Builder, HasOneUse: BO->hasOneUse()))
3226 return replaceInstUsesWith(I&: Cmp, V: Cond);
3227 return nullptr;
3228}
3229
3230/// Fold icmp (add X, Y), C.
3231Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
3232 BinaryOperator *Add,
3233 const APInt &C) {
3234 Value *Y = Add->getOperand(i_nocapture: 1);
3235 Value *X = Add->getOperand(i_nocapture: 0);
3236 const CmpPredicate Pred = Cmp.getCmpPredicate();
3237
3238 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3239 // when C <= (1 << ShAmtC).
3240 const APInt *ShAmtC;
3241 Value *A;
3242 unsigned BitWidth = C.getBitWidth();
3243 if (Pred == ICmpInst::ICMP_ULT &&
3244 match(V: Add,
3245 P: m_c_NUWAdd(L: m_Value(V&: A), R: m_LShr(L: m_Deferred(V: A), R: m_APInt(Res&: ShAmtC)))) &&
3246 ShAmtC->ult(RHS: BitWidth) &&
3247 C.ule(RHS: APInt::getOneBitSet(numBits: BitWidth, BitNo: ShAmtC->getZExtValue())))
3248 return new ICmpInst(Pred, A, ConstantInt::get(Ty: A->getType(), V: C));
3249
3250 const APInt *C2;
3251 if (Cmp.isEquality() || !match(V: Y, P: m_APInt(Res&: C2)))
3252 return nullptr;
3253
3254 // Fold icmp pred (add X, C2), C.
3255 Type *Ty = Add->getType();
3256
3257 // If the add does not wrap, we can always adjust the compare by subtracting
3258 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3259 // have been canonicalized to SGT/SLT/UGT/ULT.
3260 if (Add->hasNoUnsignedWrap() &&
3261 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3262 bool Overflow;
3263 APInt NewC = C.usub_ov(RHS: *C2, Overflow);
3264 // If there is overflow, the result must be true or false.
3265 if (!Overflow)
3266 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3267 return new ICmpInst(Pred, X, ConstantInt::get(Ty, V: NewC));
3268 }
3269
3270 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3271
3272 if (Add->hasNoSignedWrap() &&
3273 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3274 bool Overflow;
3275 APInt NewC = C.ssub_ov(RHS: *C2, Overflow);
3276 if (!Overflow)
3277 // icmp samesign ugt/ult (add nsw X, C2), C
3278 // -> icmp sgt/slt X, (C - C2)
3279 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, V: NewC));
3280 }
3281
3282 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3283 C.isNonNegative() && (C - *C2).isNonNegative() &&
3284 computeConstantRange(V: X, /*ForSigned=*/true, SQ: SQ.getWithInstruction(I: &Cmp))
3285 .add(Other: *C2)
3286 .isAllNonNegative())
3287 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3288 ConstantInt::get(Ty, V: C - *C2));
3289
3290 auto CR = ConstantRange::makeExactICmpRegion(Pred, Other: C).subtract(CI: *C2);
3291 const APInt &Upper = CR.getUpper();
3292 const APInt &Lower = CR.getLower();
3293 if (Cmp.isSigned()) {
3294 if (Lower.isSignMask())
3295 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: Upper));
3296 if (Upper.isSignMask())
3297 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, V: Lower));
3298 } else {
3299 if (Lower.isMinValue())
3300 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: Upper));
3301 if (Upper.isMinValue())
3302 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, V: Lower));
3303 }
3304
3305 // This set of folds is intentionally placed after folds that use no-wrapping
3306 // flags because those folds are likely better for later analysis/codegen.
3307 const APInt SMax = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
3308 const APInt SMin = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
3309
3310 // Fold compare with offset to opposite sign compare if it eliminates offset:
3311 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3312 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3313 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, V: -(*C2)));
3314
3315 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3316 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3317 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, V: ~(*C2)));
3318
3319 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3320 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3321 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, V: SMax - C));
3322
3323 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3324 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3325 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, V: C ^ SMax));
3326
3327 // (X + -1) <u C --> X <=u C (if X is never null)
3328 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3329 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3330 if (llvm::isKnownNonZero(V: X, Q))
3331 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, V: C));
3332 }
3333
3334 if (!Add->hasOneUse())
3335 return nullptr;
3336
3337 // X+C <u C2 -> (X & -C2) == C
3338 // iff C & (C2-1) == 0
3339 // C2 is a power of 2
3340 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3341 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(LHS: X, RHS: -C),
3342 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3343
3344 // X+C2 <u C -> (X & C) == 2C
3345 // iff C == -(C2)
3346 // C2 is a power of 2
3347 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3348 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: C),
3349 ConstantInt::get(Ty, V: C * 2));
3350
3351 // X+C >u C2 -> (X & ~C2) != C
3352 // iff C & C2 == 0
3353 // C2+1 is a power of 2
3354 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3355 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(LHS: X, RHS: ~C),
3356 ConstantExpr::getNeg(C: cast<Constant>(Val: Y)));
3357
3358 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3359 // to the ult form.
3360 // X+C2 >u C -> X+(C2-C-1) <u ~C
3361 if (Pred == ICmpInst::ICMP_UGT)
3362 return new ICmpInst(ICmpInst::ICMP_ULT,
3363 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *C2 - C - 1)),
3364 ConstantInt::get(Ty, V: ~C));
3365
3366 // zext(V) + C2 pred C -> V + C3 pred' C4
3367 Value *V;
3368 if (match(V: X, P: m_ZExt(Op: m_Value(V)))) {
3369 Type *NewCmpTy = V->getType();
3370 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3371 if (shouldChangeType(From: Ty, To: NewCmpTy)) {
3372 ConstantRange SrcCR = CR.truncate(BitWidth: NewCmpBW, NoWrapKind: TruncInst::NoUnsignedWrap);
3373 CmpInst::Predicate EquivPred;
3374 APInt EquivInt;
3375 APInt EquivOffset;
3376
3377 SrcCR.getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
3378 return new ICmpInst(
3379 EquivPred,
3380 EquivOffset.isZero()
3381 ? V
3382 : Builder.CreateAdd(LHS: V, RHS: ConstantInt::get(Ty: NewCmpTy, V: EquivOffset)),
3383 ConstantInt::get(Ty: NewCmpTy, V: EquivInt));
3384 }
3385 }
3386
3387 return nullptr;
3388}
3389
3390bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
3391 Value *&RHS, ConstantInt *&Less,
3392 ConstantInt *&Equal,
3393 ConstantInt *&Greater) {
3394 // TODO: Generalize this to work with other comparison idioms or ensure
3395 // they get canonicalized into this form.
3396
3397 // select i1 (a == b),
3398 // i32 Equal,
3399 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3400 // where Equal, Less and Greater are placeholders for any three constants.
3401 CmpPredicate PredA;
3402 if (!match(V: SI->getCondition(), P: m_ICmp(Pred&: PredA, L: m_Value(V&: LHS), R: m_Value(V&: RHS))) ||
3403 !ICmpInst::isEquality(P: PredA))
3404 return false;
3405 Value *EqualVal = SI->getTrueValue();
3406 Value *UnequalVal = SI->getFalseValue();
3407 // We still can get non-canonical predicate here, so canonicalize.
3408 if (PredA == ICmpInst::ICMP_NE)
3409 std::swap(a&: EqualVal, b&: UnequalVal);
3410 if (!match(V: EqualVal, P: m_ConstantInt(CI&: Equal)))
3411 return false;
3412 CmpPredicate PredB;
3413 Value *LHS2, *RHS2;
3414 if (!match(V: UnequalVal, P: m_Select(C: m_ICmp(Pred&: PredB, L: m_Value(V&: LHS2), R: m_Value(V&: RHS2)),
3415 L: m_ConstantInt(CI&: Less), R: m_ConstantInt(CI&: Greater))))
3416 return false;
3417 // We can get predicate mismatch here, so canonicalize if possible:
3418 // First, ensure that 'LHS' match.
3419 if (LHS2 != LHS) {
3420 // x sgt y <--> y slt x
3421 std::swap(a&: LHS2, b&: RHS2);
3422 PredB = ICmpInst::getSwappedPredicate(pred: PredB);
3423 }
3424 if (LHS2 != LHS)
3425 return false;
3426 // We also need to canonicalize 'RHS'.
3427 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(Val: RHS2)) {
3428 // x sgt C-1 <--> x sge C <--> not(x slt C)
3429 auto FlippedStrictness =
3430 getFlippedStrictnessPredicateAndConstant(Pred: PredB, C: cast<Constant>(Val: RHS2));
3431 if (!FlippedStrictness)
3432 return false;
3433 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3434 "basic correctness failure");
3435 RHS2 = FlippedStrictness->second;
3436 // And kind-of perform the result swap.
3437 std::swap(a&: Less, b&: Greater);
3438 PredB = ICmpInst::ICMP_SLT;
3439 }
3440 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3441}
3442
3443Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
3444 SelectInst *Select,
3445 ConstantInt *C) {
3446
3447 assert(C && "Cmp RHS should be a constant int!");
3448 // If we're testing a constant value against the result of a three way
3449 // comparison, the result can be expressed directly in terms of the
3450 // original values being compared. Note: We could possibly be more
3451 // aggressive here and remove the hasOneUse test. The original select is
3452 // really likely to simplify or sink when we remove a test of the result.
3453 Value *OrigLHS, *OrigRHS;
3454 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3455 if (Cmp.hasOneUse() &&
3456 matchThreeWayIntCompare(SI: Select, LHS&: OrigLHS, RHS&: OrigRHS, Less&: C1LessThan, Equal&: C2Equal,
3457 Greater&: C3GreaterThan)) {
3458 assert(C1LessThan && C2Equal && C3GreaterThan);
3459
3460 bool TrueWhenLessThan = ICmpInst::compare(
3461 LHS: C1LessThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3462 bool TrueWhenEqual = ICmpInst::compare(LHS: C2Equal->getValue(), RHS: C->getValue(),
3463 Pred: Cmp.getPredicate());
3464 bool TrueWhenGreaterThan = ICmpInst::compare(
3465 LHS: C3GreaterThan->getValue(), RHS: C->getValue(), Pred: Cmp.getPredicate());
3466
3467 // This generates the new instruction that will replace the original Cmp
3468 // Instruction. Instead of enumerating the various combinations when
3469 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3470 // false, we rely on chaining of ORs and future passes of InstCombine to
3471 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3472
3473 // When none of the three constants satisfy the predicate for the RHS (C),
3474 // the entire original Cmp can be simplified to a false.
3475 Value *Cond = Builder.getFalse();
3476 if (TrueWhenLessThan)
3477 Cond = Builder.CreateOr(
3478 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SLT, LHS: OrigLHS, RHS: OrigRHS));
3479 if (TrueWhenEqual)
3480 Cond = Builder.CreateOr(
3481 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: OrigLHS, RHS: OrigRHS));
3482 if (TrueWhenGreaterThan)
3483 Cond = Builder.CreateOr(
3484 LHS: Cond, RHS: Builder.CreateICmp(P: ICmpInst::ICMP_SGT, LHS: OrigLHS, RHS: OrigRHS));
3485
3486 return replaceInstUsesWith(I&: Cmp, V: Cond);
3487 }
3488 return nullptr;
3489}
3490
3491Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
3492 auto *Bitcast = dyn_cast<BitCastInst>(Val: Cmp.getOperand(i_nocapture: 0));
3493 if (!Bitcast)
3494 return nullptr;
3495
3496 ICmpInst::Predicate Pred = Cmp.getPredicate();
3497 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
3498 Value *BCSrcOp = Bitcast->getOperand(i_nocapture: 0);
3499 Type *SrcType = Bitcast->getSrcTy();
3500 Type *DstType = Bitcast->getType();
3501
3502 // Make sure the bitcast doesn't change between scalar and vector and
3503 // doesn't change the number of vector elements.
3504 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3505 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3506 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3507 Value *X;
3508 if (match(V: BCSrcOp, P: m_SIToFP(Op: m_Value(V&: X)))) {
3509 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3510 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3511 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3512 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3513 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3514 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3515 match(V: Op1, P: m_Zero()))
3516 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3517
3518 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3519 if (Pred == ICmpInst::ICMP_SLT && match(V: Op1, P: m_One()))
3520 return new ICmpInst(Pred, X, ConstantInt::get(Ty: X->getType(), V: 1));
3521
3522 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3523 if (Pred == ICmpInst::ICMP_SGT && match(V: Op1, P: m_AllOnes()))
3524 return new ICmpInst(Pred, X,
3525 ConstantInt::getAllOnesValue(Ty: X->getType()));
3526 }
3527
3528 // Zero-equality checks are preserved through unsigned floating-point casts:
3529 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3530 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3531 if (match(V: BCSrcOp, P: m_UIToFP(Op: m_Value(V&: X))))
3532 if (Cmp.isEquality() && match(V: Op1, P: m_Zero()))
3533 return new ICmpInst(Pred, X, ConstantInt::getNullValue(Ty: X->getType()));
3534
3535 const APInt *C;
3536 bool TrueIfSigned;
3537 if (match(V: Op1, P: m_APInt(Res&: C)) && Bitcast->hasOneUse()) {
3538 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3539 // the FP extend/truncate because that cast does not change the sign-bit.
3540 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3541 // The sign-bit is always the most significant bit in those types.
3542 if (isSignBitCheck(Pred, RHS: *C, TrueIfSigned) &&
3543 (match(V: BCSrcOp, P: m_FPExt(Op: m_Value(V&: X))) ||
3544 match(V: BCSrcOp, P: m_FPTrunc(Op: m_Value(V&: X))))) {
3545 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3546 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3547 Type *XType = X->getType();
3548
3549 // We can't currently handle Power style floating point operations here.
3550 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3551 Type *NewType = Builder.getIntNTy(N: XType->getScalarSizeInBits());
3552 if (auto *XVTy = dyn_cast<VectorType>(Val: XType))
3553 NewType = VectorType::get(ElementType: NewType, EC: XVTy->getElementCount());
3554 Value *NewBitcast = Builder.CreateBitCast(V: X, DestTy: NewType);
3555 if (TrueIfSigned)
3556 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3557 ConstantInt::getNullValue(Ty: NewType));
3558 else
3559 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3560 ConstantInt::getAllOnesValue(Ty: NewType));
3561 }
3562 }
3563
3564 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3565 Type *FPType = SrcType->getScalarType();
3566 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3567 Kind: Attribute::NoImplicitFloat) &&
3568 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3569 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3570 if (Mask & (fcInf | fcZero)) {
3571 if (Pred == ICmpInst::ICMP_NE)
3572 Mask = ~Mask;
3573 return replaceInstUsesWith(I&: Cmp,
3574 V: Builder.createIsFPClass(FPNum: BCSrcOp, Test: Mask));
3575 }
3576 }
3577 }
3578 }
3579
3580 const APInt *C;
3581 if (!match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) || !DstType->isIntegerTy() ||
3582 !SrcType->isIntOrIntVectorTy())
3583 return nullptr;
3584
3585 // If this is checking if all elements of a vector compare are set or not,
3586 // invert the casted vector equality compare and test if all compare
3587 // elements are clear or not. Compare against zero is generally easier for
3588 // analysis and codegen.
3589 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3590 // Example: are all elements equal? --> are zero elements not equal?
3591 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3592 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3593 if (Value *NotBCSrcOp =
3594 getFreelyInverted(V: BCSrcOp, WillInvertAllUses: BCSrcOp->hasOneUse(), Builder: &Builder)) {
3595 Value *Cast = Builder.CreateBitCast(V: NotBCSrcOp, DestTy: DstType);
3596 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(Ty: DstType));
3597 }
3598 }
3599
3600 // If this is checking if all elements of an extended vector are clear or not,
3601 // compare in a narrow type to eliminate the extend:
3602 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3603 Value *X;
3604 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3605 match(V: BCSrcOp, P: m_ZExtOrSExt(Op: m_Value(V&: X)))) {
3606 if (auto *VecTy = dyn_cast<FixedVectorType>(Val: X->getType())) {
3607 Type *NewType = Builder.getIntNTy(N: VecTy->getPrimitiveSizeInBits());
3608 Value *NewCast = Builder.CreateBitCast(V: X, DestTy: NewType);
3609 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(Ty: NewType));
3610 }
3611 }
3612
3613 // Folding: icmp <pred> iN X, C
3614 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3615 // and C is a splat of a K-bit pattern
3616 // and SC is a constant vector = <C', C', C', ..., C'>
3617 // Into:
3618 // %E = extractelement <M x iK> %vec, i32 C'
3619 // icmp <pred> iK %E, trunc(C)
3620 Value *Vec;
3621 ArrayRef<int> Mask;
3622 if (match(V: BCSrcOp, P: m_Shuffle(v1: m_Value(V&: Vec), v2: m_Undef(), mask: m_Mask(Mask)))) {
3623 // Check whether every element of Mask is the same constant
3624 if (all_equal(Range&: Mask)) {
3625 auto *VecTy = cast<VectorType>(Val: SrcType);
3626 auto *EltTy = cast<IntegerType>(Val: VecTy->getElementType());
3627 if (C->isSplat(SplatSizeInBits: EltTy->getBitWidth())) {
3628 // Fold the icmp based on the value of C
3629 // If C is M copies of an iK sized bit pattern,
3630 // then:
3631 // => %E = extractelement <N x iK> %vec, i64 Elem
3632 // icmp <pred> iK %SplatVal, <pattern>
3633 Value *Extract = Builder.CreateExtractElement(Vec, Idx: Mask[0]);
3634 Value *NewC = ConstantInt::get(Ty: EltTy, V: C->trunc(width: EltTy->getBitWidth()));
3635 return new ICmpInst(Pred, Extract, NewC);
3636 }
3637 }
3638 }
3639 return nullptr;
3640}
3641
3642/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3643/// where X is some kind of instruction.
3644Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
3645 const APInt *C;
3646
3647 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
3648 if (auto *BO = dyn_cast<BinaryOperator>(Val: Cmp.getOperand(i_nocapture: 0)))
3649 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, C: *C))
3650 return I;
3651
3652 if (auto *SI = dyn_cast<SelectInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3653 // For now, we only support constant integers while folding the
3654 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3655 // similar to the cases handled by binary ops above.
3656 if (auto *ConstRHS = dyn_cast<ConstantInt>(Val: Cmp.getOperand(i_nocapture: 1)))
3657 if (Instruction *I = foldICmpSelectConstant(Cmp, Select: SI, C: ConstRHS))
3658 return I;
3659
3660 if (auto *TI = dyn_cast<TruncInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3661 if (Instruction *I = foldICmpTruncConstant(Cmp, Trunc: TI, C: *C))
3662 return I;
3663
3664 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0)))
3665 if (Instruction *I = foldICmpIntrinsicWithConstant(ICI&: Cmp, II, C: *C))
3666 return I;
3667
3668 {
3669 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3670 // fcmp olt/oge (fabs X), 2^ExpVal
3671 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3672 Value *X;
3673 if (match(V: Cmp.getOperand(i_nocapture: 0),
3674 P: m_OneUse(SubPattern: m_ExtractValue<1>(
3675 V: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::frexp>(Ops: m_Value(V&: X))))))) {
3676 ICmpInst::Predicate Pred = Cmp.getPredicate();
3677 APInt Exp;
3678 FCmpInst::Predicate NewPred;
3679 bool ValidPred = true;
3680
3681 switch (Pred) {
3682 case ICmpInst::ICMP_SLT:
3683 NewPred = FCmpInst::FCMP_OLT;
3684 Exp = *C - 1;
3685 break;
3686 case ICmpInst::ICMP_SGT:
3687 NewPred = FCmpInst::FCMP_OGE;
3688 Exp = *C;
3689 break;
3690 default:
3691 ValidPred = false;
3692 break;
3693 }
3694
3695 if (ValidPred) {
3696 const fltSemantics &Sem =
3697 X->getType()->getScalarType()->getFltSemantics();
3698 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3699
3700 if (!Exp.isNegative() && Exp.sle(RHS: MaxExp + 1) &&
3701 isKnownNeverInfOrNaN(V: X, SQ: SQ.getWithInstruction(I: &Cmp))) {
3702 int ExpVal = static_cast<int>(Exp.getSExtValue());
3703 APFloat CmpConst = scalbn(X: APFloat::getOne(Sem), Exp: ExpVal,
3704 RM: APFloat::rmNearestTiesToEven);
3705 Value *Fabs = Builder.CreateFAbs(V: X);
3706 return new FCmpInst(NewPred, Fabs,
3707 ConstantFP::get(Ty: X->getType(), V: CmpConst));
3708 }
3709 }
3710 }
3711 }
3712
3713 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3714 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3715 // TODO: This checks one-use, but that is not strictly necessary.
3716 Value *Cmp0 = Cmp.getOperand(i_nocapture: 0);
3717 Value *X, *Y;
3718 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3719 (match(V: Cmp0,
3720 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::ssub_with_overflow>(
3721 Ops: m_Value(V&: X), Ops: m_Value(V&: Y)))) ||
3722 match(V: Cmp0,
3723 P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
3724 Ops: m_Value(V&: X), Ops: m_Value(V&: Y))))))
3725 return new ICmpInst(Cmp.getPredicate(), X, Y);
3726 }
3727
3728 if (match(V: Cmp.getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: C)))
3729 return foldICmpInstWithConstantAllowPoison(Cmp, C: *C);
3730
3731 return nullptr;
3732}
3733
3734/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3735/// icmp eq/ne BO, C.
3736Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
3737 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3738 // TODO: Some of these folds could work with arbitrary constants, but this
3739 // function is limited to scalar and vector splat constants.
3740 if (!Cmp.isEquality())
3741 return nullptr;
3742
3743 ICmpInst::Predicate Pred = Cmp.getPredicate();
3744 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3745 Constant *RHS = cast<Constant>(Val: Cmp.getOperand(i_nocapture: 1));
3746 Value *BOp0 = BO->getOperand(i_nocapture: 0), *BOp1 = BO->getOperand(i_nocapture: 1);
3747
3748 switch (BO->getOpcode()) {
3749 case Instruction::SRem:
3750 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3751 if (C.isZero() && BO->hasOneUse()) {
3752 const APInt *BOC;
3753 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BOC->sgt(RHS: 1) && BOC->isPowerOf2()) {
3754 Value *NewRem = Builder.CreateURem(LHS: BOp0, RHS: BOp1, Name: BO->getName());
3755 return new ICmpInst(Pred, NewRem,
3756 Constant::getNullValue(Ty: BO->getType()));
3757 }
3758 }
3759 break;
3760 case Instruction::Add: {
3761 // (A + C2) == C --> A == (C - C2)
3762 // (A + C2) != C --> A != (C - C2)
3763 // TODO: Remove the one-use limitation? See discussion in D58633.
3764 if (Constant *C2 = dyn_cast<Constant>(Val: BOp1)) {
3765 if (BO->hasOneUse())
3766 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(C1: RHS, C2));
3767 } else if (C.isZero()) {
3768 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3769 // efficiently invertible, or if the add has just this one use.
3770 if (Value *NegVal = dyn_castNegVal(V: BOp1))
3771 return new ICmpInst(Pred, BOp0, NegVal);
3772 if (Value *NegVal = dyn_castNegVal(V: BOp0))
3773 return new ICmpInst(Pred, NegVal, BOp1);
3774 if (BO->hasOneUse()) {
3775 // (add nuw A, B) != 0 -> (or A, B) != 0
3776 if (match(V: BO, P: m_NUWAdd(L: m_Value(), R: m_Value()))) {
3777 Value *Or = Builder.CreateOr(LHS: BOp0, RHS: BOp1);
3778 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty: BO->getType()));
3779 }
3780 Value *Neg = Builder.CreateNeg(V: BOp1);
3781 Neg->takeName(V: BO);
3782 return new ICmpInst(Pred, BOp0, Neg);
3783 }
3784 }
3785 break;
3786 }
3787 case Instruction::Xor:
3788 if (Constant *BOC = dyn_cast<Constant>(Val: BOp1)) {
3789 // For the xor case, we can xor two constants together, eliminating
3790 // the explicit xor.
3791 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(C1: RHS, C2: BOC));
3792 } else if (C.isZero()) {
3793 // Replace ((xor A, B) != 0) with (A != B)
3794 return new ICmpInst(Pred, BOp0, BOp1);
3795 }
3796 break;
3797 case Instruction::Or: {
3798 const APInt *BOC;
3799 if (match(V: BOp1, P: m_APInt(Res&: BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3800 // Comparing if all bits outside of a constant mask are set?
3801 // Replace (X | C) == -1 with (X & ~C) == ~C.
3802 // This removes the -1 constant.
3803 Constant *NotBOC = ConstantExpr::getNot(C: cast<Constant>(Val: BOp1));
3804 Value *And = Builder.CreateAnd(LHS: BOp0, RHS: NotBOC);
3805 return new ICmpInst(Pred, And, NotBOC);
3806 }
3807 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3808 // -> (and cond, (icmp eq Other, 0))
3809 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3810 // -> (or cond, (icmp ne Other, 0))
3811 Value *Cond, *TV, *FV, *Other, *Sel;
3812 if (C.isZero() &&
3813 match(V: BO,
3814 P: m_OneUse(SubPattern: m_c_Or(L: m_CombineAnd(Ps: m_Value(V&: Sel),
3815 Ps: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TV),
3816 R: m_Value(V&: FV))),
3817 R: m_Value(V&: Other)))) &&
3818 Cond->getType() == Cmp.getType()) {
3819 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
3820 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3821 if (Pred == ICmpInst::ICMP_EQ
3822 ? (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q))
3823 : (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))) {
3824 Value *Cmp = Builder.CreateICmp(
3825 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3826 return BinaryOperator::Create(
3827 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3828 S2: Cond);
3829 }
3830 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3831 // case we need to invert the select condition so we need to be careful to
3832 // avoid creating extra instructions.
3833 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3834 // -> (or (not cond), (icmp ne Other, 0))
3835 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3836 // -> (and (not cond), (icmp eq Other, 0))
3837 //
3838 // Only do this if the inner select has one use, in which case we are
3839 // replacing `select` with `(not cond)`. Otherwise, we will create more
3840 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3841 // cond was freely invertable, the select arms would have been inverted.
3842 if (Sel->hasOneUse() &&
3843 (Pred == ICmpInst::ICMP_EQ
3844 ? (match(V: FV, P: m_Zero()) && isKnownNonZero(V: TV, Q))
3845 : (match(V: TV, P: m_Zero()) && isKnownNonZero(V: FV, Q)))) {
3846 Value *NotCond = Builder.CreateNot(V: Cond);
3847 Value *Cmp = Builder.CreateICmp(
3848 P: Pred, LHS: Other, RHS: Constant::getNullValue(Ty: Other->getType()));
3849 return BinaryOperator::Create(
3850 Op: Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, S1: Cmp,
3851 S2: NotCond);
3852 }
3853 }
3854 break;
3855 }
3856 case Instruction::UDiv:
3857 case Instruction::SDiv:
3858 if (BO->isExact()) {
3859 // div exact X, Y eq/ne 0 -> X eq/ne 0
3860 // div exact X, Y eq/ne 1 -> X eq/ne Y
3861 // div exact X, Y eq/ne C ->
3862 // if Y * C never-overflow && OneUse:
3863 // -> Y * C eq/ne X
3864 if (C.isZero())
3865 return new ICmpInst(Pred, BOp0, Constant::getNullValue(Ty: BO->getType()));
3866 else if (C.isOne())
3867 return new ICmpInst(Pred, BOp0, BOp1);
3868 else if (BO->hasOneUse()) {
3869 OverflowResult OR = computeOverflow(
3870 BinaryOp: Instruction::Mul, IsSigned: BO->getOpcode() == Instruction::SDiv, LHS: BOp1,
3871 RHS: Cmp.getOperand(i_nocapture: 1), CxtI: BO);
3872 if (OR == OverflowResult::NeverOverflows) {
3873 Value *YC =
3874 Builder.CreateMul(LHS: BOp1, RHS: ConstantInt::get(Ty: BO->getType(), V: C));
3875 return new ICmpInst(Pred, YC, BOp0);
3876 }
3877 }
3878 }
3879 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3880 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3881 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3882 return new ICmpInst(NewPred, BOp1, BOp0);
3883 }
3884 break;
3885 default:
3886 break;
3887 }
3888 return nullptr;
3889}
3890
3891static Instruction *foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs,
3892 const APInt &CRhs,
3893 InstCombiner::BuilderTy &Builder,
3894 const SimplifyQuery &Q) {
3895 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3896 "Non-ctpop intrin in ctpop fold");
3897 if (!CtpopLhs->hasOneUse())
3898 return nullptr;
3899
3900 // Power of 2 test:
3901 // isPow2OrZero : ctpop(X) u< 2
3902 // isPow2 : ctpop(X) == 1
3903 // NotPow2OrZero: ctpop(X) u> 1
3904 // NotPow2 : ctpop(X) != 1
3905 // If we know any bit of X can be folded to:
3906 // IsPow2 : X & (~Bit) == 0
3907 // NotPow2 : X & (~Bit) != 0
3908 const ICmpInst::Predicate Pred = I.getPredicate();
3909 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3910 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3911 Value *Op = CtpopLhs->getArgOperand(i: 0);
3912 KnownBits OpKnown = computeKnownBits(V: Op, DL: Q.DL, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT);
3913 // No need to check for count > 1, that should be already constant folded.
3914 if (OpKnown.countMinPopulation() == 1) {
3915 Value *And = Builder.CreateAnd(
3916 LHS: Op, RHS: Constant::getIntegerValue(Ty: Op->getType(), V: ~(OpKnown.One)));
3917 return new ICmpInst(
3918 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3919 ? ICmpInst::ICMP_EQ
3920 : ICmpInst::ICMP_NE,
3921 And, Constant::getNullValue(Ty: Op->getType()));
3922 }
3923 }
3924
3925 return nullptr;
3926}
3927
3928/// Fold an equality icmp with LLVM intrinsic and constant operand.
3929Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
3930 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3931 Type *Ty = II->getType();
3932 unsigned BitWidth = C.getBitWidth();
3933 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3934
3935 switch (II->getIntrinsicID()) {
3936 case Intrinsic::abs:
3937 // abs(A) == 0 -> A == 0
3938 // abs(A) == INT_MIN -> A == INT_MIN
3939 if (C.isZero() || C.isMinSignedValue())
3940 return new ICmpInst(Pred, II->getArgOperand(i: 0), ConstantInt::get(Ty, V: C));
3941 break;
3942
3943 case Intrinsic::bswap:
3944 // bswap(A) == C -> A == bswap(C)
3945 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3946 ConstantInt::get(Ty, V: C.byteSwap()));
3947
3948 case Intrinsic::bitreverse:
3949 // bitreverse(A) == C -> A == bitreverse(C)
3950 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3951 ConstantInt::get(Ty, V: C.reverseBits()));
3952
3953 case Intrinsic::ctlz:
3954 case Intrinsic::cttz: {
3955 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3956 if (C == BitWidth)
3957 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3958 ConstantInt::getNullValue(Ty));
3959
3960 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3961 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3962 // Limit to one use to ensure we don't increase instruction count.
3963 unsigned Num = C.getLimitedValue(Limit: BitWidth);
3964 if (Num != BitWidth && II->hasOneUse()) {
3965 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3966 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: Num + 1)
3967 : APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: Num + 1);
3968 APInt Mask2 = IsTrailing
3969 ? APInt::getOneBitSet(numBits: BitWidth, BitNo: Num)
3970 : APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
3971 return new ICmpInst(Pred, Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask1),
3972 ConstantInt::get(Ty, V: Mask2));
3973 }
3974 break;
3975 }
3976
3977 case Intrinsic::ctpop: {
3978 // popcount(A) == 0 -> A == 0 and likewise for !=
3979 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3980 bool IsZero = C.isZero();
3981 if (IsZero || C == BitWidth)
3982 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3983 IsZero ? Constant::getNullValue(Ty)
3984 : Constant::getAllOnesValue(Ty));
3985
3986 break;
3987 }
3988
3989 case Intrinsic::fshl:
3990 case Intrinsic::fshr:
3991 if (II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
3992 const APInt *RotAmtC;
3993 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3994 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3995 if (match(V: II->getArgOperand(i: 2), P: m_APInt(Res&: RotAmtC)))
3996 return new ICmpInst(Pred, II->getArgOperand(i: 0),
3997 II->getIntrinsicID() == Intrinsic::fshl
3998 ? ConstantInt::get(Ty, V: C.rotr(rotateAmt: *RotAmtC))
3999 : ConstantInt::get(Ty, V: C.rotl(rotateAmt: *RotAmtC)));
4000 }
4001 break;
4002
4003 case Intrinsic::umax:
4004 case Intrinsic::uadd_sat: {
4005 // uadd.sat(a, b) == 0 -> (a | b) == 0
4006 // umax(a, b) == 0 -> (a | b) == 0
4007 if (C.isZero() && II->hasOneUse()) {
4008 Value *Or = Builder.CreateOr(LHS: II->getArgOperand(i: 0), RHS: II->getArgOperand(i: 1));
4009 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4010 }
4011 break;
4012 }
4013
4014 case Intrinsic::ssub_sat:
4015 // ssub.sat(a, b) == 0 -> a == b
4016 //
4017 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4018 // (because 1 saturates to 0). Just skip the optimization for i1.
4019 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4020 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4021 break;
4022 case Intrinsic::usub_sat: {
4023 // usub.sat(a, b) == 0 -> a <= b
4024 if (C.isZero()) {
4025 ICmpInst::Predicate NewPred =
4026 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
4027 return new ICmpInst(NewPred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4028 }
4029 break;
4030 }
4031 default:
4032 break;
4033 }
4034
4035 return nullptr;
4036}
4037
4038/// Fold an icmp with LLVM intrinsics
4039static Instruction *
4040foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp,
4041 InstCombiner::BuilderTy &Builder) {
4042 assert(Cmp.isEquality());
4043
4044 ICmpInst::Predicate Pred = Cmp.getPredicate();
4045 Value *Op0 = Cmp.getOperand(i_nocapture: 0);
4046 Value *Op1 = Cmp.getOperand(i_nocapture: 1);
4047 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Val: Op0);
4048 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Val: Op1);
4049 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4050 return nullptr;
4051
4052 switch (IIOp0->getIntrinsicID()) {
4053 case Intrinsic::bswap:
4054 case Intrinsic::bitreverse:
4055 // If both operands are byte-swapped or bit-reversed, just compare the
4056 // original values.
4057 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
4058 case Intrinsic::fshl:
4059 case Intrinsic::fshr: {
4060 // If both operands are rotated by same amount, just compare the
4061 // original values.
4062 if (IIOp0->getOperand(i_nocapture: 0) != IIOp0->getOperand(i_nocapture: 1))
4063 break;
4064 if (IIOp1->getOperand(i_nocapture: 0) != IIOp1->getOperand(i_nocapture: 1))
4065 break;
4066 if (IIOp0->getOperand(i_nocapture: 2) == IIOp1->getOperand(i_nocapture: 2))
4067 return new ICmpInst(Pred, IIOp0->getOperand(i_nocapture: 0), IIOp1->getOperand(i_nocapture: 0));
4068
4069 // rotate(X, AmtX) == rotate(Y, AmtY)
4070 // -> rotate(X, AmtX - AmtY) == Y
4071 // Do this if either both rotates have one use or if only one has one use
4072 // and AmtX/AmtY are constants.
4073 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4074 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4075 if (OneUses == 2 ||
4076 (OneUses == 1 && match(V: IIOp0->getOperand(i_nocapture: 2), P: m_ImmConstant()) &&
4077 match(V: IIOp1->getOperand(i_nocapture: 2), P: m_ImmConstant()))) {
4078
4079 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4080 // of two.
4081 if (isPowerOf2_32(Value: BW)) {
4082 Value *SubAmt =
4083 Builder.CreateSub(LHS: IIOp0->getOperand(i_nocapture: 2), RHS: IIOp1->getOperand(i_nocapture: 2));
4084 Value *CombinedRotate = Builder.CreateIntrinsic(
4085 RetTy: Op0->getType(), ID: IIOp0->getIntrinsicID(),
4086 Args: {IIOp0->getOperand(i_nocapture: 0), IIOp0->getOperand(i_nocapture: 0), SubAmt});
4087 return new ICmpInst(Pred, IIOp1->getOperand(i_nocapture: 0), CombinedRotate);
4088 }
4089 }
4090 } break;
4091 default:
4092 break;
4093 }
4094
4095 return nullptr;
4096}
4097
4098/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4099/// where X is some kind of instruction and C is AllowPoison.
4100/// TODO: Move more folds which allow poison to this function.
4101Instruction *
4102InstCombinerImpl::foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp,
4103 const APInt &C) {
4104 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4105 if (auto *II = dyn_cast<IntrinsicInst>(Val: Cmp.getOperand(i_nocapture: 0))) {
4106 switch (II->getIntrinsicID()) {
4107 default:
4108 break;
4109 case Intrinsic::fshl:
4110 case Intrinsic::fshr:
4111 if (Cmp.isEquality() && II->getArgOperand(i: 0) == II->getArgOperand(i: 1)) {
4112 // (rot X, ?) == 0/-1 --> X == 0/-1
4113 if (C.isZero() || C.isAllOnes())
4114 return new ICmpInst(Pred, II->getArgOperand(i: 0), Cmp.getOperand(i_nocapture: 1));
4115 }
4116 break;
4117 }
4118 }
4119
4120 return nullptr;
4121}
4122
4123/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4124Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
4125 BinaryOperator *BO,
4126 const APInt &C) {
4127 switch (BO->getOpcode()) {
4128 case Instruction::Xor:
4129 if (Instruction *I = foldICmpXorConstant(Cmp, Xor: BO, C))
4130 return I;
4131 break;
4132 case Instruction::And:
4133 if (Instruction *I = foldICmpAndConstant(Cmp, And: BO, C))
4134 return I;
4135 break;
4136 case Instruction::Or:
4137 if (Instruction *I = foldICmpOrConstant(Cmp, Or: BO, C))
4138 return I;
4139 break;
4140 case Instruction::Mul:
4141 if (Instruction *I = foldICmpMulConstant(Cmp, Mul: BO, C))
4142 return I;
4143 break;
4144 case Instruction::Shl:
4145 if (Instruction *I = foldICmpShlConstant(Cmp, Shl: BO, C))
4146 return I;
4147 break;
4148 case Instruction::LShr:
4149 case Instruction::AShr:
4150 if (Instruction *I = foldICmpShrConstant(Cmp, Shr: BO, C))
4151 return I;
4152 break;
4153 case Instruction::SRem:
4154 if (Instruction *I = foldICmpSRemConstant(Cmp, SRem: BO, C))
4155 return I;
4156 break;
4157 case Instruction::UDiv:
4158 if (Instruction *I = foldICmpUDivConstant(Cmp, UDiv: BO, C))
4159 return I;
4160 [[fallthrough]];
4161 case Instruction::SDiv:
4162 if (Instruction *I = foldICmpDivConstant(Cmp, Div: BO, C))
4163 return I;
4164 break;
4165 case Instruction::Sub:
4166 if (Instruction *I = foldICmpSubConstant(Cmp, Sub: BO, C))
4167 return I;
4168 break;
4169 case Instruction::Add:
4170 if (Instruction *I = foldICmpAddConstant(Cmp, Add: BO, C))
4171 return I;
4172 break;
4173 default:
4174 break;
4175 }
4176
4177 // TODO: These folds could be refactored to be part of the above calls.
4178 if (Instruction *I = foldICmpBinOpEqualityWithConstant(Cmp, BO, C))
4179 return I;
4180
4181 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4182 // : C4), C5` pattern, by computing a truth table of the four constant
4183 // variants.
4184 return foldICmpBinOpWithConstantViaTruthTable(Cmp, BO, C);
4185}
4186
4187static Instruction *
4188foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II,
4189 const APInt &C,
4190 InstCombiner::BuilderTy &Builder) {
4191 // This transform may end up producing more than one instruction for the
4192 // intrinsic, so limit it to one user of the intrinsic.
4193 if (!II->hasOneUse())
4194 return nullptr;
4195
4196 // Let Y = [add/sub]_sat(X, C) pred C2
4197 // SatVal = The saturating value for the operation
4198 // WillWrap = Whether or not the operation will underflow / overflow
4199 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4200 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4201 //
4202 // When (SatVal pred C2) is true, then
4203 // Y = WillWrap ? true : ((X binop C) pred C2)
4204 // => Y = WillWrap || ((X binop C) pred C2)
4205 // else
4206 // Y = WillWrap ? false : ((X binop C) pred C2)
4207 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4208 // => Y = !WillWrap && ((X binop C) pred C2)
4209 Value *Op0 = II->getOperand(i_nocapture: 0);
4210 Value *Op1 = II->getOperand(i_nocapture: 1);
4211
4212 const APInt *COp1;
4213 // This transform only works when the intrinsic has an integral constant or
4214 // splat vector as the second operand.
4215 if (!match(V: Op1, P: m_APInt(Res&: COp1)))
4216 return nullptr;
4217
4218 APInt SatVal;
4219 switch (II->getIntrinsicID()) {
4220 default:
4221 llvm_unreachable(
4222 "This function only works with usub_sat and uadd_sat for now!");
4223 case Intrinsic::uadd_sat:
4224 SatVal = APInt::getAllOnes(numBits: C.getBitWidth());
4225 break;
4226 case Intrinsic::usub_sat:
4227 SatVal = APInt::getZero(numBits: C.getBitWidth());
4228 break;
4229 }
4230
4231 // Check (SatVal pred C2)
4232 bool SatValCheck = ICmpInst::compare(LHS: SatVal, RHS: C, Pred);
4233
4234 // !WillWrap.
4235 ConstantRange C1 = ConstantRange::makeExactNoWrapRegion(
4236 BinOp: II->getBinaryOp(), Other: *COp1, NoWrapKind: II->getNoWrapKind());
4237
4238 // WillWrap.
4239 if (SatValCheck)
4240 C1 = C1.inverse();
4241
4242 ConstantRange C2 = ConstantRange::makeExactICmpRegion(Pred, Other: C);
4243 if (II->getBinaryOp() == Instruction::Add)
4244 C2 = C2.sub(Other: *COp1);
4245 else
4246 C2 = C2.add(Other: *COp1);
4247
4248 Instruction::BinaryOps CombiningOp =
4249 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4250
4251 std::optional<ConstantRange> Combination;
4252 if (CombiningOp == Instruction::BinaryOps::Or)
4253 Combination = C1.exactUnionWith(CR: C2);
4254 else /* CombiningOp == Instruction::BinaryOps::And */
4255 Combination = C1.exactIntersectWith(CR: C2);
4256
4257 if (!Combination)
4258 return nullptr;
4259
4260 CmpInst::Predicate EquivPred;
4261 APInt EquivInt;
4262 APInt EquivOffset;
4263
4264 Combination->getEquivalentICmp(Pred&: EquivPred, RHS&: EquivInt, Offset&: EquivOffset);
4265
4266 return new ICmpInst(
4267 EquivPred,
4268 Builder.CreateAdd(LHS: Op0, RHS: ConstantInt::get(Ty: Op1->getType(), V: EquivOffset)),
4269 ConstantInt::get(Ty: Op1->getType(), V: EquivInt));
4270}
4271
4272static Instruction *
4273foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I,
4274 const APInt &C,
4275 InstCombiner::BuilderTy &Builder) {
4276 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4277 switch (Pred) {
4278 case ICmpInst::ICMP_EQ:
4279 case ICmpInst::ICMP_NE:
4280 if (C.isZero())
4281 NewPredicate = Pred;
4282 else if (C.isOne())
4283 NewPredicate =
4284 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
4285 else if (C.isAllOnes())
4286 NewPredicate =
4287 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
4288 break;
4289
4290 case ICmpInst::ICMP_SGT:
4291 if (C.isAllOnes())
4292 NewPredicate = ICmpInst::ICMP_UGE;
4293 else if (C.isZero())
4294 NewPredicate = ICmpInst::ICMP_UGT;
4295 break;
4296
4297 case ICmpInst::ICMP_SLT:
4298 if (C.isZero())
4299 NewPredicate = ICmpInst::ICMP_ULT;
4300 else if (C.isOne())
4301 NewPredicate = ICmpInst::ICMP_ULE;
4302 break;
4303
4304 case ICmpInst::ICMP_ULT:
4305 if (C.ugt(RHS: 1))
4306 NewPredicate = ICmpInst::ICMP_UGE;
4307 break;
4308
4309 case ICmpInst::ICMP_UGT:
4310 if (!C.isZero() && !C.isAllOnes())
4311 NewPredicate = ICmpInst::ICMP_ULT;
4312 break;
4313
4314 default:
4315 break;
4316 }
4317
4318 if (!NewPredicate)
4319 return nullptr;
4320
4321 if (I->getIntrinsicID() == Intrinsic::scmp)
4322 NewPredicate = ICmpInst::getSignedPredicate(Pred: *NewPredicate);
4323 Value *LHS = I->getOperand(i_nocapture: 0);
4324 Value *RHS = I->getOperand(i_nocapture: 1);
4325 return new ICmpInst(*NewPredicate, LHS, RHS);
4326}
4327
4328/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4329Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
4330 IntrinsicInst *II,
4331 const APInt &C) {
4332 ICmpInst::Predicate Pred = Cmp.getPredicate();
4333
4334 // Handle folds that apply for any kind of icmp.
4335 switch (II->getIntrinsicID()) {
4336 default:
4337 break;
4338 case Intrinsic::uadd_sat:
4339 case Intrinsic::usub_sat:
4340 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4341 Pred, II: cast<SaturatingInst>(Val: II), C, Builder))
4342 return Folded;
4343 break;
4344 case Intrinsic::ctpop: {
4345 const SimplifyQuery Q = SQ.getWithInstruction(I: &Cmp);
4346 if (Instruction *R = foldCtpopPow2Test(I&: Cmp, CtpopLhs: II, CRhs: C, Builder, Q))
4347 return R;
4348 } break;
4349 case Intrinsic::scmp:
4350 case Intrinsic::ucmp:
4351 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, I: II, C, Builder))
4352 return Folded;
4353 break;
4354 }
4355
4356 if (Cmp.isEquality())
4357 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4358
4359 Type *Ty = II->getType();
4360 unsigned BitWidth = C.getBitWidth();
4361 switch (II->getIntrinsicID()) {
4362 case Intrinsic::ctpop: {
4363 // (ctpop X > BitWidth - 1) --> X == -1
4364 Value *X = II->getArgOperand(i: 0);
4365 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4366 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ, S1: X,
4367 S2: ConstantInt::getAllOnesValue(Ty));
4368 // (ctpop X < BitWidth) --> X != -1
4369 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4370 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE, S1: X,
4371 S2: ConstantInt::getAllOnesValue(Ty));
4372 break;
4373 }
4374 case Intrinsic::ctlz: {
4375 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4376 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4377 unsigned Num = C.getLimitedValue();
4378 APInt Limit = APInt::getOneBitSet(numBits: BitWidth, BitNo: BitWidth - Num - 1);
4379 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_ULT,
4380 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4381 }
4382
4383 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4384 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4385 unsigned Num = C.getLimitedValue();
4386 APInt Limit = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: BitWidth - Num);
4387 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_UGT,
4388 S1: II->getArgOperand(i: 0), S2: ConstantInt::get(Ty, V: Limit));
4389 }
4390 break;
4391 }
4392 case Intrinsic::cttz: {
4393 // Limit to one use to ensure we don't increase instruction count.
4394 if (!II->hasOneUse())
4395 return nullptr;
4396
4397 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4398 if (Pred == ICmpInst::ICMP_UGT && C.ult(RHS: BitWidth)) {
4399 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue() + 1);
4400 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_EQ,
4401 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4402 S2: ConstantInt::getNullValue(Ty));
4403 }
4404
4405 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4406 if (Pred == ICmpInst::ICMP_ULT && C.uge(RHS: 1) && C.ule(RHS: BitWidth)) {
4407 APInt Mask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: C.getLimitedValue());
4408 return CmpInst::Create(Op: Instruction::ICmp, Pred: ICmpInst::ICMP_NE,
4409 S1: Builder.CreateAnd(LHS: II->getArgOperand(i: 0), RHS: Mask),
4410 S2: ConstantInt::getNullValue(Ty));
4411 }
4412 break;
4413 }
4414 case Intrinsic::ssub_sat:
4415 // ssub.sat(a, b) spred 0 -> a spred b
4416 //
4417 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4418 // (because 1 saturates to 0). Just skip the optimization for i1.
4419 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4420 if (C.isZero())
4421 return new ICmpInst(Pred, II->getArgOperand(i: 0), II->getArgOperand(i: 1));
4422 // X s<= 0 is cannonicalized to X s< 1
4423 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4424 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(i: 0),
4425 II->getArgOperand(i: 1));
4426 // X s>= 0 is cannonicalized to X s> -1
4427 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4428 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(i: 0),
4429 II->getArgOperand(i: 1));
4430 }
4431 break;
4432 case Intrinsic::abs: {
4433 if (!II->hasOneUse())
4434 return nullptr;
4435
4436 Value *X = II->getArgOperand(i: 0);
4437
4438 // If C >= 0:
4439 // abs(X) u> C --> X + C u> 2 * C
4440 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4441 return new ICmpInst(ICmpInst::ICMP_UGT,
4442 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C)),
4443 ConstantInt::get(Ty, V: 2 * C));
4444 }
4445
4446 // If C >= 1:
4447 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4448 if (Pred == CmpInst::ICMP_ULT && C.sge(RHS: 1))
4449 return new ICmpInst(ICmpInst::ICMP_ULE,
4450 Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: C - 1)),
4451 ConstantInt::get(Ty, V: 2 * (C - 1)));
4452
4453 break;
4454 }
4455 default:
4456 break;
4457 }
4458
4459 return nullptr;
4460}
4461
4462/// Handle icmp with constant (but not simple integer constant) RHS.
4463Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
4464 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
4465 Constant *RHSC = dyn_cast<Constant>(Val: Op1);
4466 Instruction *LHSI = dyn_cast<Instruction>(Val: Op0);
4467 if (!RHSC || !LHSI)
4468 return nullptr;
4469
4470 switch (LHSI->getOpcode()) {
4471 case Instruction::IntToPtr:
4472 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4473 if (isa<ConstantPointerNull>(Val: RHSC)) {
4474 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4475 if (IntPtrTy == LHSI->getOperand(i: 0)->getType()) {
4476 APInt NullPtrValue =
4477 DL.getNullPtrValue(AS: RHSC->getType()->getPointerAddressSpace());
4478 return new ICmpInst(I.getPredicate(), LHSI->getOperand(i: 0),
4479 Constant::getIntegerValue(Ty: IntPtrTy, V: NullPtrValue));
4480 }
4481 }
4482 break;
4483
4484 case Instruction::Load:
4485 // Try to optimize things like "A[i] > 4" to index computations.
4486 if (GetElementPtrInst *GEP =
4487 dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
4488 if (Instruction *Res =
4489 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
4490 return Res;
4491 break;
4492 }
4493
4494 return nullptr;
4495}
4496
4497Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
4498 Value *RHS, const ICmpInst &I) {
4499 // Try to fold the comparison into the select arms, which will cause the
4500 // select to be converted into a logical and/or.
4501 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4502 if (Value *Res = simplifyICmpInst(Pred, LHS: Op, RHS, Q: SQ))
4503 return Res;
4504 if (std::optional<bool> Impl = isImpliedCondition(
4505 LHS: SI->getCondition(), RHSPred: Pred, RHSOp0: Op, RHSOp1: RHS, DL, LHSIsTrue: SelectCondIsTrue))
4506 return ConstantInt::get(Ty: I.getType(), V: *Impl);
4507 return nullptr;
4508 };
4509
4510 ConstantInt *CI = nullptr;
4511 Value *Op1 = SimplifyOp(SI->getOperand(i_nocapture: 1), true);
4512 if (Op1)
4513 CI = dyn_cast<ConstantInt>(Val: Op1);
4514
4515 Value *Op2 = SimplifyOp(SI->getOperand(i_nocapture: 2), false);
4516 if (Op2)
4517 CI = dyn_cast<ConstantInt>(Val: Op2);
4518
4519 auto Simplifies = [&](Value *Op, unsigned Idx) {
4520 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4521 const APInt *Dummy;
4522 return Op ||
4523 (isa<CmpIntrinsic>(Val: SI->getOperand(i_nocapture: Idx)) &&
4524 SI->getOperand(i_nocapture: Idx)->hasOneUse() && match(V: RHS, P: m_APInt(Res&: Dummy)));
4525 };
4526
4527 // We only want to perform this transformation if it will not lead to
4528 // additional code. This is true if either both sides of the select
4529 // fold to a constant (in which case the icmp is replaced with a select
4530 // which will usually simplify) or this is the only user of the
4531 // select (in which case we are trading a select+icmp for a simpler
4532 // select+icmp) or all uses of the select can be replaced based on
4533 // dominance information ("Global cases").
4534 bool Transform = false;
4535 if (Op1 && Op2)
4536 Transform = true;
4537 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4538 // Local case
4539 if (SI->hasOneUse())
4540 Transform = true;
4541 // Global cases
4542 else if (CI && !CI->isZero())
4543 // When Op1 is constant try replacing select with second operand.
4544 // Otherwise Op2 is constant and try replacing select with first
4545 // operand.
4546 Transform = replacedSelectWithOperand(SI, Icmp: &I, SIOpd: Op1 ? 2 : 1);
4547 }
4548 if (Transform) {
4549 if (!Op1)
4550 Op1 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 1), RHS, Name: I.getName());
4551 if (!Op2)
4552 Op2 = Builder.CreateICmp(P: Pred, LHS: SI->getOperand(i_nocapture: 2), RHS, Name: I.getName());
4553 return SelectInst::Create(C: SI->getOperand(i_nocapture: 0), S1: Op1, S2: Op2, NameStr: "", InsertBefore: nullptr, MDFrom: SI);
4554 }
4555
4556 return nullptr;
4557}
4558
4559// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4560static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4561 unsigned Depth = 0) {
4562 if (Not ? match(V, P: m_NegatedPower2OrZero()) : match(V, P: m_LowBitMaskOrZero()))
4563 return true;
4564 if (V->getType()->getScalarSizeInBits() == 1)
4565 return true;
4566 if (Depth++ >= MaxAnalysisRecursionDepth)
4567 return false;
4568 Value *X;
4569 const Instruction *I = dyn_cast<Instruction>(Val: V);
4570 if (!I)
4571 return false;
4572 switch (I->getOpcode()) {
4573 case Instruction::ZExt:
4574 // ZExt(Mask) is a Mask.
4575 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4576 case Instruction::SExt:
4577 // SExt(Mask) is a Mask.
4578 // SExt(~Mask) is a ~Mask.
4579 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4580 case Instruction::And:
4581 case Instruction::Or:
4582 // Mask0 | Mask1 is a Mask.
4583 // Mask0 & Mask1 is a Mask.
4584 // ~Mask0 | ~Mask1 is a ~Mask.
4585 // ~Mask0 & ~Mask1 is a ~Mask.
4586 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4587 isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4588 case Instruction::Xor:
4589 if (match(V, P: m_Not(V: m_Value(V&: X))))
4590 return isMaskOrZero(V: X, Not: !Not, Q, Depth);
4591
4592 // (X ^ -X) is a ~Mask
4593 if (Not)
4594 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Neg(V: m_Deferred(V: X))));
4595 // (X ^ (X - 1)) is a Mask
4596 else
4597 return match(V, P: m_c_Xor(L: m_Value(V&: X), R: m_Add(L: m_Deferred(V: X), R: m_AllOnes())));
4598 case Instruction::Select:
4599 // c ? Mask0 : Mask1 is a Mask.
4600 return isMaskOrZero(V: I->getOperand(i: 1), Not, Q, Depth) &&
4601 isMaskOrZero(V: I->getOperand(i: 2), Not, Q, Depth);
4602 case Instruction::Shl:
4603 // (~Mask) << X is a ~Mask.
4604 return Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4605 case Instruction::LShr:
4606 // Mask >> X is a Mask.
4607 return !Not && isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4608 case Instruction::AShr:
4609 // Mask s>> X is a Mask.
4610 // ~Mask s>> X is a ~Mask.
4611 return isMaskOrZero(V: I->getOperand(i: 0), Not, Q, Depth);
4612 case Instruction::Add:
4613 // Pow2 - 1 is a Mask.
4614 if (!Not && match(V: I->getOperand(i: 1), P: m_AllOnes()))
4615 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 0), DL: Q.DL, /*OrZero*/ true,
4616 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4617 break;
4618 case Instruction::Sub:
4619 // -Pow2 is a ~Mask.
4620 if (Not && match(V: I->getOperand(i: 0), P: m_Zero()))
4621 return isKnownToBeAPowerOfTwo(V: I->getOperand(i: 1), DL: Q.DL, /*OrZero*/ true,
4622 AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT, UseInstrInfo: Depth);
4623 break;
4624 case Instruction::Call: {
4625 if (auto *II = dyn_cast<IntrinsicInst>(Val: I)) {
4626 switch (II->getIntrinsicID()) {
4627 // min/max(Mask0, Mask1) is a Mask.
4628 // min/max(~Mask0, ~Mask1) is a ~Mask.
4629 case Intrinsic::umax:
4630 case Intrinsic::smax:
4631 case Intrinsic::umin:
4632 case Intrinsic::smin:
4633 return isMaskOrZero(V: II->getArgOperand(i: 1), Not, Q, Depth) &&
4634 isMaskOrZero(V: II->getArgOperand(i: 0), Not, Q, Depth);
4635
4636 // In the context of masks, bitreverse(Mask) == ~Mask
4637 case Intrinsic::bitreverse:
4638 return isMaskOrZero(V: II->getArgOperand(i: 0), Not: !Not, Q, Depth);
4639 default:
4640 break;
4641 }
4642 }
4643 break;
4644 }
4645 default:
4646 break;
4647 }
4648 return false;
4649}
4650
4651/// Some comparisons can be simplified.
4652/// In this case, we are looking for comparisons that look like
4653/// a check for a lossy truncation.
4654/// Folds:
4655/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4656/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4657/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4658/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4659/// Where Mask is some pattern that produces all-ones in low bits:
4660/// (-1 >> y)
4661/// ((-1 << y) >> y) <- non-canonical, has extra uses
4662/// ~(-1 << y)
4663/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4664/// The Mask can be a constant, too.
4665/// For some predicates, the operands are commutative.
4666/// For others, x can only be on a specific side.
4667static Value *foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0,
4668 Value *Op1, const SimplifyQuery &Q,
4669 InstCombiner &IC) {
4670
4671 ICmpInst::Predicate DstPred;
4672 switch (Pred) {
4673 case ICmpInst::Predicate::ICMP_EQ:
4674 // x & Mask == x
4675 // x & ~Mask == 0
4676 // ~x | Mask == -1
4677 // -> x u<= Mask
4678 // x & ~Mask == ~Mask
4679 // -> ~Mask u<= x
4680 DstPred = ICmpInst::Predicate::ICMP_ULE;
4681 break;
4682 case ICmpInst::Predicate::ICMP_NE:
4683 // x & Mask != x
4684 // x & ~Mask != 0
4685 // ~x | Mask != -1
4686 // -> x u> Mask
4687 // x & ~Mask != ~Mask
4688 // -> ~Mask u> x
4689 DstPred = ICmpInst::Predicate::ICMP_UGT;
4690 break;
4691 case ICmpInst::Predicate::ICMP_ULT:
4692 // x & Mask u< x
4693 // -> x u> Mask
4694 // x & ~Mask u< ~Mask
4695 // -> ~Mask u> x
4696 DstPred = ICmpInst::Predicate::ICMP_UGT;
4697 break;
4698 case ICmpInst::Predicate::ICMP_UGE:
4699 // x & Mask u>= x
4700 // -> x u<= Mask
4701 // x & ~Mask u>= ~Mask
4702 // -> ~Mask u<= x
4703 DstPred = ICmpInst::Predicate::ICMP_ULE;
4704 break;
4705 case ICmpInst::Predicate::ICMP_SLT:
4706 // x & Mask s< x [iff Mask s>= 0]
4707 // -> x s> Mask
4708 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4709 // -> ~Mask s> x
4710 DstPred = ICmpInst::Predicate::ICMP_SGT;
4711 break;
4712 case ICmpInst::Predicate::ICMP_SGE:
4713 // x & Mask s>= x [iff Mask s>= 0]
4714 // -> x s<= Mask
4715 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4716 // -> ~Mask s<= x
4717 DstPred = ICmpInst::Predicate::ICMP_SLE;
4718 break;
4719 default:
4720 // We don't support sgt,sle
4721 // ult/ugt are simplified to true/false respectively.
4722 return nullptr;
4723 }
4724
4725 Value *X, *M;
4726 // Put search code in lambda for early positive returns.
4727 auto IsLowBitMask = [&]() {
4728 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: M)))) {
4729 X = Op1;
4730 // Look for: x & Mask pred x
4731 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4732 return !ICmpInst::isSigned(Pred) ||
4733 (match(V: M, P: m_NonNegative()) || isKnownNonNegative(V: M, SQ: Q));
4734 }
4735
4736 // Look for: x & ~Mask pred ~Mask
4737 if (isMaskOrZero(V: X, /*Not=*/true, Q)) {
4738 return !ICmpInst::isSigned(Pred) || isKnownNonZero(V: X, Q);
4739 }
4740 return false;
4741 }
4742 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_AllOnes()) &&
4743 match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4744
4745 auto Check = [&]() {
4746 // Look for: ~x | Mask == -1
4747 if (isMaskOrZero(V: M, /*Not=*/false, Q)) {
4748 if (Value *NotX =
4749 IC.getFreelyInverted(V: X, WillInvertAllUses: X->hasOneUse(), Builder: &IC.Builder)) {
4750 X = NotX;
4751 return true;
4752 }
4753 }
4754 return false;
4755 };
4756 if (Check())
4757 return true;
4758 std::swap(a&: X, b&: M);
4759 return Check();
4760 }
4761 if (ICmpInst::isEquality(P: Pred) && match(V: Op1, P: m_Zero()) &&
4762 match(V: Op0, P: m_OneUse(SubPattern: m_And(L: m_Value(V&: X), R: m_Value(V&: M))))) {
4763 auto Check = [&]() {
4764 // Look for: x & ~Mask == 0
4765 if (isMaskOrZero(V: M, /*Not=*/true, Q)) {
4766 if (Value *NotM =
4767 IC.getFreelyInverted(V: M, WillInvertAllUses: M->hasOneUse(), Builder: &IC.Builder)) {
4768 M = NotM;
4769 return true;
4770 }
4771 }
4772 return false;
4773 };
4774 if (Check())
4775 return true;
4776 std::swap(a&: X, b&: M);
4777 return Check();
4778 }
4779 return false;
4780 };
4781
4782 if (!IsLowBitMask())
4783 return nullptr;
4784
4785 return IC.Builder.CreateICmp(P: DstPred, LHS: X, RHS: M);
4786}
4787
4788/// Some comparisons can be simplified.
4789/// In this case, we are looking for comparisons that look like
4790/// a check for a lossy signed truncation.
4791/// Folds: (MaskedBits is a constant.)
4792/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4793/// Into:
4794/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4795/// Where KeptBits = bitwidth(%x) - MaskedBits
4796static Value *
4797foldICmpWithTruncSignExtendedVal(ICmpInst &I,
4798 InstCombiner::BuilderTy &Builder) {
4799 CmpPredicate SrcPred;
4800 Value *X;
4801 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4802 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4803 if (!match(V: &I, P: m_c_ICmp(Pred&: SrcPred,
4804 L: m_OneUse(SubPattern: m_AShr(L: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: C0)),
4805 R: m_APInt(Res&: C1))),
4806 R: m_Deferred(V: X))))
4807 return nullptr;
4808
4809 // Potential handling of non-splats: for each element:
4810 // * if both are undef, replace with constant 0.
4811 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4812 // * if both are not undef, and are different, bailout.
4813 // * else, only one is undef, then pick the non-undef one.
4814
4815 // The shift amount must be equal.
4816 if (*C0 != *C1)
4817 return nullptr;
4818 const APInt &MaskedBits = *C0;
4819 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4820
4821 ICmpInst::Predicate DstPred;
4822 switch (SrcPred) {
4823 case ICmpInst::Predicate::ICMP_EQ:
4824 // ((%x << MaskedBits) a>> MaskedBits) == %x
4825 // =>
4826 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4827 DstPred = ICmpInst::Predicate::ICMP_ULT;
4828 break;
4829 case ICmpInst::Predicate::ICMP_NE:
4830 // ((%x << MaskedBits) a>> MaskedBits) != %x
4831 // =>
4832 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4833 DstPred = ICmpInst::Predicate::ICMP_UGE;
4834 break;
4835 // FIXME: are more folds possible?
4836 default:
4837 return nullptr;
4838 }
4839
4840 auto *XType = X->getType();
4841 const unsigned XBitWidth = XType->getScalarSizeInBits();
4842 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4843 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4844
4845 // KeptBits = bitwidth(%x) - MaskedBits
4846 const APInt KeptBits = BitWidth - MaskedBits;
4847 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4848 // ICmpCst = (1 << KeptBits)
4849 const APInt ICmpCst = APInt(XBitWidth, 1).shl(ShiftAmt: KeptBits);
4850 assert(ICmpCst.isPowerOf2());
4851 // AddCst = (1 << (KeptBits-1))
4852 const APInt AddCst = ICmpCst.lshr(shiftAmt: 1);
4853 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4854
4855 // T0 = add %x, AddCst
4856 Value *T0 = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: XType, V: AddCst));
4857 // T1 = T0 DstPred ICmpCst
4858 Value *T1 = Builder.CreateICmp(P: DstPred, LHS: T0, RHS: ConstantInt::get(Ty: XType, V: ICmpCst));
4859
4860 return T1;
4861}
4862
4863// Given pattern:
4864// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4865// we should move shifts to the same hand of 'and', i.e. rewrite as
4866// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4867// We are only interested in opposite logical shifts here.
4868// One of the shifts can be truncated.
4869// If we can, we want to end up creating 'lshr' shift.
4870static Value *
4871foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
4872 InstCombiner::BuilderTy &Builder) {
4873 if (!I.isEquality() || !match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) ||
4874 !I.getOperand(i_nocapture: 0)->hasOneUse())
4875 return nullptr;
4876
4877 auto m_AnyLogicalShift = m_LogicalShift(L: m_Value(), R: m_Value());
4878
4879 // Look for an 'and' of two logical shifts, one of which may be truncated.
4880 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4881 Instruction *XShift, *MaybeTruncation, *YShift;
4882 if (!match(
4883 V: I.getOperand(i_nocapture: 0),
4884 P: m_c_And(L: m_CombineAnd(Ps: m_AnyLogicalShift, Ps: m_Instruction(I&: XShift)),
4885 R: m_CombineAnd(Ps: m_TruncOrSelf(Op: m_CombineAnd(
4886 Ps: m_AnyLogicalShift, Ps: m_Instruction(I&: YShift))),
4887 Ps: m_Instruction(I&: MaybeTruncation)))))
4888 return nullptr;
4889
4890 // We potentially looked past 'trunc', but only when matching YShift,
4891 // therefore YShift must have the widest type.
4892 Instruction *WidestShift = YShift;
4893 // Therefore XShift must have the shallowest type.
4894 // Or they both have identical types if there was no truncation.
4895 Instruction *NarrowestShift = XShift;
4896
4897 Type *WidestTy = WidestShift->getType();
4898 Type *NarrowestTy = NarrowestShift->getType();
4899 assert(NarrowestTy == I.getOperand(0)->getType() &&
4900 "We did not look past any shifts while matching XShift though.");
4901 bool HadTrunc = WidestTy != I.getOperand(i_nocapture: 0)->getType();
4902
4903 // If YShift is a 'lshr', swap the shifts around.
4904 if (match(V: YShift, P: m_LShr(L: m_Value(), R: m_Value())))
4905 std::swap(a&: XShift, b&: YShift);
4906
4907 // The shifts must be in opposite directions.
4908 auto XShiftOpcode = XShift->getOpcode();
4909 if (XShiftOpcode == YShift->getOpcode())
4910 return nullptr; // Do not care about same-direction shifts here.
4911
4912 Value *X, *XShAmt, *Y, *YShAmt;
4913 match(V: XShift, P: m_BinOp(L: m_Value(V&: X), R: m_ZExtOrSelf(Op: m_Value(V&: XShAmt))));
4914 match(V: YShift, P: m_BinOp(L: m_Value(V&: Y), R: m_ZExtOrSelf(Op: m_Value(V&: YShAmt))));
4915
4916 // If one of the values being shifted is a constant, then we will end with
4917 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4918 // however, we will need to ensure that we won't increase instruction count.
4919 if (!isa<Constant>(Val: X) && !isa<Constant>(Val: Y)) {
4920 // At least one of the hands of the 'and' should be one-use shift.
4921 if (!match(V: I.getOperand(i_nocapture: 0),
4922 P: m_c_And(L: m_OneUse(SubPattern: m_AnyLogicalShift), R: m_Value())))
4923 return nullptr;
4924 if (HadTrunc) {
4925 // Due to the 'trunc', we will need to widen X. For that either the old
4926 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4927 if (!MaybeTruncation->hasOneUse() &&
4928 !NarrowestShift->getOperand(i: 1)->hasOneUse())
4929 return nullptr;
4930 }
4931 }
4932
4933 // We have two shift amounts from two different shifts. The types of those
4934 // shift amounts may not match. If that's the case let's bailout now.
4935 if (XShAmt->getType() != YShAmt->getType())
4936 return nullptr;
4937
4938 // As input, we have the following pattern:
4939 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4940 // We want to rewrite that as:
4941 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4942 // While we know that originally (Q+K) would not overflow
4943 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4944 // shift amounts. so it may now overflow in smaller bitwidth.
4945 // To ensure that does not happen, we need to ensure that the total maximal
4946 // shift amount is still representable in that smaller bit width.
4947 unsigned MaximalPossibleTotalShiftAmount =
4948 (WidestTy->getScalarSizeInBits() - 1) +
4949 (NarrowestTy->getScalarSizeInBits() - 1);
4950 APInt MaximalRepresentableShiftAmount =
4951 APInt::getAllOnes(numBits: XShAmt->getType()->getScalarSizeInBits());
4952 if (MaximalRepresentableShiftAmount.ult(RHS: MaximalPossibleTotalShiftAmount))
4953 return nullptr;
4954
4955 // Can we fold (XShAmt+YShAmt) ?
4956 auto *NewShAmt = dyn_cast_or_null<Constant>(
4957 Val: simplifyAddInst(LHS: XShAmt, RHS: YShAmt, /*isNSW=*/IsNSW: false,
4958 /*isNUW=*/IsNUW: false, Q: SQ.getWithInstruction(I: &I)));
4959 if (!NewShAmt)
4960 return nullptr;
4961 if (NewShAmt->getType() != WidestTy) {
4962 NewShAmt =
4963 ConstantFoldCastOperand(Opcode: Instruction::ZExt, C: NewShAmt, DestTy: WidestTy, DL: SQ.DL);
4964 if (!NewShAmt)
4965 return nullptr;
4966 }
4967 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4968
4969 // Is the new shift amount smaller than the bit width?
4970 // FIXME: could also rely on ConstantRange.
4971 if (!match(V: NewShAmt,
4972 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_ULT,
4973 Threshold: APInt(WidestBitWidth, WidestBitWidth))))
4974 return nullptr;
4975
4976 // An extra legality check is needed if we had trunc-of-lshr.
4977 if (HadTrunc && match(V: WidestShift, P: m_LShr(L: m_Value(), R: m_Value()))) {
4978 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4979 WidestShift]() {
4980 // It isn't obvious whether it's worth it to analyze non-constants here.
4981 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4982 // If *any* of these preconditions matches we can perform the fold.
4983 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4984 ? NewShAmt->getSplatValue()
4985 : NewShAmt;
4986 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4987 if (NewShAmtSplat &&
4988 (NewShAmtSplat->isNullValue() ||
4989 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4990 return true;
4991 // We consider *min* leading zeros so a single outlier
4992 // blocks the transform as opposed to allowing it.
4993 if (auto *C = dyn_cast<Constant>(Val: NarrowestShift->getOperand(i: 0))) {
4994 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
4995 unsigned MinLeadZero = Known.countMinLeadingZeros();
4996 // If the value being shifted has at most lowest bit set we can fold.
4997 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4998 if (MaxActiveBits <= 1)
4999 return true;
5000 // Precondition: NewShAmt u<= countLeadingZeros(C)
5001 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(RHS: MinLeadZero))
5002 return true;
5003 }
5004 if (auto *C = dyn_cast<Constant>(Val: WidestShift->getOperand(i: 0))) {
5005 KnownBits Known = computeKnownBits(V: C, DL: SQ.DL);
5006 unsigned MinLeadZero = Known.countMinLeadingZeros();
5007 // If the value being shifted has at most lowest bit set we can fold.
5008 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5009 if (MaxActiveBits <= 1)
5010 return true;
5011 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5012 if (NewShAmtSplat) {
5013 APInt AdjNewShAmt =
5014 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5015 if (AdjNewShAmt.ule(RHS: MinLeadZero))
5016 return true;
5017 }
5018 }
5019 return false; // Can't tell if it's ok.
5020 };
5021 if (!CanFold())
5022 return nullptr;
5023 }
5024
5025 // All good, we can do this fold.
5026 X = Builder.CreateZExt(V: X, DestTy: WidestTy);
5027 Y = Builder.CreateZExt(V: Y, DestTy: WidestTy);
5028 // The shift is the same that was for X.
5029 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5030 ? Builder.CreateLShr(LHS: X, RHS: NewShAmt)
5031 : Builder.CreateShl(LHS: X, RHS: NewShAmt);
5032 Value *T1 = Builder.CreateAnd(LHS: T0, RHS: Y);
5033 return Builder.CreateICmp(P: I.getPredicate(), LHS: T1,
5034 RHS: Constant::getNullValue(Ty: WidestTy));
5035}
5036
5037/// Fold
5038/// (-1 u/ x) u< y
5039/// ((x * y) ?/ x) != y
5040/// to
5041/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5042/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5043/// will mean that we are looking for the opposite answer.
5044Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
5045 CmpPredicate Pred;
5046 Value *X, *Y;
5047 Instruction *Mul;
5048 Instruction *Div;
5049 bool NeedNegation;
5050 // Look for: (-1 u/ x) u</u>= y
5051 if (!I.isEquality() &&
5052 match(V: &I, P: m_c_ICmp(Pred,
5053 L: m_CombineAnd(Ps: m_OneUse(SubPattern: m_UDiv(L: m_AllOnes(), R: m_Value(V&: X))),
5054 Ps: m_Instruction(I&: Div)),
5055 R: m_Value(V&: Y)))) {
5056 Mul = nullptr;
5057
5058 // Are we checking that overflow does not happen, or does happen?
5059 switch (Pred) {
5060 case ICmpInst::Predicate::ICMP_ULT:
5061 NeedNegation = false;
5062 break; // OK
5063 case ICmpInst::Predicate::ICMP_UGE:
5064 NeedNegation = true;
5065 break; // OK
5066 default:
5067 return nullptr; // Wrong predicate.
5068 }
5069 } else // Look for: ((x * y) / x) !=/== y
5070 if (I.isEquality() &&
5071 match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: Y),
5072 R: m_CombineAnd(Ps: m_OneUse(SubPattern: m_IDiv(
5073 L: m_CombineAnd(Ps: m_c_Mul(L: m_Deferred(V: Y),
5074 R: m_Value(V&: X)),
5075 Ps: m_Instruction(I&: Mul)),
5076 R: m_Deferred(V: X))),
5077 Ps: m_Instruction(I&: Div))))) {
5078 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5079 } else
5080 return nullptr;
5081
5082 BuilderTy::InsertPointGuard Guard(Builder);
5083 // If the pattern included (x * y), we'll want to insert new instructions
5084 // right before that original multiplication so that we can replace it.
5085 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5086 if (MulHadOtherUses)
5087 Builder.SetInsertPoint(Mul);
5088
5089 Value *Call = Builder.CreateIntrinsic(
5090 ID: Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5091 : Intrinsic::smul_with_overflow,
5092 OverloadTypes: X->getType(), Args: {X, Y}, /*FMFSource=*/nullptr, Name: "mul");
5093
5094 // If the multiplication was used elsewhere, to ensure that we don't leave
5095 // "duplicate" instructions, replace uses of that original multiplication
5096 // with the multiplication result from the with.overflow intrinsic.
5097 if (MulHadOtherUses)
5098 replaceInstUsesWith(I&: *Mul, V: Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "mul.val"));
5099
5100 Value *Res = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "mul.ov");
5101 if (NeedNegation) // This technically increases instruction count.
5102 Res = Builder.CreateNot(V: Res, Name: "mul.not.ov");
5103
5104 // If we replaced the mul, erase it. Do this after all uses of Builder,
5105 // as the mul is used as insertion point.
5106 if (MulHadOtherUses)
5107 eraseInstFromFunction(I&: *Mul);
5108
5109 return Res;
5110}
5111
5112static Instruction *foldICmpXNegX(ICmpInst &I,
5113 InstCombiner::BuilderTy &Builder) {
5114 CmpPredicate Pred;
5115 Value *X;
5116 if (match(V: &I, P: m_c_ICmp(Pred, L: m_NSWNeg(V: m_Value(V&: X)), R: m_Deferred(V: X)))) {
5117
5118 if (ICmpInst::isSigned(Pred))
5119 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5120 else if (ICmpInst::isUnsigned(Pred))
5121 Pred = ICmpInst::getSignedPredicate(Pred);
5122 // else for equality-comparisons just keep the predicate.
5123
5124 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: X,
5125 S2: Constant::getNullValue(Ty: X->getType()), Name: I.getName());
5126 }
5127
5128 // A value is not equal to its negation unless that value is 0 or
5129 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5130 if (match(V: &I, P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X))), R: m_Deferred(V: X))) &&
5131 ICmpInst::isEquality(P: Pred)) {
5132 Type *Ty = X->getType();
5133 uint32_t BitWidth = Ty->getScalarSizeInBits();
5134 Constant *MaxSignedVal =
5135 ConstantInt::get(Ty, V: APInt::getSignedMaxValue(numBits: BitWidth));
5136 Value *And = Builder.CreateAnd(LHS: X, RHS: MaxSignedVal);
5137 Constant *Zero = Constant::getNullValue(Ty);
5138 return CmpInst::Create(Op: Instruction::ICmp, Pred, S1: And, S2: Zero);
5139 }
5140
5141 return nullptr;
5142}
5143
5144static Instruction *foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q,
5145 InstCombinerImpl &IC) {
5146 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5147 // Normalize and operand as operand 0.
5148 CmpInst::Predicate Pred = I.getPredicate();
5149 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value()))) {
5150 std::swap(a&: Op0, b&: Op1);
5151 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5152 }
5153
5154 if (!match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5155 return nullptr;
5156
5157 // (icmp (X & Y) u< X --> (X & Y) != X
5158 if (Pred == ICmpInst::ICMP_ULT)
5159 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5160
5161 // (icmp (X & Y) u>= X --> (X & Y) == X
5162 if (Pred == ICmpInst::ICMP_UGE)
5163 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5164
5165 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5166 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5167 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5168 // so don't do this fold.
5169 if (!match(V: Op1, P: m_ImmConstant()))
5170 if (auto *NotOp1 =
5171 IC.getFreelyInverted(V: Op1, WillInvertAllUses: !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5172 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: A, RHS: NotOp1),
5173 Constant::getAllOnesValue(Ty: Op1->getType()));
5174 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5175 if (auto *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5176 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: Op1, RHS: NotA),
5177 Constant::getNullValue(Ty: Op1->getType()));
5178 }
5179
5180 if (!ICmpInst::isSigned(Pred))
5181 return nullptr;
5182
5183 KnownBits KnownY = IC.computeKnownBits(V: A, CxtI: &I);
5184 // (X & NegY) spred X --> (X & NegY) upred X
5185 if (KnownY.isNegative())
5186 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5187
5188 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5189 return nullptr;
5190
5191 if (KnownY.isNonNegative())
5192 // (X & PosY) s<= X --> X s>= 0
5193 // (X & PosY) s> X --> X s< 0
5194 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
5195 Constant::getNullValue(Ty: Op1->getType()));
5196
5197 if (isKnownNegative(V: Op1, SQ: IC.getSimplifyQuery().getWithInstruction(I: &I)))
5198 // (NegX & Y) s<= NegX --> Y s< 0
5199 // (NegX & Y) s> NegX --> Y s>= 0
5200 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5201 Constant::getNullValue(Ty: A->getType()));
5202
5203 return nullptr;
5204}
5205
5206static Instruction *foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q,
5207 InstCombinerImpl &IC) {
5208 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5209
5210 // Normalize or operand as operand 0.
5211 CmpInst::Predicate Pred = I.getPredicate();
5212 if (match(V: Op1, P: m_c_Or(L: m_Specific(V: Op0), R: m_Value(V&: A)))) {
5213 std::swap(a&: Op0, b&: Op1);
5214 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5215 } else if (!match(V: Op0, P: m_c_Or(L: m_Specific(V: Op1), R: m_Value(V&: A)))) {
5216 return nullptr;
5217 }
5218
5219 // icmp (X | Y) u<= X --> (X | Y) == X
5220 if (Pred == ICmpInst::ICMP_ULE)
5221 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5222
5223 // icmp (X | Y) u> X --> (X | Y) != X
5224 if (Pred == ICmpInst::ICMP_UGT)
5225 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5226
5227 if (ICmpInst::isEquality(P: Pred) && Op0->hasOneUse()) {
5228 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5229 if (Value *NotOp1 = IC.getFreelyInverted(
5230 V: Op1, WillInvertAllUses: !isa<Constant>(Val: Op1) && !Op1->hasNUsesOrMore(N: 3), Builder: &IC.Builder))
5231 return new ICmpInst(Pred, IC.Builder.CreateAnd(LHS: A, RHS: NotOp1),
5232 Constant::getNullValue(Ty: Op1->getType()));
5233 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5234 if (Value *NotA = IC.getFreelyInverted(V: A, WillInvertAllUses: A->hasOneUse(), Builder: &IC.Builder))
5235 return new ICmpInst(Pred, IC.Builder.CreateOr(LHS: Op1, RHS: NotA),
5236 Constant::getAllOnesValue(Ty: Op1->getType()));
5237 }
5238 return nullptr;
5239}
5240
5241static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
5242 InstCombinerImpl &IC) {
5243 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1), *A;
5244 // Normalize xor operand as operand 0.
5245 CmpInst::Predicate Pred = I.getPredicate();
5246 if (match(V: Op1, P: m_c_Xor(L: m_Specific(V: Op0), R: m_Value()))) {
5247 std::swap(a&: Op0, b&: Op1);
5248 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
5249 }
5250 if (!match(V: Op0, P: m_c_Xor(L: m_Specific(V: Op1), R: m_Value(V&: A))))
5251 return nullptr;
5252
5253 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5254 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5255 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5256 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5257 CmpInst::Predicate PredOut = CmpInst::getStrictPredicate(pred: Pred);
5258 if (PredOut != Pred && isKnownNonZero(V: A, Q))
5259 return new ICmpInst(PredOut, Op0, Op1);
5260
5261 // These transform work when A is negative.
5262 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5263 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5264 if (match(V: A, P: m_Negative())) {
5265 CmpInst::Predicate NewPred;
5266 switch (ICmpInst::getStrictPredicate(pred: Pred)) {
5267 default:
5268 return nullptr;
5269 case ICmpInst::ICMP_SLT:
5270 case ICmpInst::ICMP_UGT:
5271 NewPred = ICmpInst::ICMP_SLT;
5272 break;
5273 case ICmpInst::ICMP_SGT:
5274 case ICmpInst::ICMP_ULT:
5275 NewPred = ICmpInst::ICMP_SGE;
5276 break;
5277 }
5278 Constant *Const = Constant::getNullValue(Ty: Op0->getType());
5279 return new ICmpInst(NewPred, Op0, Const);
5280 }
5281
5282 return nullptr;
5283}
5284
5285/// Return true if X is a multiple of C.
5286/// TODO: Handle non-power-of-2 factors.
5287static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5288 if (C.isOne())
5289 return true;
5290
5291 if (!C.isPowerOf2())
5292 return false;
5293
5294 return MaskedValueIsZero(V: X, Mask: C - 1, SQ: Q);
5295}
5296
5297/// Try to fold icmp (binop), X or icmp X, (binop).
5298/// TODO: A large part of this logic is duplicated in InstSimplify's
5299/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5300/// duplication.
5301Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
5302 const SimplifyQuery &SQ) {
5303 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5304 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
5305
5306 // Special logic for binary operators.
5307 BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Val: Op0);
5308 BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Val: Op1);
5309 if (!BO0 && !BO1)
5310 return nullptr;
5311
5312 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5313 return NewICmp;
5314
5315 const CmpInst::Predicate Pred = I.getPredicate();
5316
5317 // (X urem Y) == X --> X u< Y
5318 // (X urem Y) != X --> X u>= Y
5319 Value *Dividend, *Divisor;
5320 if (I.isEquality() &&
5321 match(V: &I, P: m_c_ICmp(L: m_URem(L: m_Value(V&: Dividend), R: m_Value(V&: Divisor)),
5322 R: m_Deferred(V: Dividend)))) {
5323 CmpInst::Predicate NewPred =
5324 Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
5325 return new ICmpInst(NewPred, Dividend, Divisor);
5326 }
5327
5328 Value *X;
5329
5330 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5331 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5332 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)))) &&
5333 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5334 return new ICmpInst(Pred, Builder.CreateNot(V: Op1), X);
5335 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5336 if (match(V: Op1, P: m_OneUse(SubPattern: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)))) &&
5337 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5338 return new ICmpInst(Pred, X, Builder.CreateNot(V: Op0));
5339
5340 {
5341 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5342 Constant *C;
5343 if (match(V: Op0, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op1), R: m_Value(V&: X)),
5344 R: m_ImmConstant(C)))) &&
5345 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5346 Constant *C2 = ConstantExpr::getNot(C);
5347 return new ICmpInst(Pred, Builder.CreateSub(LHS: C2, RHS: X), Op1);
5348 }
5349 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5350 if (match(V: Op1, P: m_OneUse(SubPattern: m_Add(L: m_c_Add(L: m_Specific(V: Op0), R: m_Value(V&: X)),
5351 R: m_ImmConstant(C)))) &&
5352 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5353 Constant *C2 = ConstantExpr::getNot(C);
5354 return new ICmpInst(Pred, Op0, Builder.CreateSub(LHS: C2, RHS: X));
5355 }
5356 }
5357
5358 // (icmp eq/ne (X, -P2), INT_MIN)
5359 // -> (icmp slt/sge X, INT_MIN + P2)
5360 if (ICmpInst::isEquality(P: Pred) && BO0 &&
5361 match(V: I.getOperand(i_nocapture: 1), P: m_SignMask()) &&
5362 match(V: BO0, P: m_And(L: m_Value(), R: m_NegatedPower2OrZero()))) {
5363 // Will Constant fold.
5364 Value *NewC = Builder.CreateSub(LHS: I.getOperand(i_nocapture: 1), RHS: BO0->getOperand(i_nocapture: 1));
5365 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5366 : ICmpInst::ICMP_SGE,
5367 BO0->getOperand(i_nocapture: 0), NewC);
5368 }
5369
5370 {
5371 // Similar to above: an unsigned overflow comparison may use offset + mask:
5372 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5373 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5374 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5375 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5376 BinaryOperator *BO;
5377 const APInt *C;
5378 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5379 match(V: Op0, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5380 match(V: BO, P: m_Add(L: m_Specific(V: Op1), R: m_SpecificIntAllowPoison(V: *C)))) {
5381 CmpInst::Predicate NewPred =
5382 Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5383 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5384 return new ICmpInst(NewPred, Op1, Zero);
5385 }
5386
5387 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5388 match(V: Op1, P: m_And(L: m_BinOp(I&: BO), R: m_LowBitMask(V&: C))) &&
5389 match(V: BO, P: m_Add(L: m_Specific(V: Op0), R: m_SpecificIntAllowPoison(V: *C)))) {
5390 CmpInst::Predicate NewPred =
5391 Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
5392 Constant *Zero = ConstantInt::getNullValue(Ty: Op1->getType());
5393 return new ICmpInst(NewPred, Op0, Zero);
5394 }
5395 }
5396
5397 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5398 bool Op0HasNUW = false, Op1HasNUW = false;
5399 bool Op0HasNSW = false, Op1HasNSW = false;
5400 // Analyze the case when either Op0 or Op1 is an add instruction.
5401 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5402 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5403 bool &HasNSW, bool &HasNUW) -> bool {
5404 if (isa<OverflowingBinaryOperator>(Val: BO)) {
5405 HasNUW = BO.hasNoUnsignedWrap();
5406 HasNSW = BO.hasNoSignedWrap();
5407 return ICmpInst::isEquality(P: Pred) ||
5408 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5409 (CmpInst::isSigned(Pred) && HasNSW);
5410 } else if (BO.getOpcode() == Instruction::Or) {
5411 // The invariant here is that we are handling m_AddLike instructions,
5412 // which can only be a or disjoint, which is equivalent to an add nuw nsw.
5413 HasNUW = true;
5414 HasNSW = true;
5415 return true;
5416 } else {
5417 return false;
5418 }
5419 };
5420 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5421
5422 if (BO0) {
5423 match(V: BO0, P: m_AddLike(L: m_Value(V&: A), R: m_Value(V&: B)));
5424 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5425 }
5426 if (BO1) {
5427 match(V: BO1, P: m_AddLike(L: m_Value(V&: C), R: m_Value(V&: D)));
5428 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5429 }
5430
5431 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5432 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5433 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5434 return new ICmpInst(Pred, A == Op1 ? B : A,
5435 Constant::getNullValue(Ty: Op1->getType()));
5436
5437 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5438 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5439 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5440 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op0->getType()),
5441 C == Op0 ? D : C);
5442
5443 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5444 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5445 NoOp1WrapProblem) {
5446 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5447 Value *Y, *Z;
5448 if (A == C) {
5449 // C + B == C + D -> B == D
5450 Y = B;
5451 Z = D;
5452 } else if (A == D) {
5453 // D + B == C + D -> B == C
5454 Y = B;
5455 Z = C;
5456 } else if (B == C) {
5457 // A + C == C + D -> A == D
5458 Y = A;
5459 Z = D;
5460 } else {
5461 assert(B == D);
5462 // A + D == C + D -> A == C
5463 Y = A;
5464 Z = C;
5465 }
5466 return new ICmpInst(Pred, Y, Z);
5467 }
5468
5469 if (ICmpInst::isRelational(P: Pred)) {
5470 // Return if both X and Y is divisible by Z/-Z.
5471 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5472 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5473 bool IsNegative) -> bool {
5474 const APInt *OffsetC;
5475 if (!match(V: Z, P: m_APInt(Res&: OffsetC)))
5476 return false;
5477
5478 // Fast path for Z == 1/-1.
5479 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5480 return true;
5481
5482 APInt C = *OffsetC;
5483 if (IsNegative)
5484 C.negate();
5485 // Note: -INT_MIN is also negative.
5486 if (!C.isStrictlyPositive())
5487 return false;
5488
5489 return isMultipleOf(X, C, Q) && isMultipleOf(X: Y, C, Q);
5490 };
5491
5492 // The subtraction-related identities (A -nuw B) shown below require that
5493 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5494 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5495 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5496 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5497 // requires proving A <u B, for which the nowrap precondition can never be
5498 // satisfied. These are therefore skipped.
5499 //
5500 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5501 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5502 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5503 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5504
5505 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5506 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5507 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5508 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5509 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5510 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5511 bool IsNegative = ICmpInst::isLT(P: Pred) || ICmpInst::isGE(P: Pred);
5512 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5513 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5514 ShareCommonDivisor(A, Op1, B, IsNegative))
5515 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), A,
5516 Op1);
5517
5518 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5519 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5520 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5521 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5522 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5523 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5524 if (C && NoOp1WrapProblem &&
5525 ShareCommonDivisor(Op0, C, D,
5526 ICmpInst::isGT(P: Pred) || ICmpInst::isLE(P: Pred)))
5527 return new ICmpInst(ICmpInst::getFlippedStrictnessPredicate(pred: Pred), Op0,
5528 C);
5529 }
5530
5531 // if C1 has greater magnitude than C2:
5532 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5533 // s.t. C3 = C1 - C2
5534 //
5535 // if C2 has greater magnitude than C1:
5536 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5537 // s.t. C3 = C2 - C1
5538 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5539 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5540 const APInt *AP1, *AP2;
5541 // TODO: Support non-uniform vectors.
5542 // TODO: Allow poison passthrough if B or D's element is poison.
5543 if (match(V: B, P: m_APIntAllowPoison(Res&: AP1)) &&
5544 match(V: D, P: m_APIntAllowPoison(Res&: AP2)) &&
5545 AP1->isNegative() == AP2->isNegative()) {
5546 APInt AP1Abs = AP1->abs();
5547 APInt AP2Abs = AP2->abs();
5548 if (AP1Abs.uge(RHS: AP2Abs)) {
5549 APInt Diff = *AP1 - *AP2;
5550 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5551 Value *NewAdd = Builder.CreateAdd(
5552 LHS: A, RHS: C3, Name: "", HasNUW: Op0HasNUW && Diff.ule(RHS: *AP1), HasNSW: Op0HasNSW);
5553 return new ICmpInst(Pred, NewAdd, C);
5554 } else {
5555 APInt Diff = *AP2 - *AP1;
5556 Constant *C3 = Constant::getIntegerValue(Ty: BO0->getType(), V: Diff);
5557 Value *NewAdd = Builder.CreateAdd(
5558 LHS: C, RHS: C3, Name: "", HasNUW: Op1HasNUW && Diff.ule(RHS: *AP2), HasNSW: Op1HasNSW);
5559 return new ICmpInst(Pred, A, NewAdd);
5560 }
5561 }
5562 Constant *Cst1, *Cst2;
5563 if (match(V: B, P: m_ImmConstant(C&: Cst1)) && match(V: D, P: m_ImmConstant(C&: Cst2)) &&
5564 ICmpInst::isEquality(P: Pred)) {
5565 Constant *Diff = ConstantExpr::getSub(C1: Cst2, C2: Cst1);
5566 Value *NewAdd = Builder.CreateAdd(LHS: C, RHS: Diff);
5567 return new ICmpInst(Pred, A, NewAdd);
5568 }
5569 }
5570
5571 // Analyze the case when either Op0 or Op1 is a sub instruction.
5572 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5573 A = nullptr;
5574 B = nullptr;
5575 C = nullptr;
5576 D = nullptr;
5577 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5578 A = BO0->getOperand(i_nocapture: 0);
5579 B = BO0->getOperand(i_nocapture: 1);
5580 }
5581 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5582 C = BO1->getOperand(i_nocapture: 0);
5583 D = BO1->getOperand(i_nocapture: 1);
5584 }
5585
5586 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5587 if (A == Op1 && NoOp0WrapProblem)
5588 return new ICmpInst(Pred, Constant::getNullValue(Ty: Op1->getType()), B);
5589 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5590 if (C == Op0 && NoOp1WrapProblem)
5591 return new ICmpInst(Pred, D, Constant::getNullValue(Ty: Op0->getType()));
5592
5593 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5594 // (A - B) u>/u<= A --> B u>/u<= A
5595 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5596 return new ICmpInst(Pred, B, A);
5597 // C u</u>= (C - D) --> C u</u>= D
5598 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5599 return new ICmpInst(Pred, C, D);
5600 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5601 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5602 isKnownNonZero(V: B, Q))
5603 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), B, A);
5604 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5605 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5606 isKnownNonZero(V: D, Q))
5607 return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(pred: Pred), C, D);
5608
5609 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5610 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5611 return new ICmpInst(Pred, A, C);
5612
5613 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5614 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5615 return new ICmpInst(Pred, D, B);
5616
5617 // icmp (0-X) < cst --> x > -cst
5618 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5619 Value *X;
5620 if (match(V: BO0, P: m_Neg(V: m_Value(V&: X))))
5621 if (Constant *RHSC = dyn_cast<Constant>(Val: Op1))
5622 if (RHSC->isNotMinSignedValue())
5623 return new ICmpInst(I.getSwappedPredicate(), X,
5624 ConstantExpr::getNeg(C: RHSC));
5625 }
5626
5627 if (Instruction *R = foldICmpXorXX(I, Q, IC&: *this))
5628 return R;
5629 if (Instruction *R = foldICmpOrXX(I, Q, IC&: *this))
5630 return R;
5631
5632 {
5633 // Try to remove shared multiplier from comparison:
5634 // X * Z pred Y * Z
5635 Value *X, *Y, *Z;
5636 if ((match(V: Op0, P: m_Mul(L: m_Value(V&: X), R: m_Value(V&: Z))) &&
5637 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y)))) ||
5638 (match(V: Op0, P: m_Mul(L: m_Value(V&: Z), R: m_Value(V&: X))) &&
5639 match(V: Op1, P: m_c_Mul(L: m_Specific(V: Z), R: m_Value(V&: Y))))) {
5640 if (ICmpInst::isSigned(Pred)) {
5641 if (Op0HasNSW && Op1HasNSW) {
5642 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5643 if (ZKnown.isStrictlyPositive())
5644 return new ICmpInst(Pred, X, Y);
5645 if (ZKnown.isNegative())
5646 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), X, Y);
5647 Value *LessThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SLT, LHS: X, RHS: Y,
5648 Q: SQ.getWithInstruction(I: &I));
5649 if (LessThan && match(V: LessThan, P: m_One()))
5650 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Z,
5651 Constant::getNullValue(Ty: Z->getType()));
5652 Value *GreaterThan = simplifyICmpInst(Pred: ICmpInst::ICMP_SGT, LHS: X, RHS: Y,
5653 Q: SQ.getWithInstruction(I: &I));
5654 if (GreaterThan && match(V: GreaterThan, P: m_One()))
5655 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5656 }
5657 } else {
5658 bool NonZero;
5659 if (ICmpInst::isEquality(P: Pred)) {
5660 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5661 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5662 isKnownNonEqual(V1: X, V2: Y, SQ))
5663 return new ICmpInst(Pred, Z, Constant::getNullValue(Ty: Z->getType()));
5664
5665 KnownBits ZKnown = computeKnownBits(V: Z, CxtI: &I);
5666 // if Z % 2 != 0
5667 // X * Z eq/ne Y * Z -> X eq/ne Y
5668 if (ZKnown.countMaxTrailingZeros() == 0)
5669 return new ICmpInst(Pred, X, Y);
5670 NonZero = !ZKnown.One.isZero() || isKnownNonZero(V: Z, Q);
5671 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5672 // X * Z eq/ne Y * Z -> X eq/ne Y
5673 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5674 return new ICmpInst(Pred, X, Y);
5675 } else
5676 NonZero = isKnownNonZero(V: Z, Q);
5677
5678 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5679 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5680 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5681 return new ICmpInst(Pred, X, Y);
5682 }
5683 }
5684 }
5685
5686 BinaryOperator *SRem = nullptr;
5687 // icmp (srem X, Y), Y
5688 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(i_nocapture: 1))
5689 SRem = BO0;
5690 // icmp Y, (srem X, Y)
5691 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5692 Op0 == BO1->getOperand(i_nocapture: 1))
5693 SRem = BO1;
5694 if (SRem) {
5695 // We don't check hasOneUse to avoid increasing register pressure because
5696 // the value we use is the same value this instruction was already using.
5697 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(pred: Pred) : Pred) {
5698 default:
5699 break;
5700 case ICmpInst::ICMP_EQ:
5701 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5702 case ICmpInst::ICMP_NE:
5703 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5704 case ICmpInst::ICMP_SGT:
5705 case ICmpInst::ICMP_SGE:
5706 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(i_nocapture: 1),
5707 Constant::getAllOnesValue(Ty: SRem->getType()));
5708 case ICmpInst::ICMP_SLT:
5709 case ICmpInst::ICMP_SLE:
5710 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(i_nocapture: 1),
5711 Constant::getNullValue(Ty: SRem->getType()));
5712 }
5713 }
5714
5715 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5716 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5717 BO0->getOperand(i_nocapture: 1) == BO1->getOperand(i_nocapture: 1)) {
5718 switch (BO0->getOpcode()) {
5719 default:
5720 break;
5721 case Instruction::Add:
5722 case Instruction::Sub:
5723 case Instruction::Xor: {
5724 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5725 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5726
5727 const APInt *C;
5728 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C))) {
5729 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5730 if (C->isSignMask()) {
5731 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5732 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5733 }
5734
5735 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5736 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5737 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5738 NewPred = I.getSwappedPredicate(pred: NewPred);
5739 return new ICmpInst(NewPred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5740 }
5741 }
5742 break;
5743 }
5744 case Instruction::Mul: {
5745 if (!I.isEquality())
5746 break;
5747
5748 const APInt *C;
5749 if (match(V: BO0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C)) && !C->isZero() &&
5750 !C->isOne()) {
5751 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5752 // Mask = -1 >> count-trailing-zeros(C).
5753 if (unsigned TZs = C->countr_zero()) {
5754 Constant *Mask = ConstantInt::get(
5755 Ty: BO0->getType(),
5756 V: APInt::getLowBitsSet(numBits: C->getBitWidth(), loBitsSet: C->getBitWidth() - TZs));
5757 Value *And1 = Builder.CreateAnd(LHS: BO0->getOperand(i_nocapture: 0), RHS: Mask);
5758 Value *And2 = Builder.CreateAnd(LHS: BO1->getOperand(i_nocapture: 0), RHS: Mask);
5759 return new ICmpInst(Pred, And1, And2);
5760 }
5761 }
5762 break;
5763 }
5764 case Instruction::UDiv:
5765 case Instruction::LShr:
5766 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5767 break;
5768 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5769
5770 case Instruction::SDiv:
5771 if (!(I.isEquality() || match(V: BO0->getOperand(i_nocapture: 1), P: m_NonNegative())) ||
5772 !BO0->isExact() || !BO1->isExact())
5773 break;
5774 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5775
5776 case Instruction::AShr:
5777 if (!BO0->isExact() || !BO1->isExact())
5778 break;
5779 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5780
5781 case Instruction::Shl: {
5782 bool NUW = Op0HasNUW && Op1HasNUW;
5783 bool NSW = Op0HasNSW && Op1HasNSW;
5784 if (!NUW && !NSW)
5785 break;
5786 if (!NSW && I.isSigned())
5787 break;
5788 return new ICmpInst(Pred, BO0->getOperand(i_nocapture: 0), BO1->getOperand(i_nocapture: 0));
5789 }
5790 }
5791 }
5792
5793 if (BO0) {
5794 // Transform A & (L - 1) `ult` L --> L != 0
5795 auto LSubOne = m_Add(L: m_Specific(V: Op1), R: m_AllOnes());
5796 auto BitwiseAnd = m_c_And(L: m_Value(), R: LSubOne);
5797
5798 if (match(V: BO0, P: BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5799 auto *Zero = Constant::getNullValue(Ty: BO0->getType());
5800 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5801 }
5802 }
5803
5804 // For unsigned predicates / eq / ne:
5805 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5806 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5807 if (!ICmpInst::isSigned(Pred)) {
5808 if (match(V: Op0, P: m_Shl(L: m_Specific(V: Op1), R: m_One())))
5809 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5810 Constant::getNullValue(Ty: Op1->getType()));
5811 else if (match(V: Op1, P: m_Shl(L: m_Specific(V: Op0), R: m_One())))
5812 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5813 Constant::getNullValue(Ty: Op0->getType()), Op0);
5814 }
5815
5816 if (Value *V = foldMultiplicationOverflowCheck(I))
5817 return replaceInstUsesWith(I, V);
5818
5819 if (Instruction *R = foldICmpAndXX(I, Q, IC&: *this))
5820 return R;
5821
5822 if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
5823 return replaceInstUsesWith(I, V);
5824
5825 if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
5826 return replaceInstUsesWith(I, V);
5827
5828 return nullptr;
5829}
5830
5831/// Fold icmp Pred min|max(X, Y), Z.
5832Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
5833 MinMaxIntrinsic *MinMax,
5834 Value *Z, CmpPredicate Pred) {
5835 Value *X = MinMax->getLHS();
5836 Value *Y = MinMax->getRHS();
5837 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5838 return nullptr;
5839 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5840 // Revert the transform signed pred -> unsigned pred
5841 // TODO: We can flip the signedness of predicate if both operands of icmp
5842 // are negative.
5843 if (isKnownNonNegative(V: Z, SQ: SQ.getWithInstruction(I: &I)) &&
5844 isKnownNonNegative(V: MinMax, SQ: SQ.getWithInstruction(I: &I))) {
5845 Pred = ICmpInst::getFlippedSignednessPredicate(Pred);
5846 } else
5847 return nullptr;
5848 }
5849 SimplifyQuery Q = SQ.getWithInstruction(I: &I);
5850 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5851 if (!Val)
5852 return std::nullopt;
5853 if (match(V: Val, P: m_One()))
5854 return true;
5855 if (match(V: Val, P: m_Zero()))
5856 return false;
5857 return std::nullopt;
5858 };
5859 // Remove samesign here since it is illegal to keep it when we speculatively
5860 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5861 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5862 // -46, -32)`. `X` is allowed to be non-negative here.
5863 Pred = Pred.dropSameSign();
5864 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: X, RHS: Z, Q));
5865 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, LHS: Y, RHS: Z, Q));
5866 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5867 return nullptr;
5868 if (!CmpXZ.has_value()) {
5869 std::swap(a&: X, b&: Y);
5870 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5871 }
5872
5873 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5874 if (CmpYZ.has_value())
5875 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *CmpYZ));
5876 return ICmpInst::Create(Op: Instruction::ICmp, Pred, S1: Y, S2: Z);
5877 };
5878
5879 switch (Pred) {
5880 case ICmpInst::ICMP_EQ:
5881 case ICmpInst::ICMP_NE: {
5882 // If X == Z:
5883 // Expr Result
5884 // min(X, Y) == Z X <= Y
5885 // max(X, Y) == Z X >= Y
5886 // min(X, Y) != Z X > Y
5887 // max(X, Y) != Z X < Y
5888 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5889 ICmpInst::Predicate NewPred =
5890 ICmpInst::getNonStrictPredicate(pred: MinMax->getPredicate());
5891 if (Pred == ICmpInst::ICMP_NE)
5892 NewPred = ICmpInst::getInversePredicate(pred: NewPred);
5893 return ICmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: X, S2: Y);
5894 }
5895 // Otherwise (X != Z):
5896 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5897 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5898 if (!MinMaxCmpXZ.has_value()) {
5899 std::swap(a&: X, b&: Y);
5900 std::swap(lhs&: CmpXZ, rhs&: CmpYZ);
5901 // Re-check pre-condition X != Z
5902 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5903 break;
5904 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred: NewPred, LHS: X, RHS: Z, Q));
5905 }
5906 if (!MinMaxCmpXZ.has_value())
5907 break;
5908 if (*MinMaxCmpXZ) {
5909 // Expr Fact Result
5910 // min(X, Y) == Z X < Z false
5911 // max(X, Y) == Z X > Z false
5912 // min(X, Y) != Z X < Z true
5913 // max(X, Y) != Z X > Z true
5914 return replaceInstUsesWith(
5915 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred == ICmpInst::ICMP_NE));
5916 } else {
5917 // Expr Fact Result
5918 // min(X, Y) == Z X > Z Y == Z
5919 // max(X, Y) == Z X < Z Y == Z
5920 // min(X, Y) != Z X > Z Y != Z
5921 // max(X, Y) != Z X < Z Y != Z
5922 return FoldIntoCmpYZ();
5923 }
5924 break;
5925 }
5926 case ICmpInst::ICMP_SLT:
5927 case ICmpInst::ICMP_ULT:
5928 case ICmpInst::ICMP_SLE:
5929 case ICmpInst::ICMP_ULE:
5930 case ICmpInst::ICMP_SGT:
5931 case ICmpInst::ICMP_UGT:
5932 case ICmpInst::ICMP_SGE:
5933 case ICmpInst::ICMP_UGE: {
5934 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(pred: Pred);
5935 if (*CmpXZ) {
5936 if (IsSame) {
5937 // Expr Fact Result
5938 // min(X, Y) < Z X < Z true
5939 // min(X, Y) <= Z X <= Z true
5940 // max(X, Y) > Z X > Z true
5941 // max(X, Y) >= Z X >= Z true
5942 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
5943 } else {
5944 // Expr Fact Result
5945 // max(X, Y) < Z X < Z Y < Z
5946 // max(X, Y) <= Z X <= Z Y <= Z
5947 // min(X, Y) > Z X > Z Y > Z
5948 // min(X, Y) >= Z X >= Z Y >= Z
5949 return FoldIntoCmpYZ();
5950 }
5951 } else {
5952 if (IsSame) {
5953 // Expr Fact Result
5954 // min(X, Y) < Z X >= Z Y < Z
5955 // min(X, Y) <= Z X > Z Y <= Z
5956 // max(X, Y) > Z X <= Z Y > Z
5957 // max(X, Y) >= Z X < Z Y >= Z
5958 return FoldIntoCmpYZ();
5959 } else {
5960 // Expr Fact Result
5961 // max(X, Y) < Z X >= Z false
5962 // max(X, Y) <= Z X > Z false
5963 // min(X, Y) > Z X <= Z false
5964 // min(X, Y) >= Z X < Z false
5965 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
5966 }
5967 }
5968 break;
5969 }
5970 default:
5971 break;
5972 }
5973
5974 return nullptr;
5975}
5976
5977/// Match and fold patterns like:
5978/// icmp eq/ne X, min(max(X, Lo), Hi)
5979/// which represents a range check and can be represented as a ConstantRange.
5980///
5981/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5982/// (X - Lo) u< (Hi + 1 - Lo)
5983/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5984/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5985Instruction *InstCombinerImpl::foldICmpWithClamp(ICmpInst &I, Value *X,
5986 MinMaxIntrinsic *Min) {
5987 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5988 return nullptr;
5989
5990 const APInt *Lo = nullptr, *Hi = nullptr;
5991 if (Min->isSigned()) {
5992 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_SMax(Op0: m_Specific(V: X), Op1: m_APInt(Res&: Lo)))) ||
5993 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->slt(RHS: *Hi))
5994 return nullptr;
5995 } else {
5996 if (!match(V: Min->getLHS(), P: m_OneUse(SubPattern: m_UMax(Op0: m_Specific(V: X), Op1: m_APInt(Res&: Lo)))) ||
5997 !match(V: Min->getRHS(), P: m_APInt(Res&: Hi)) || !Lo->ult(RHS: *Hi))
5998 return nullptr;
5999 }
6000
6001 ConstantRange CR = ConstantRange::getNonEmpty(Lower: *Lo, Upper: *Hi + 1);
6002 ICmpInst::Predicate Pred;
6003 APInt C, Offset;
6004 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6005 CR.getEquivalentICmp(Pred, RHS&: C, Offset);
6006 else
6007 CR.inverse().getEquivalentICmp(Pred, RHS&: C, Offset);
6008
6009 if (!Offset.isZero())
6010 X = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: Offset));
6011
6012 return replaceInstUsesWith(
6013 I, V: Builder.CreateICmp(P: Pred, LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: C)));
6014}
6015
6016// Canonicalize checking for a power-of-2-or-zero value:
6017static Instruction *foldICmpPow2Test(ICmpInst &I,
6018 InstCombiner::BuilderTy &Builder) {
6019 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6020 const CmpInst::Predicate Pred = I.getPredicate();
6021 Value *A = nullptr;
6022 bool CheckIs;
6023 if (I.isEquality()) {
6024 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6025 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6026 if (!match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Add(L: m_Value(V&: A), R: m_AllOnes()),
6027 R: m_Deferred(V: A)))) ||
6028 !match(V: Op1, P: m_ZeroInt()))
6029 A = nullptr;
6030
6031 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6032 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6033 if (match(V: Op0, P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op1)), R: m_Specific(V: Op1)))))
6034 A = Op1;
6035 else if (match(V: Op1,
6036 P: m_OneUse(SubPattern: m_c_And(L: m_Neg(V: m_Specific(V: Op0)), R: m_Specific(V: Op0)))))
6037 A = Op0;
6038
6039 CheckIs = Pred == ICmpInst::ICMP_EQ;
6040 } else if (ICmpInst::isUnsigned(Pred)) {
6041 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6042 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6043
6044 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6045 match(V: Op0, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op1), R: m_AllOnes()),
6046 R: m_Specific(V: Op1))))) {
6047 A = Op1;
6048 CheckIs = Pred == ICmpInst::ICMP_UGE;
6049 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6050 match(V: Op1, P: m_OneUse(SubPattern: m_c_Xor(L: m_Add(L: m_Specific(V: Op0), R: m_AllOnes()),
6051 R: m_Specific(V: Op0))))) {
6052 A = Op0;
6053 CheckIs = Pred == ICmpInst::ICMP_ULE;
6054 }
6055 }
6056
6057 if (A) {
6058 Type *Ty = A->getType();
6059 Value *CtPop = Builder.CreateUnaryIntrinsic(ID: Intrinsic::ctpop, Op: A);
6060 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6061 ConstantInt::get(Ty, V: 2))
6062 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6063 ConstantInt::get(Ty, V: 1));
6064 }
6065
6066 return nullptr;
6067}
6068
6069/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6070using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6071static void collectOffsetOp(Value *V, SmallVectorImpl<OffsetOp> &Offsets,
6072 bool AllowRecursion) {
6073 Instruction *Inst = dyn_cast<Instruction>(Val: V);
6074 if (!Inst || !Inst->hasOneUse())
6075 return;
6076
6077 switch (Inst->getOpcode()) {
6078 case Instruction::Add:
6079 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 1));
6080 Offsets.emplace_back(Args: Instruction::Sub, Args: Inst->getOperand(i: 0));
6081 break;
6082 case Instruction::Sub:
6083 Offsets.emplace_back(Args: Instruction::Add, Args: Inst->getOperand(i: 1));
6084 break;
6085 case Instruction::Xor:
6086 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 1));
6087 Offsets.emplace_back(Args: Instruction::Xor, Args: Inst->getOperand(i: 0));
6088 break;
6089 case Instruction::Shl:
6090 if (Inst->hasNoSignedWrap())
6091 Offsets.emplace_back(Args: Instruction::AShr, Args: Inst->getOperand(i: 1));
6092 if (Inst->hasNoUnsignedWrap())
6093 Offsets.emplace_back(Args: Instruction::LShr, Args: Inst->getOperand(i: 1));
6094 break;
6095 case Instruction::Select:
6096 if (AllowRecursion) {
6097 collectOffsetOp(V: Inst->getOperand(i: 1), Offsets, /*AllowRecursion=*/false);
6098 collectOffsetOp(V: Inst->getOperand(i: 2), Offsets, /*AllowRecursion=*/false);
6099 }
6100 break;
6101 default:
6102 break;
6103 }
6104}
6105
6106enum class OffsetKind { Invalid, Value, Select };
6107
6108struct OffsetResult {
6109 OffsetKind Kind;
6110 Value *V0, *V1, *V2;
6111 Instruction *MDFrom;
6112
6113 static OffsetResult invalid() {
6114 return {.Kind: OffsetKind::Invalid, .V0: nullptr, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
6115 }
6116 static OffsetResult value(Value *V) {
6117 return {.Kind: OffsetKind::Value, .V0: V, .V1: nullptr, .V2: nullptr, .MDFrom: nullptr};
6118 }
6119 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6120 Instruction *MDFrom) {
6121 return {.Kind: OffsetKind::Select, .V0: Cond, .V1: TrueV, .V2: FalseV, .MDFrom: MDFrom};
6122 }
6123 bool isValid() const { return Kind != OffsetKind::Invalid; }
6124 Value *materialize(InstCombiner::BuilderTy &Builder) const {
6125 switch (Kind) {
6126 case OffsetKind::Invalid:
6127 llvm_unreachable("Invalid offset result");
6128 case OffsetKind::Value:
6129 return V0;
6130 case OffsetKind::Select:
6131 return Builder.CreateSelect(C: V0, True: V1, False: V2, Name: "", MDFrom);
6132 }
6133 llvm_unreachable("Unknown OffsetKind enum");
6134 }
6135};
6136
6137/// Offset both sides of an equality icmp to see if we can save some
6138/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6139/// Note: This operation should not introduce poison.
6140static Instruction *foldICmpEqualityWithOffset(ICmpInst &I,
6141 InstCombiner::BuilderTy &Builder,
6142 const SimplifyQuery &SQ) {
6143 assert(I.isEquality() && "Expected an equality icmp");
6144 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6145 if (!Op0->getType()->isIntOrIntVectorTy())
6146 return nullptr;
6147
6148 SmallVector<OffsetOp, 4> OffsetOps;
6149 collectOffsetOp(V: Op0, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6150 collectOffsetOp(V: Op1, Offsets&: OffsetOps, /*AllowRecursion=*/true);
6151
6152 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6153 switch (BinOpc) {
6154 // V = shl nsw X, RHS => X = ashr V, RHS
6155 case Instruction::AShr: {
6156 const APInt *CV, *CRHS;
6157 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6158 CV->ashr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6159 !match(V, P: m_NSWShl(L: m_Value(), R: m_Specific(V: RHS))))
6160 return nullptr;
6161 break;
6162 }
6163 // V = shl nuw X, RHS => X = lshr V, RHS
6164 case Instruction::LShr: {
6165 const APInt *CV, *CRHS;
6166 if (!(match(V, P: m_APInt(Res&: CV)) && match(V: RHS, P: m_APInt(Res&: CRHS)) &&
6167 CV->lshr(ShiftAmt: *CRHS).shl(ShiftAmt: *CRHS) == *CV) &&
6168 !match(V, P: m_NUWShl(L: m_Value(), R: m_Specific(V: RHS))))
6169 return nullptr;
6170 break;
6171 }
6172 default:
6173 break;
6174 }
6175
6176 Value *Simplified = simplifyBinOp(Opcode: BinOpc, LHS: V, RHS, Q: SQ);
6177 if (!Simplified)
6178 return nullptr;
6179 // Reject constant expressions as they don't simplify things.
6180 if (isa<Constant>(Val: Simplified) && !match(V: Simplified, P: m_ImmConstant()))
6181 return nullptr;
6182 // Check if the transformation introduces poison.
6183 return impliesPoison(ValAssumedPoison: RHS, V) ? Simplified : nullptr;
6184 };
6185
6186 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6187 Value *RHS) -> OffsetResult {
6188 if (auto *Sel = dyn_cast<SelectInst>(Val: V)) {
6189 if (!Sel->hasOneUse())
6190 return OffsetResult::invalid();
6191 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6192 if (!TrueVal)
6193 return OffsetResult::invalid();
6194 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6195 if (!FalseVal)
6196 return OffsetResult::invalid();
6197 return OffsetResult::select(Cond: Sel->getCondition(), TrueV: TrueVal, FalseV: FalseVal, MDFrom: Sel);
6198 }
6199 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6200 return OffsetResult::value(V: Simplified);
6201 return OffsetResult::invalid();
6202 };
6203
6204 for (auto [BinOp, RHS] : OffsetOps) {
6205 auto BinOpc = static_cast<unsigned>(BinOp);
6206
6207 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6208 if (!Op0Result.isValid())
6209 continue;
6210 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6211 if (!Op1Result.isValid())
6212 continue;
6213
6214 Value *NewLHS = Op0Result.materialize(Builder);
6215 Value *NewRHS = Op1Result.materialize(Builder);
6216 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6217 }
6218
6219 return nullptr;
6220}
6221
6222Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
6223 if (!I.isEquality())
6224 return nullptr;
6225
6226 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
6227 const CmpInst::Predicate Pred = I.getPredicate();
6228 Value *A, *B, *C, *D;
6229 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) {
6230 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6231 Value *OtherVal = A == Op1 ? B : A;
6232 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6233 }
6234
6235 if (match(V: Op1, P: m_Xor(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6236 // A^c1 == C^c2 --> A == C^(c1^c2)
6237 ConstantInt *C1, *C2;
6238 if (match(V: B, P: m_ConstantInt(CI&: C1)) && match(V: D, P: m_ConstantInt(CI&: C2)) &&
6239 Op1->hasOneUse()) {
6240 Constant *NC = Builder.getInt(AI: C1->getValue() ^ C2->getValue());
6241 Value *Xor = Builder.CreateXor(LHS: C, RHS: NC);
6242 return new ICmpInst(Pred, A, Xor);
6243 }
6244
6245 // A^B == A^D -> B == D
6246 if (A == C)
6247 return new ICmpInst(Pred, B, D);
6248 if (A == D)
6249 return new ICmpInst(Pred, B, C);
6250 if (B == C)
6251 return new ICmpInst(Pred, A, D);
6252 if (B == D)
6253 return new ICmpInst(Pred, A, C);
6254 }
6255 }
6256
6257 if (match(V: Op1, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == Op0 || B == Op0)) {
6258 // A == (A^B) -> B == 0
6259 Value *OtherVal = A == Op0 ? B : A;
6260 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(Ty: A->getType()));
6261 }
6262
6263 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6264 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_Value(V&: B))) &&
6265 match(V: Op1, P: m_And(L: m_Value(V&: C), R: m_Value(V&: D)))) {
6266 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6267
6268 if (A == C) {
6269 X = B;
6270 Y = D;
6271 Z = A;
6272 } else if (A == D) {
6273 X = B;
6274 Y = C;
6275 Z = A;
6276 } else if (B == C) {
6277 X = A;
6278 Y = D;
6279 Z = B;
6280 } else if (B == D) {
6281 X = A;
6282 Y = C;
6283 Z = B;
6284 }
6285
6286 if (X) {
6287 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6288 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6289 // instructions.
6290 const APInt *C0, *C1;
6291 bool XorIsNegP2 = match(V: X, P: m_APInt(Res&: C0)) && match(V: Y, P: m_APInt(Res&: C1)) &&
6292 (*C0 ^ *C1).isNegatedPowerOf2();
6293
6294 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6295 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6296 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6297 int UseCnt =
6298 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6299 (int(match(V: X, P: m_ImmConstant()) && match(V: Y, P: m_ImmConstant())));
6300 if (XorIsNegP2 || UseCnt >= 2) {
6301 // Build (X^Y) & Z
6302 Op1 = Builder.CreateXor(LHS: X, RHS: Y);
6303 Op1 = Builder.CreateAnd(LHS: Op1, RHS: Z);
6304 return new ICmpInst(Pred, Op1, Constant::getNullValue(Ty: Op1->getType()));
6305 }
6306 }
6307 }
6308
6309 {
6310 // Similar to above, but specialized for constant because invert is needed:
6311 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6312 Value *X, *Y;
6313 Constant *C;
6314 if (match(V: Op0, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: X), R: m_Constant(C)))) &&
6315 match(V: Op1, P: m_OneUse(SubPattern: m_Or(L: m_Value(V&: Y), R: m_Specific(V: C))))) {
6316 Value *Xor = Builder.CreateXor(LHS: X, RHS: Y);
6317 Value *And = Builder.CreateAnd(LHS: Xor, RHS: ConstantExpr::getNot(C));
6318 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: And->getType()));
6319 }
6320 }
6321
6322 if (match(V: Op1, P: m_ZExt(Op: m_Value(V&: A))) &&
6323 (Op0->hasOneUse() || Op1->hasOneUse())) {
6324 // (B & (Pow2C-1)) == zext A --> A == trunc B
6325 // (B & (Pow2C-1)) != zext A --> A != trunc B
6326 const APInt *MaskC;
6327 if (match(V: Op0, P: m_And(L: m_Value(V&: B), R: m_LowBitMask(V&: MaskC))) &&
6328 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6329 return new ICmpInst(Pred, A, Builder.CreateTrunc(V: B, DestTy: A->getType()));
6330 }
6331
6332 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6333 // For lshr and ashr pairs.
6334 const APInt *AP1, *AP2;
6335 if ((match(V: Op0, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6336 match(V: Op1, P: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2))))) ||
6337 (match(V: Op0, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: A), R: m_APIntAllowPoison(Res&: AP1)))) &&
6338 match(V: Op1, P: m_OneUse(SubPattern: m_AShr(L: m_Value(V&: B), R: m_APIntAllowPoison(Res&: AP2)))))) {
6339 if (*AP1 != *AP2)
6340 return nullptr;
6341 unsigned TypeBits = AP1->getBitWidth();
6342 unsigned ShAmt = AP1->getLimitedValue(Limit: TypeBits);
6343 if (ShAmt < TypeBits && ShAmt != 0) {
6344 ICmpInst::Predicate NewPred =
6345 Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6346 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6347 APInt CmpVal = APInt::getOneBitSet(numBits: TypeBits, BitNo: ShAmt);
6348 return new ICmpInst(NewPred, Xor, ConstantInt::get(Ty: A->getType(), V: CmpVal));
6349 }
6350 }
6351
6352 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6353 ConstantInt *Cst1;
6354 if (match(V: Op0, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: A), R: m_ConstantInt(CI&: Cst1)))) &&
6355 match(V: Op1, P: m_OneUse(SubPattern: m_Shl(L: m_Value(V&: B), R: m_Specific(V: Cst1))))) {
6356 unsigned TypeBits = Cst1->getBitWidth();
6357 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(Limit: TypeBits);
6358 if (ShAmt < TypeBits && ShAmt != 0) {
6359 Value *Xor = Builder.CreateXor(LHS: A, RHS: B, Name: I.getName() + ".unshifted");
6360 APInt AndVal = APInt::getLowBitsSet(numBits: TypeBits, loBitsSet: TypeBits - ShAmt);
6361 Value *And =
6362 Builder.CreateAnd(LHS: Xor, RHS: Builder.getInt(AI: AndVal), Name: I.getName() + ".mask");
6363 return new ICmpInst(Pred, And, Constant::getNullValue(Ty: Cst1->getType()));
6364 }
6365 }
6366
6367 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6368 // "icmp (and X, mask), cst"
6369 uint64_t ShAmt = 0;
6370 if (Op0->hasOneUse() &&
6371 match(V: Op0, P: m_Trunc(Op: m_OneUse(SubPattern: m_LShr(L: m_Value(V&: A), R: m_ConstantInt(V&: ShAmt))))) &&
6372 match(V: Op1, P: m_ConstantInt(CI&: Cst1)) &&
6373 // Only do this when A has multiple uses. This is most important to do
6374 // when it exposes other optimizations.
6375 !A->hasOneUse()) {
6376 unsigned ASize = cast<IntegerType>(Val: A->getType())->getPrimitiveSizeInBits();
6377
6378 if (ShAmt < ASize) {
6379 APInt MaskV =
6380 APInt::getLowBitsSet(numBits: ASize, loBitsSet: Op0->getType()->getPrimitiveSizeInBits());
6381 MaskV <<= ShAmt;
6382
6383 APInt CmpV = Cst1->getValue().zext(width: ASize);
6384 CmpV <<= ShAmt;
6385
6386 Value *Mask = Builder.CreateAnd(LHS: A, RHS: Builder.getInt(AI: MaskV));
6387 return new ICmpInst(Pred, Mask, Builder.getInt(AI: CmpV));
6388 }
6389 }
6390
6391 if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(Cmp&: I, Builder))
6392 return ICmp;
6393
6394 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6395 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6396 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6397 // few steps of instcombine.
6398 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6399 if (match(V: Op0, P: m_AShr(L: m_Trunc(Op: m_Value(V&: A)), R: m_SpecificInt(V: BitWidth - 1))) &&
6400 match(V: Op1, P: m_Trunc(Op: m_LShr(L: m_Specific(V: A), R: m_SpecificInt(V: BitWidth)))) &&
6401 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6402 (I.getOperand(i_nocapture: 0)->hasOneUse() || I.getOperand(i_nocapture: 1)->hasOneUse())) {
6403 APInt C = APInt::getOneBitSet(numBits: BitWidth * 2, BitNo: BitWidth - 1);
6404 Value *Add = Builder.CreateAdd(LHS: A, RHS: ConstantInt::get(Ty: A->getType(), V: C));
6405 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6406 : ICmpInst::ICMP_UGE,
6407 Add, ConstantInt::get(Ty: A->getType(), V: C.shl(shiftAmt: 1)));
6408 }
6409
6410 // Canonicalize:
6411 // Assume B_Pow2 != 0
6412 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6413 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6414 if (match(V: Op0, P: m_c_And(L: m_Specific(V: Op1), R: m_Value())) &&
6415 isKnownToBeAPowerOfTwo(V: Op1, /* OrZero */ false, CxtI: &I))
6416 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
6417 ConstantInt::getNullValue(Ty: Op0->getType()));
6418
6419 if (match(V: Op1, P: m_c_And(L: m_Specific(V: Op0), R: m_Value())) &&
6420 isKnownToBeAPowerOfTwo(V: Op0, /* OrZero */ false, CxtI: &I))
6421 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op1,
6422 ConstantInt::getNullValue(Ty: Op1->getType()));
6423
6424 // Canonicalize:
6425 // icmp eq/ne X, OneUse(rotate-right(X))
6426 // -> icmp eq/ne X, rotate-left(X)
6427 // We generally try to convert rotate-right -> rotate-left, this just
6428 // canonicalizes another case.
6429 if (match(V: &I, P: m_c_ICmp(L: m_Value(V&: A),
6430 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::fshr>(
6431 Ops: m_Deferred(V: A), Ops: m_Deferred(V: A), Ops: m_Value(V&: B))))))
6432 return new ICmpInst(
6433 Pred, A,
6434 Builder.CreateIntrinsic(RetTy: Op0->getType(), ID: Intrinsic::fshl, Args: {A, A, B}));
6435
6436 // Canonicalize:
6437 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6438 Constant *Cst;
6439 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_Xor(L: m_Value(V&: A), R: m_ImmConstant(C&: Cst))),
6440 R: m_CombineAnd(Ps: m_Value(V&: B), Ps: m_Unless(P: m_ImmConstant())))))
6441 return new ICmpInst(Pred, Builder.CreateXor(LHS: A, RHS: B), Cst);
6442
6443 {
6444 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6445 auto m_Matcher =
6446 m_CombineOr(Ps: m_CombineOr(Ps: m_c_Add(L: m_Value(V&: B), R: m_Deferred(V: A)),
6447 Ps: m_c_Xor(L: m_Value(V&: B), R: m_Deferred(V: A))),
6448 Ps: m_Sub(L: m_Value(V&: B), R: m_Deferred(V: A)));
6449 std::optional<bool> IsZero = std::nullopt;
6450 if (match(V: &I, P: m_c_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)),
6451 R: m_Deferred(V: A))))
6452 IsZero = false;
6453 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6454 else if (match(V: &I,
6455 P: m_ICmp(L: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: A), R: m_Matcher)), R: m_Zero())))
6456 IsZero = true;
6457
6458 if (IsZero && isKnownToBeAPowerOfTwo(V: A, /* OrZero */ true, CxtI: &I))
6459 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6460 // -> (icmp eq/ne (and X, P2), 0)
6461 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6462 // -> (icmp eq/ne (and X, P2), P2)
6463 return new ICmpInst(Pred, Builder.CreateAnd(LHS: B, RHS: A),
6464 *IsZero ? A
6465 : ConstantInt::getNullValue(Ty: A->getType()));
6466 }
6467
6468 if (auto *Res = foldICmpEqualityWithOffset(
6469 I, Builder, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
6470 return Res;
6471
6472 return nullptr;
6473}
6474
6475Instruction *InstCombinerImpl::foldICmpWithTrunc(ICmpInst &ICmp) {
6476 ICmpInst::Predicate Pred = ICmp.getPredicate();
6477 Value *Op0 = ICmp.getOperand(i_nocapture: 0), *Op1 = ICmp.getOperand(i_nocapture: 1);
6478
6479 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6480 // The trunc masks high bits while the compare may effectively mask low bits.
6481 Value *X;
6482 const APInt *C;
6483 if (!match(V: Op0, P: m_OneUse(SubPattern: m_Trunc(Op: m_Value(V&: X)))) || !match(V: Op1, P: m_APInt(Res&: C)))
6484 return nullptr;
6485
6486 // This matches patterns corresponding to tests of the signbit as well as:
6487 // (trunc X) pred C2 --> (X & Mask) == C
6488 if (auto Res = decomposeBitTestICmp(LHS: Op0, RHS: Op1, Pred, /*LookThroughTrunc=*/true,
6489 /*AllowNonZeroC=*/true)) {
6490 Value *And = Builder.CreateAnd(LHS: Res->X, RHS: Res->Mask);
6491 Constant *C = ConstantInt::get(Ty: Res->X->getType(), V: Res->C);
6492 return new ICmpInst(Res->Pred, And, C);
6493 }
6494
6495 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6496 if (auto *II = dyn_cast<IntrinsicInst>(Val: X)) {
6497 if (II->getIntrinsicID() == Intrinsic::cttz ||
6498 II->getIntrinsicID() == Intrinsic::ctlz) {
6499 unsigned MaxRet = SrcBits;
6500 // If the "is_zero_poison" argument is set, then we know at least
6501 // one bit is set in the input, so the result is always at least one
6502 // less than the full bitwidth of that input.
6503 if (match(V: II->getArgOperand(i: 1), P: m_One()))
6504 MaxRet--;
6505
6506 // Make sure the destination is wide enough to hold the largest output of
6507 // the intrinsic.
6508 if (llvm::Log2_32(Value: MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6509 if (Instruction *I =
6510 foldICmpIntrinsicWithConstant(Cmp&: ICmp, II, C: C->zext(width: SrcBits)))
6511 return I;
6512 }
6513 }
6514
6515 return nullptr;
6516}
6517
6518Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
6519 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6520 auto *CastOp0 = cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6521 Value *X;
6522 if (!match(V: CastOp0, P: m_ZExtOrSExt(Op: m_Value(V&: X))))
6523 return nullptr;
6524
6525 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6526 bool IsSignedCmp = ICmp.isSigned();
6527
6528 // icmp Pred (ext X), (ext Y)
6529 Value *Y;
6530 if (match(V: ICmp.getOperand(i_nocapture: 1), P: m_ZExtOrSExt(Op: m_Value(V&: Y)))) {
6531 bool IsZext0 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 0));
6532 bool IsZext1 = isa<ZExtInst>(Val: ICmp.getOperand(i_nocapture: 1));
6533
6534 if (IsZext0 != IsZext1) {
6535 // If X and Y and both i1
6536 // (icmp eq/ne (zext X) (sext Y))
6537 // eq -> (icmp eq (or X, Y), 0)
6538 // ne -> (icmp ne (or X, Y), 0)
6539 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
6540 Y->getType()->isIntOrIntVectorTy(BitWidth: 1))
6541 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(LHS: X, RHS: Y),
6542 Constant::getNullValue(Ty: X->getType()));
6543
6544 // If we have mismatched casts and zext has the nneg flag, we can
6545 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6546
6547 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 0));
6548 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(Val: ICmp.getOperand(i_nocapture: 1));
6549
6550 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6551 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6552
6553 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6554 IsSignedExt = true;
6555 else
6556 return nullptr;
6557 }
6558
6559 // Not an extension from the same type?
6560 Type *XTy = X->getType(), *YTy = Y->getType();
6561 if (XTy != YTy) {
6562 // One of the casts must have one use because we are creating a new cast.
6563 if (!ICmp.getOperand(i_nocapture: 0)->hasOneUse() && !ICmp.getOperand(i_nocapture: 1)->hasOneUse())
6564 return nullptr;
6565 // Extend the narrower operand to the type of the wider operand.
6566 CastInst::CastOps CastOpcode =
6567 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6568 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6569 X = Builder.CreateCast(Op: CastOpcode, V: X, DestTy: YTy);
6570 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6571 Y = Builder.CreateCast(Op: CastOpcode, V: Y, DestTy: XTy);
6572 else
6573 return nullptr;
6574 }
6575
6576 // (zext X) == (zext Y) --> X == Y
6577 // (sext X) == (sext Y) --> X == Y
6578 if (ICmp.isEquality())
6579 return new ICmpInst(ICmp.getPredicate(), X, Y);
6580
6581 // A signed comparison of sign extended values simplifies into a
6582 // signed comparison.
6583 if (IsSignedCmp && IsSignedExt)
6584 return new ICmpInst(ICmp.getPredicate(), X, Y);
6585
6586 // The other three cases all fold into an unsigned comparison.
6587 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6588 }
6589
6590 // Below here, we are only folding a compare with constant.
6591 auto *C = dyn_cast<Constant>(Val: ICmp.getOperand(i_nocapture: 1));
6592 if (!C)
6593 return nullptr;
6594
6595 // If a lossless truncate is possible...
6596 Type *SrcTy = CastOp0->getSrcTy();
6597 Constant *Res = getLosslessInvCast(C, InvCastTo: SrcTy, CastOp: CastOp0->getOpcode(), DL);
6598 if (Res) {
6599 if (ICmp.isEquality())
6600 return new ICmpInst(ICmp.getPredicate(), X, Res);
6601
6602 // A signed comparison of sign extended values simplifies into a
6603 // signed comparison.
6604 if (IsSignedExt && IsSignedCmp)
6605 return new ICmpInst(ICmp.getPredicate(), X, Res);
6606
6607 // The other three cases all fold into an unsigned comparison.
6608 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6609 }
6610
6611 // The re-extended constant changed, partly changed (in the case of a vector),
6612 // or could not be determined to be equal (in the case of a constant
6613 // expression), so the constant cannot be represented in the shorter type.
6614 // All the cases that fold to true or false will have already been handled
6615 // by simplifyICmpInst, so only deal with the tricky case.
6616 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(Val: C))
6617 return nullptr;
6618
6619 // Is source op positive?
6620 // icmp ult (sext X), C --> icmp sgt X, -1
6621 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6622 return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(Ty: SrcTy));
6623
6624 // Is source op negative?
6625 // icmp ugt (sext X), C --> icmp slt X, 0
6626 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6627 return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(Ty: SrcTy));
6628}
6629
6630/// Handle icmp (cast x), (cast or constant).
6631Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
6632 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6633 // icmp compares only pointer's value.
6634 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6635 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 0));
6636 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(Val: ICmp.getOperand(i_nocapture: 1));
6637 if (SimplifiedOp0 || SimplifiedOp1)
6638 return new ICmpInst(ICmp.getPredicate(),
6639 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(i_nocapture: 0),
6640 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(i_nocapture: 1));
6641
6642 auto *CastOp0 = dyn_cast<CastInst>(Val: ICmp.getOperand(i_nocapture: 0));
6643 Value *Op1 = ICmp.getOperand(i_nocapture: 1);
6644 if (!CastOp0)
6645 return nullptr;
6646 if (!isa<Constant>(Val: ICmp.getOperand(i_nocapture: 1)) && !isa<CastInst>(Val: ICmp.getOperand(i_nocapture: 1)))
6647 return nullptr;
6648
6649 Value *Op0Src = CastOp0->getOperand(i_nocapture: 0);
6650 Type *SrcTy = CastOp0->getSrcTy();
6651 Type *DestTy = CastOp0->getDestTy();
6652
6653 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6654 // integer type is the same size as the pointer type.
6655 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6656 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6657 unsigned IndexWidth = DL.getAddressSizeInBits(Ty: PtrTy);
6658 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6659 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6660 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6661 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6662 };
6663 if (isa<PtrToIntInst, PtrToAddrInst>(Val: CastOp0)) {
6664 bool HasPtrToInt = isa<PtrToIntInst>(Val: CastOp0);
6665 Value *NewOp1 = nullptr;
6666 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Val: Op1)) {
6667 NewOp1 = PtrToIntOp1->getOperand(i_nocapture: 0);
6668 HasPtrToInt = true;
6669 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Val: Op1)) {
6670 NewOp1 = PtrToAddrOp1->getOperand(i_nocapture: 0);
6671 } else if (auto *RHSC = dyn_cast<Constant>(Val: Op1)) {
6672 NewOp1 = ConstantExpr::getIntToPtr(C: RHSC, Ty: SrcTy);
6673 }
6674
6675 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6676 // check PtrWidth.
6677 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6678 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6679 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6680 }
6681
6682 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6683 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6684 CompatibleSizes(DestTy, SrcTy)) {
6685 Value *NewOp1 = nullptr;
6686 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Val: Op1)) {
6687 Value *IntSrc = IntToPtrOp1->getOperand(i_nocapture: 0);
6688 if (IntSrc->getType() == Op0Src->getType())
6689 NewOp1 = IntToPtrOp1->getOperand(i_nocapture: 0);
6690 } else if (auto *RHSC = dyn_cast<Constant>(Val: Op1)) {
6691 NewOp1 = ConstantFoldConstant(C: ConstantExpr::getPtrToInt(C: RHSC, Ty: SrcTy), DL);
6692 }
6693
6694 if (NewOp1)
6695 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6696 }
6697
6698 if (Instruction *R = foldICmpWithTrunc(ICmp))
6699 return R;
6700
6701 return foldICmpWithZextOrSext(ICmp);
6702}
6703
6704static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS,
6705 bool IsSigned) {
6706 switch (BinaryOp) {
6707 default:
6708 llvm_unreachable("Unsupported binary op");
6709 case Instruction::Add:
6710 case Instruction::Sub:
6711 return match(V: RHS, P: m_Zero());
6712 case Instruction::Mul:
6713 return !(RHS->getType()->isIntOrIntVectorTy(BitWidth: 1) && IsSigned) &&
6714 match(V: RHS, P: m_One());
6715 }
6716}
6717
6718OverflowResult
6719InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
6720 bool IsSigned, Value *LHS, Value *RHS,
6721 Instruction *CxtI) const {
6722 switch (BinaryOp) {
6723 default:
6724 llvm_unreachable("Unsupported binary op");
6725 case Instruction::Add:
6726 if (IsSigned)
6727 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6728 else
6729 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6730 case Instruction::Sub:
6731 if (IsSigned)
6732 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6733 else
6734 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6735 case Instruction::Mul:
6736 if (IsSigned)
6737 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6738 else
6739 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6740 }
6741}
6742
6743bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6744 bool IsSigned, Value *LHS,
6745 Value *RHS, Instruction &OrigI,
6746 Value *&Result,
6747 Constant *&Overflow) {
6748 if (OrigI.isCommutative() && isa<Constant>(Val: LHS) && !isa<Constant>(Val: RHS))
6749 std::swap(a&: LHS, b&: RHS);
6750
6751 // If the overflow check was an add followed by a compare, the insertion point
6752 // may be pointing to the compare. We want to insert the new instructions
6753 // before the add in case there are uses of the add between the add and the
6754 // compare.
6755 Builder.SetInsertPoint(&OrigI);
6756
6757 Type *OverflowTy = Type::getInt1Ty(C&: LHS->getContext());
6758 if (auto *LHSTy = dyn_cast<VectorType>(Val: LHS->getType()))
6759 OverflowTy = VectorType::get(ElementType: OverflowTy, EC: LHSTy->getElementCount());
6760
6761 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6762 Result = LHS;
6763 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6764 return true;
6765 }
6766
6767 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, CxtI: &OrigI)) {
6768 case OverflowResult::MayOverflow:
6769 return false;
6770 case OverflowResult::AlwaysOverflowsLow:
6771 case OverflowResult::AlwaysOverflowsHigh:
6772 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6773 Result->takeName(V: &OrigI);
6774 Overflow = ConstantInt::getTrue(Ty: OverflowTy);
6775 return true;
6776 case OverflowResult::NeverOverflows:
6777 Result = Builder.CreateBinOp(Opc: BinaryOp, LHS, RHS);
6778 Result->takeName(V: &OrigI);
6779 Overflow = ConstantInt::getFalse(Ty: OverflowTy);
6780 if (auto *Inst = dyn_cast<Instruction>(Val: Result)) {
6781 if (IsSigned)
6782 Inst->setHasNoSignedWrap();
6783 else
6784 Inst->setHasNoUnsignedWrap();
6785 }
6786 return true;
6787 }
6788
6789 llvm_unreachable("Unexpected overflow result");
6790}
6791
6792/// Recognize and process idiom involving test for unsigned
6793/// overflow.
6794///
6795/// The caller has matched a pattern of the form:
6796/// I = cmp u (add(zext A, zext B), V
6797/// I = cmp u (mul(zext A, zext B), V
6798/// The function checks if this is a test for overflow and if so replaces
6799/// addition/multiplication with call to the umul intrinsic or the canonical
6800/// form of uadd overflow.
6801///
6802/// \param I Compare instruction.
6803/// \param Val Result of add/mul instruction. It is one of the arguments of
6804/// the compare instruction. Must be of integer type.
6805/// \param OtherVal The other argument of compare instruction.
6806/// \returns Instruction which must replace the compare instruction, NULL if no
6807/// replacement required.
6808static Instruction *processUZExtIdiom(ICmpInst &I, Value *Val,
6809 const APInt *OtherVal,
6810 InstCombinerImpl &IC) {
6811 // Don't bother doing this transformation for pointers, don't do it for
6812 // vectors.
6813 if (!isa<IntegerType>(Val: Val->getType()))
6814 return nullptr;
6815
6816 auto *Instr = cast<Instruction>(Val);
6817 unsigned Opcode = Instr->getOpcode();
6818 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6819
6820 auto *LHS = cast<ZExtInst>(Val: Instr->getOperand(i: 0)),
6821 *RHS = cast<ZExtInst>(Val: Instr->getOperand(i: 1));
6822 Value *A = LHS->getOperand(i_nocapture: 0), *B = RHS->getOperand(i_nocapture: 0);
6823
6824 // Calculate type and width of the result produced by add/mul.with.overflow.
6825 Type *TyA = A->getType(), *TyB = B->getType();
6826 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6827 WidthB = TyB->getPrimitiveSizeInBits();
6828 unsigned ResultWidth;
6829 Type *ResultType;
6830 if (WidthB > WidthA) {
6831 ResultWidth = WidthB;
6832 ResultType = TyB;
6833 } else {
6834 ResultWidth = WidthA;
6835 ResultType = TyA;
6836 }
6837
6838 // In order to replace the original result with a narrower one, all uses must
6839 // ignore upper bits of the result. The number of used low bits must be not
6840 // greater than the width of add or mul.with.overflow.
6841 if (Val->hasNUsesOrMore(N: 2))
6842 for (User *U : Val->users()) {
6843 if (U == &I)
6844 continue;
6845 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6846 // Check if truncation ignores bits above ResultWidth.
6847 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6848 if (TruncWidth > ResultWidth)
6849 return nullptr;
6850 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6851 // Check if AND ignores bits above ResultWidth.
6852 if (BO->getOpcode() != Instruction::And)
6853 return nullptr;
6854 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1))) {
6855 const APInt &CVal = CI->getValue();
6856 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
6857 return nullptr;
6858 } else {
6859 // In this case we could have the operand of the binary operation
6860 // being defined in another block, and performing the replacement
6861 // could break the dominance relation.
6862 return nullptr;
6863 }
6864 } else {
6865 // Other uses prohibit this transformation.
6866 return nullptr;
6867 }
6868 }
6869
6870 // Recognize patterns
6871 switch (I.getPredicate()) {
6872 case ICmpInst::ICMP_UGT: {
6873 // Recognize pattern:
6874 // val = add/mul(zext A, zext B)
6875 // cmp ugt val, max
6876 APInt MaxVal = APInt::getMaxValue(numBits: ResultWidth);
6877 MaxVal = MaxVal.zext(width: OtherVal->getBitWidth());
6878 if (MaxVal.eq(RHS: *OtherVal))
6879 break; // Recognized
6880 return nullptr;
6881 }
6882
6883 case ICmpInst::ICMP_ULT: {
6884 // Recognize pattern:
6885 // val = add/mul(zext A, zext B)
6886 // cmp ult val, max + 1
6887 APInt MaxVal = APInt::getOneBitSet(numBits: OtherVal->getBitWidth(), BitNo: ResultWidth);
6888 if (MaxVal.eq(RHS: *OtherVal))
6889 break; // Recognized
6890 return nullptr;
6891 }
6892
6893 default:
6894 return nullptr;
6895 }
6896
6897 InstCombiner::BuilderTy &Builder = IC.Builder;
6898 Builder.SetInsertPoint(Instr);
6899
6900 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
6901 Value *ResultA = A, *ResultB = B;
6902 if (WidthA < ResultWidth)
6903 ResultA = Builder.CreateZExt(V: A, DestTy: ResultType);
6904 if (WidthB < ResultWidth)
6905 ResultB = Builder.CreateZExt(V: B, DestTy: ResultType);
6906
6907 Value *ArithResult;
6908 Value *OverflowCheck;
6909
6910 if (Opcode == Instruction::Add) {
6911 // Canonical add overflow check: add + compare
6912 ArithResult = Builder.CreateAdd(LHS: ResultA, RHS: ResultB, Name: "add");
6913 // Overflow if result < either operand (for unsigned add)
6914 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6915 OverflowCheck =
6916 Builder.CreateICmpUGE(LHS: ArithResult, RHS: ResultA, Name: "not.add.overflow");
6917 else
6918 OverflowCheck =
6919 Builder.CreateICmpULT(LHS: ArithResult, RHS: ResultA, Name: "add.overflow");
6920 } else {
6921 // For multiplication, the intrinsic is actually the canonical form
6922 Value *Call = Builder.CreateIntrinsic(ID: Intrinsic::umul_with_overflow,
6923 OverloadTypes: ResultType, Args: {ResultA, ResultB},
6924 /*FMFSource=*/nullptr, Name: "umul");
6925 ArithResult = Builder.CreateExtractValue(Agg: Call, Idxs: 0, Name: "umul.value");
6926 OverflowCheck = Builder.CreateExtractValue(Agg: Call, Idxs: 1, Name: "umul.overflow");
6927 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6928 OverflowCheck = Builder.CreateNot(V: OverflowCheck);
6929 }
6930
6931 IC.addToWorklist(I: Instr);
6932
6933 // Replace uses of the original add/mul result with the new arithmetic result
6934 if (Val->hasNUsesOrMore(N: 2)) {
6935 for (User *U : make_early_inc_range(Range: Val->users())) {
6936 if (U == &I)
6937 continue;
6938 if (TruncInst *TI = dyn_cast<TruncInst>(Val: U)) {
6939 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
6940 IC.replaceInstUsesWith(I&: *TI, V: ArithResult);
6941 else
6942 TI->setOperand(i_nocapture: 0, Val_nocapture: ArithResult);
6943 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: U)) {
6944 assert(BO->getOpcode() == Instruction::And);
6945 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
6946 ConstantInt *CI = cast<ConstantInt>(Val: BO->getOperand(i_nocapture: 1));
6947 APInt ShortMask = CI->getValue().trunc(width: ResultWidth);
6948 Value *ShortAnd = Builder.CreateAnd(LHS: ArithResult, RHS: ShortMask);
6949 Value *Zext = Builder.CreateZExt(V: ShortAnd, DestTy: BO->getType());
6950 IC.replaceInstUsesWith(I&: *BO, V: Zext);
6951 } else {
6952 llvm_unreachable("Unexpected Binary operation");
6953 }
6954 IC.addToWorklist(I: cast<Instruction>(Val: U));
6955 }
6956 }
6957
6958 return IC.replaceInstUsesWith(I, V: OverflowCheck);
6959}
6960
6961/// When performing a comparison against a constant, it is possible that not all
6962/// the bits in the LHS are demanded. This helper method computes the mask that
6963/// IS demanded.
6964static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
6965 const APInt *RHS;
6966 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APInt(Res&: RHS)))
6967 return APInt::getAllOnes(numBits: BitWidth);
6968
6969 // If this is a normal comparison, it demands all bits. If it is a sign bit
6970 // comparison, it only demands the sign bit.
6971 bool UnusedBit;
6972 if (isSignBitCheck(Pred: I.getPredicate(), RHS: *RHS, TrueIfSigned&: UnusedBit))
6973 return APInt::getSignMask(BitWidth);
6974
6975 switch (I.getPredicate()) {
6976 // For a UGT comparison, we don't care about any bits that
6977 // correspond to the trailing ones of the comparand. The value of these
6978 // bits doesn't impact the outcome of the comparison, because any value
6979 // greater than the RHS must differ in a bit higher than these due to carry.
6980 case ICmpInst::ICMP_UGT:
6981 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_one());
6982
6983 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6984 // Any value less than the RHS must differ in a higher bit because of carries.
6985 case ICmpInst::ICMP_ULT:
6986 return APInt::getBitsSetFrom(numBits: BitWidth, loBit: RHS->countr_zero());
6987
6988 default:
6989 return APInt::getAllOnes(numBits: BitWidth);
6990 }
6991}
6992
6993/// Check that one use is in the same block as the definition and all
6994/// other uses are in blocks dominated by a given block.
6995///
6996/// \param DI Definition
6997/// \param UI Use
6998/// \param DB Block that must dominate all uses of \p DI outside
6999/// the parent block
7000/// \return true when \p UI is the only use of \p DI in the parent block
7001/// and all other uses of \p DI are in blocks dominated by \p DB.
7002///
7003bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
7004 const Instruction *UI,
7005 const BasicBlock *DB) const {
7006 assert(DI && UI && "Instruction not defined\n");
7007 // Ignore incomplete definitions.
7008 if (!DI->getParent())
7009 return false;
7010 // DI and UI must be in the same block.
7011 if (DI->getParent() != UI->getParent())
7012 return false;
7013 // Protect from self-referencing blocks.
7014 if (DI->getParent() == DB)
7015 return false;
7016 for (const User *U : DI->users()) {
7017 auto *Usr = cast<Instruction>(Val: U);
7018 if (Usr != UI && !DT.dominates(A: DB, B: Usr->getParent()))
7019 return false;
7020 }
7021 return true;
7022}
7023
7024/// Return true when the instruction sequence within a block is select-cmp-br.
7025static bool isChainSelectCmpBranch(const SelectInst *SI) {
7026 const BasicBlock *BB = SI->getParent();
7027 if (!BB)
7028 return false;
7029 auto *BI = dyn_cast_or_null<CondBrInst>(Val: BB->getTerminator());
7030 if (!BI)
7031 return false;
7032 auto *IC = dyn_cast<ICmpInst>(Val: BI->getCondition());
7033 if (!IC || (IC->getOperand(i_nocapture: 0) != SI && IC->getOperand(i_nocapture: 1) != SI))
7034 return false;
7035 return true;
7036}
7037
7038/// True when a select result is replaced by one of its operands
7039/// in select-icmp sequence. This will eventually result in the elimination
7040/// of the select.
7041///
7042/// \param SI Select instruction
7043/// \param Icmp Compare instruction
7044/// \param SIOpd Operand that replaces the select
7045///
7046/// Notes:
7047/// - The replacement is global and requires dominator information
7048/// - The caller is responsible for the actual replacement
7049///
7050/// Example:
7051///
7052/// entry:
7053/// %4 = select i1 %3, %C* %0, %C* null
7054/// %5 = icmp eq %C* %4, null
7055/// br i1 %5, label %9, label %7
7056/// ...
7057/// ; <label>:7 ; preds = %entry
7058/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7059/// ...
7060///
7061/// can be transformed to
7062///
7063/// %5 = icmp eq %C* %0, null
7064/// %6 = select i1 %3, i1 %5, i1 true
7065/// br i1 %6, label %9, label %7
7066/// ...
7067/// ; <label>:7 ; preds = %entry
7068/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7069///
7070/// Similar when the first operand of the select is a constant or/and
7071/// the compare is for not equal rather than equal.
7072///
7073/// NOTE: The function is only called when the select and compare constants
7074/// are equal, the optimization can work only for EQ predicates. This is not a
7075/// major restriction since a NE compare should be 'normalized' to an equal
7076/// compare, which usually happens in the combiner and test case
7077/// select-cmp-br.ll checks for it.
7078bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
7079 const ICmpInst *Icmp,
7080 const unsigned SIOpd) {
7081 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7082 if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
7083 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(Idx: 1);
7084 // The check for the single predecessor is not the best that can be
7085 // done. But it protects efficiently against cases like when SI's
7086 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7087 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7088 // replaced can be reached on either path. So the uniqueness check
7089 // guarantees that the path all uses of SI (outside SI's parent) are on
7090 // is disjoint from all other paths out of SI. But that information
7091 // is more expensive to compute, and the trade-off here is in favor
7092 // of compile-time. It should also be noticed that we check for a single
7093 // predecessor and not only uniqueness. This to handle the situation when
7094 // Succ and Succ1 points to the same basic block.
7095 if (Succ->getSinglePredecessor() && dominatesAllUses(DI: SI, UI: Icmp, DB: Succ)) {
7096 NumSel++;
7097 SI->replaceUsesOutsideBlock(V: SI->getOperand(i_nocapture: SIOpd), BB: SI->getParent());
7098 return true;
7099 }
7100 }
7101 return false;
7102}
7103
7104/// Try to fold the comparison based on range information we can get by checking
7105/// whether bits are known to be zero or one in the inputs.
7106Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
7107 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7108 Type *Ty = Op0->getType();
7109 ICmpInst::Predicate Pred = I.getPredicate();
7110
7111 // Get scalar or pointer size.
7112 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7113 ? Ty->getScalarSizeInBits()
7114 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7115
7116 if (!BitWidth)
7117 return nullptr;
7118
7119 KnownBits Op0Known(BitWidth);
7120 KnownBits Op1Known(BitWidth);
7121
7122 {
7123 // Don't use dominating conditions when folding icmp using known bits. This
7124 // may convert signed into unsigned predicates in ways that other passes
7125 // (especially IndVarSimplify) may not be able to reliably undo.
7126 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(I: &I);
7127 if (SimplifyDemandedBits(I: &I, Op: 0, DemandedMask: getDemandedBitsLHSMask(I, BitWidth),
7128 Known&: Op0Known, Q))
7129 return &I;
7130
7131 if (SimplifyDemandedBits(I: &I, Op: 1, DemandedMask: APInt::getAllOnes(numBits: BitWidth), Known&: Op1Known, Q))
7132 return &I;
7133 }
7134
7135 // If an unsigned samesign comparison is not poison, both operands have the
7136 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7137 // values so the existing range folds can use that constraint.
7138 if (I.hasSameSign() && I.isUnsigned()) {
7139 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7140 if (To.isNegative() || To.isNonNegative())
7141 return;
7142 if (From.isNegative())
7143 To.makeNegative();
7144 else if (From.isNonNegative())
7145 To.makeNonNegative();
7146 };
7147 PropagateSignBit(Op0Known, Op1Known);
7148 PropagateSignBit(Op1Known, Op0Known);
7149 }
7150
7151 if (!isa<Constant>(Val: Op0) && Op0Known.isConstant())
7152 return new ICmpInst(
7153 Pred, ConstantExpr::getIntegerValue(Ty, V: Op0Known.getConstant()), Op1);
7154 if (!isa<Constant>(Val: Op1) && Op1Known.isConstant())
7155 return new ICmpInst(
7156 Pred, Op0, ConstantExpr::getIntegerValue(Ty, V: Op1Known.getConstant()));
7157
7158 if (std::optional<bool> Res = ICmpInst::compare(LHS: Op0Known, RHS: Op1Known, Pred))
7159 return replaceInstUsesWith(I, V: ConstantInt::getBool(Ty: I.getType(), V: *Res));
7160
7161 // Given the known and unknown bits, compute a range that the LHS could be
7162 // in. Compute the Min, Max and RHS values based on the known bits. For the
7163 // EQ and NE we use unsigned values.
7164 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7165 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7166 if (I.isSigned()) {
7167 Op0Min = Op0Known.getSignedMinValue();
7168 Op0Max = Op0Known.getSignedMaxValue();
7169 Op1Min = Op1Known.getSignedMinValue();
7170 Op1Max = Op1Known.getSignedMaxValue();
7171 } else {
7172 Op0Min = Op0Known.getMinValue();
7173 Op0Max = Op0Known.getMaxValue();
7174 Op1Min = Op1Known.getMinValue();
7175 Op1Max = Op1Known.getMaxValue();
7176 }
7177
7178 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7179 // min/max canonical compare with some other compare. That could lead to
7180 // conflict with select canonicalization and infinite looping.
7181 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7182 auto isMinMaxCmp = [&](Instruction &Cmp) {
7183 if (!Cmp.hasOneUse())
7184 return false;
7185 Value *A, *B;
7186 SelectPatternFlavor SPF = matchSelectPattern(V: Cmp.user_back(), LHS&: A, RHS&: B).Flavor;
7187 if (!SelectPatternResult::isMinOrMax(SPF))
7188 return false;
7189 return match(V: Op0, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value())) ||
7190 match(V: Op1, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value()));
7191 };
7192 if (!isMinMaxCmp(I)) {
7193 switch (Pred) {
7194 default:
7195 break;
7196 case ICmpInst::ICMP_ULT: {
7197 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7198 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7199 const APInt *CmpC;
7200 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7201 // A <u C -> A == C-1 if min(A)+1 == C
7202 if (*CmpC == Op0Min + 1)
7203 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7204 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7205 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7206 // exceeds the log2 of C.
7207 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7209 Constant::getNullValue(Ty: Op1->getType()));
7210 }
7211 break;
7212 }
7213 case ICmpInst::ICMP_UGT: {
7214 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7215 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7216 const APInt *CmpC;
7217 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7218 // A >u C -> A == C+1 if max(a)-1 == C
7219 if (*CmpC == Op0Max - 1)
7220 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7221 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7222 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7223 // exceeds the log2 of C.
7224 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7225 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7226 Constant::getNullValue(Ty: Op1->getType()));
7227 }
7228 break;
7229 }
7230 case ICmpInst::ICMP_SLT: {
7231 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7232 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7233 const APInt *CmpC;
7234 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7235 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7236 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7237 ConstantInt::get(Ty: Op1->getType(), V: *CmpC - 1));
7238 }
7239 break;
7240 }
7241 case ICmpInst::ICMP_SGT: {
7242 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7243 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7244 const APInt *CmpC;
7245 if (match(V: Op1, P: m_APInt(Res&: CmpC))) {
7246 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7248 ConstantInt::get(Ty: Op1->getType(), V: *CmpC + 1));
7249 }
7250 break;
7251 }
7252 }
7253 }
7254
7255 // Based on the range information we know about the LHS, see if we can
7256 // simplify this comparison. For example, (x&4) < 8 is always true.
7257 switch (Pred) {
7258 default:
7259 break;
7260 case ICmpInst::ICMP_EQ:
7261 case ICmpInst::ICMP_NE: {
7262 // If all bits are known zero except for one, then we know at most one bit
7263 // is set. If the comparison is against zero, then this is a check to see if
7264 // *that* bit is set.
7265 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7266 if (Op1Known.isZero()) {
7267 // If the LHS is an AND with the same constant, look through it.
7268 Value *LHS = nullptr;
7269 const APInt *LHSC;
7270 if (!match(V: Op0, P: m_And(L: m_Value(V&: LHS), R: m_APInt(Res&: LHSC))) ||
7271 *LHSC != Op0KnownZeroInverted)
7272 LHS = Op0;
7273
7274 Value *X;
7275 const APInt *C1;
7276 if (match(V: LHS, P: m_Shl(L: m_Power2(V&: C1), R: m_Value(V&: X)))) {
7277 Type *XTy = X->getType();
7278 unsigned Log2C1 = C1->countr_zero();
7279 APInt C2 = Op0KnownZeroInverted;
7280 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7281 if (C2Pow2.isPowerOf2()) {
7282 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7283 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7284 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7285 unsigned Log2C2 = C2Pow2.countr_zero();
7286 auto *CmpC = ConstantInt::get(Ty: XTy, V: Log2C2 - Log2C1);
7287 auto NewPred =
7288 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
7289 return new ICmpInst(NewPred, X, CmpC);
7290 }
7291 }
7292 }
7293
7294 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7295 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7296 (Op0Known & Op1Known) == Op0Known)
7297 return new ICmpInst(CmpInst::getInversePredicate(pred: Pred), Op0,
7298 ConstantInt::getNullValue(Ty: Op1->getType()));
7299 break;
7300 }
7301 case ICmpInst::ICMP_SGE:
7302 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7303 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7304 break;
7305 case ICmpInst::ICMP_SLE:
7306 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7307 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7308 break;
7309 case ICmpInst::ICMP_UGE:
7310 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7311 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7312 break;
7313 case ICmpInst::ICMP_ULE:
7314 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7315 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7316 break;
7317 }
7318
7319 // Turn a signed comparison into an unsigned one if both operands are known to
7320 // have the same sign. Set samesign if possible (except for equality
7321 // predicates).
7322 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7323 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7324 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7325 I.setPredicate(I.getUnsignedPredicate());
7326 I.setSameSign();
7327 return &I;
7328 }
7329
7330 return nullptr;
7331}
7332
7333/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7334/// then try to reduce patterns based on that limit.
7335Instruction *InstCombinerImpl::foldICmpUsingBoolRange(ICmpInst &I) {
7336 Value *X, *Y;
7337 CmpPredicate Pred;
7338
7339 // X must be 0 and bool must be true for "ULT":
7340 // X <u (zext i1 Y) --> (X == 0) & Y
7341 if (match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: X), R: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: Y))))) &&
7342 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULT)
7343 return BinaryOperator::CreateAnd(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7344
7345 // X must be 0 or bool must be true for "ULE":
7346 // X <=u (sext i1 Y) --> (X == 0) | Y
7347 if (match(V: &I, P: m_c_ICmp(Pred, L: m_Value(V&: X), R: m_OneUse(SubPattern: m_SExt(Op: m_Value(V&: Y))))) &&
7348 Y->getType()->isIntOrIntVectorTy(BitWidth: 1) && Pred == ICmpInst::ICMP_ULE)
7349 return BinaryOperator::CreateOr(V1: Builder.CreateIsNull(Arg: X), V2: Y);
7350
7351 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7352 CmpPredicate Pred1, Pred2;
7353 const APInt *C;
7354 Instruction *ExtI;
7355 if (match(V: &I, P: m_c_ICmp(Pred&: Pred1, L: m_Value(V&: X),
7356 R: m_CombineAnd(Ps: m_Instruction(I&: ExtI),
7357 Ps: m_ZExtOrSExt(Op: m_ICmp(Pred&: Pred2, L: m_Deferred(V: X),
7358 R: m_APInt(Res&: C)))))) &&
7359 ICmpInst::isEquality(P: Pred1) && ICmpInst::isEquality(P: Pred2)) {
7360 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7361 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(i: 0)->hasOneUse();
7362 auto CreateRangeCheck = [&] {
7363 Value *CmpV1 =
7364 Builder.CreateICmp(P: Pred1, LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
7365 Value *CmpV2 = Builder.CreateICmp(
7366 P: Pred1, LHS: X, RHS: ConstantInt::getSigned(Ty: X->getType(), V: IsSExt ? -1 : 1));
7367 return BinaryOperator::Create(
7368 Op: Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7369 S1: CmpV1, S2: CmpV2);
7370 };
7371 if (C->isZero()) {
7372 if (Pred2 == ICmpInst::ICMP_EQ) {
7373 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7374 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7375 return replaceInstUsesWith(
7376 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7377 } else if (!IsSExt || HasOneUse) {
7378 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7379 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7380 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7381 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7382 return CreateRangeCheck();
7383 }
7384 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7385 if (Pred2 == ICmpInst::ICMP_NE) {
7386 // icmp eq X, (zext (icmp ne X, 1)) --> false
7387 // icmp ne X, (zext (icmp ne X, 1)) --> true
7388 // icmp eq X, (sext (icmp ne X, -1)) --> false
7389 // icmp ne X, (sext (icmp ne X, -1)) --> true
7390 return replaceInstUsesWith(
7391 I, V: ConstantInt::getBool(Ty: I.getType(), V: Pred1 == ICmpInst::ICMP_NE));
7392 } else if (!IsSExt || HasOneUse) {
7393 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7394 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7395 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7396 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7397 return CreateRangeCheck();
7398 }
7399 } else {
7400 // when C != 0 && C != 1:
7401 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7402 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7403 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7404 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7405 // when C != 0 && C != -1:
7406 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7407 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7408 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7409 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7410 return ICmpInst::Create(
7411 Op: Instruction::ICmp, Pred: Pred1, S1: X,
7412 S2: ConstantInt::getSigned(Ty: X->getType(), V: Pred2 == ICmpInst::ICMP_NE
7413 ? (IsSExt ? -1 : 1)
7414 : 0));
7415 }
7416 }
7417
7418 return nullptr;
7419}
7420
7421/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7422/// it into the appropriate icmp lt or icmp gt instruction. This transform
7423/// allows them to be folded in visitICmpInst.
7424static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
7425 CmpPredicate Pred = I.getCmpPredicate();
7426 if (ICmpInst::isEquality(P: Pred) || !ICmpInst::isIntPredicate(P: Pred) ||
7427 InstCombiner::isCanonicalPredicate(Pred))
7428 return nullptr;
7429
7430 Value *Op0 = I.getOperand(i_nocapture: 0);
7431 Value *Op1 = I.getOperand(i_nocapture: 1);
7432 auto *Op1C = dyn_cast<Constant>(Val: Op1);
7433 if (!Op1C)
7434 return nullptr;
7435
7436 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: Op1C);
7437 if (!FlippedStrictness)
7438 return nullptr;
7439
7440 auto *NewCmp =
7441 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7442 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7443 return NewCmp;
7444}
7445
7446/// If we have a comparison with a non-canonical predicate, if we can update
7447/// all the users, invert the predicate and adjust all the users.
7448CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
7449 // Is the predicate already canonical?
7450 CmpInst::Predicate Pred = I.getPredicate();
7451 if (InstCombiner::isCanonicalPredicate(Pred))
7452 return nullptr;
7453
7454 // Can all users be adjusted to predicate inversion?
7455 if (!InstCombiner::canFreelyInvertAllUsersOf(V: &I, /*IgnoredUser=*/nullptr))
7456 return nullptr;
7457
7458 // Ok, we can canonicalize comparison!
7459 // Let's first invert the comparison's predicate.
7460 I.setPredicate(CmpInst::getInversePredicate(pred: Pred));
7461 I.setName(I.getName() + ".not");
7462
7463 // And, adapt users.
7464 freelyInvertAllUsersOf(V: &I);
7465
7466 return &I;
7467}
7468
7469/// Integer compare with boolean values can always be turned into bitwise ops.
7470static Instruction *canonicalizeICmpBool(ICmpInst &I,
7471 InstCombiner::BuilderTy &Builder) {
7472 Value *A = I.getOperand(i_nocapture: 0), *B = I.getOperand(i_nocapture: 1);
7473 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7474
7475 // A boolean compared to true/false can be simplified to Op0/true/false in
7476 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7477 // Cases not handled by InstSimplify are always 'not' of Op0.
7478 if (match(V: B, P: m_Zero())) {
7479 switch (I.getPredicate()) {
7480 case CmpInst::ICMP_EQ: // A == 0 -> !A
7481 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7482 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7483 return BinaryOperator::CreateNot(Op: A);
7484 default:
7485 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7486 }
7487 } else if (match(V: B, P: m_One())) {
7488 switch (I.getPredicate()) {
7489 case CmpInst::ICMP_NE: // A != 1 -> !A
7490 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7491 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7492 return BinaryOperator::CreateNot(Op: A);
7493 default:
7494 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7495 }
7496 }
7497
7498 switch (I.getPredicate()) {
7499 default:
7500 llvm_unreachable("Invalid icmp instruction!");
7501 case ICmpInst::ICMP_EQ:
7502 // icmp eq i1 A, B -> ~(A ^ B)
7503 return BinaryOperator::CreateNot(Op: Builder.CreateXor(LHS: A, RHS: B));
7504
7505 case ICmpInst::ICMP_NE:
7506 // icmp ne i1 A, B -> A ^ B
7507 return BinaryOperator::CreateXor(V1: A, V2: B);
7508
7509 case ICmpInst::ICMP_UGT:
7510 // icmp ugt -> icmp ult
7511 std::swap(a&: A, b&: B);
7512 [[fallthrough]];
7513 case ICmpInst::ICMP_ULT:
7514 // icmp ult i1 A, B -> ~A & B
7515 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: A), V2: B);
7516
7517 case ICmpInst::ICMP_SGT:
7518 // icmp sgt -> icmp slt
7519 std::swap(a&: A, b&: B);
7520 [[fallthrough]];
7521 case ICmpInst::ICMP_SLT:
7522 // icmp slt i1 A, B -> A & ~B
7523 return BinaryOperator::CreateAnd(V1: Builder.CreateNot(V: B), V2: A);
7524
7525 case ICmpInst::ICMP_UGE:
7526 // icmp uge -> icmp ule
7527 std::swap(a&: A, b&: B);
7528 [[fallthrough]];
7529 case ICmpInst::ICMP_ULE:
7530 // icmp ule i1 A, B -> ~A | B
7531 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: A), V2: B);
7532
7533 case ICmpInst::ICMP_SGE:
7534 // icmp sge -> icmp sle
7535 std::swap(a&: A, b&: B);
7536 [[fallthrough]];
7537 case ICmpInst::ICMP_SLE:
7538 // icmp sle i1 A, B -> A | ~B
7539 return BinaryOperator::CreateOr(V1: Builder.CreateNot(V: B), V2: A);
7540 }
7541}
7542
7543// Transform pattern like:
7544// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7545// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7546// Into:
7547// (X l>> Y) != 0
7548// (X l>> Y) == 0
7549static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
7550 InstCombiner::BuilderTy &Builder) {
7551 CmpPredicate Pred, NewPred;
7552 Value *X, *Y;
7553 if (match(V: &Cmp,
7554 P: m_c_ICmp(Pred, L: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_Value(V&: Y))), R: m_Value(V&: X)))) {
7555 switch (Pred) {
7556 case ICmpInst::ICMP_ULE:
7557 NewPred = ICmpInst::ICMP_NE;
7558 break;
7559 case ICmpInst::ICMP_UGT:
7560 NewPred = ICmpInst::ICMP_EQ;
7561 break;
7562 default:
7563 return nullptr;
7564 }
7565 } else if (match(V: &Cmp, P: m_c_ICmp(Pred,
7566 L: m_OneUse(SubPattern: m_CombineOr(
7567 Ps: m_Not(V: m_Shl(L: m_AllOnes(), R: m_Value(V&: Y))),
7568 Ps: m_Add(L: m_Shl(L: m_One(), R: m_Value(V&: Y)),
7569 R: m_AllOnes()))),
7570 R: m_Value(V&: X)))) {
7571 // The variant with 'add' is not canonical, (the variant with 'not' is)
7572 // we only get it because it has extra uses, and can't be canonicalized,
7573
7574 switch (Pred) {
7575 case ICmpInst::ICMP_ULT:
7576 NewPred = ICmpInst::ICMP_NE;
7577 break;
7578 case ICmpInst::ICMP_UGE:
7579 NewPred = ICmpInst::ICMP_EQ;
7580 break;
7581 default:
7582 return nullptr;
7583 }
7584 } else
7585 return nullptr;
7586
7587 Value *NewX = Builder.CreateLShr(LHS: X, RHS: Y, Name: X->getName() + ".highbits");
7588 Constant *Zero = Constant::getNullValue(Ty: NewX->getType());
7589 return CmpInst::Create(Op: Instruction::ICmp, Pred: NewPred, S1: NewX, S2: Zero);
7590}
7591
7592static Instruction *foldVectorCmp(CmpInst &Cmp,
7593 InstCombiner::BuilderTy &Builder) {
7594 const CmpInst::Predicate Pred = Cmp.getPredicate();
7595 Value *LHS = Cmp.getOperand(i_nocapture: 0), *RHS = Cmp.getOperand(i_nocapture: 1);
7596 Value *V1, *V2;
7597
7598 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7599 Value *V = Builder.CreateCmp(Pred, LHS: X, RHS: Y, Name: Cmp.getName());
7600 if (auto *I = dyn_cast<Instruction>(Val: V))
7601 I->copyIRFlags(V: &Cmp);
7602 Module *M = Cmp.getModule();
7603 Function *F = Intrinsic::getOrInsertDeclaration(
7604 M, id: Intrinsic::vector_reverse, OverloadTys: V->getType());
7605 return CallInst::Create(Func: F, Args: V);
7606 };
7607
7608 if (match(V: LHS, P: m_VecReverse(Op0: m_Value(V&: V1)))) {
7609 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7610 if (match(V: RHS, P: m_VecReverse(Op0: m_Value(V&: V2))) &&
7611 (LHS->hasOneUse() || RHS->hasOneUse()))
7612 return createCmpReverse(Pred, V1, V2);
7613
7614 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7615 if (LHS->hasOneUse() && isSplatValue(V: RHS))
7616 return createCmpReverse(Pred, V1, RHS);
7617 }
7618 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7619 else if (isSplatValue(V: LHS) && match(V: RHS, P: m_OneUse(SubPattern: m_VecReverse(Op0: m_Value(V&: V2)))))
7620 return createCmpReverse(Pred, LHS, V2);
7621
7622 ArrayRef<int> M;
7623 if (!match(V: LHS, P: m_Shuffle(v1: m_Value(V&: V1), v2: m_Undef(), mask: m_Mask(M))))
7624 return nullptr;
7625
7626 // If both arguments of the cmp are shuffles that use the same mask and
7627 // shuffle within a single vector, move the shuffle after the cmp:
7628 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7629 Type *V1Ty = V1->getType();
7630 if (match(V: RHS, P: m_Shuffle(v1: m_Value(V&: V2), v2: m_Undef(), mask: m_SpecificMask(M))) &&
7631 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7632 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: V2);
7633 return new ShuffleVectorInst(NewCmp, M);
7634 }
7635
7636 // Try to canonicalize compare with splatted operand and splat constant.
7637 // TODO: We could generalize this for more than splats. See/use the code in
7638 // InstCombiner::foldVectorBinop().
7639 Constant *C;
7640 if (!LHS->hasOneUse() || !match(V: RHS, P: m_Constant(C)))
7641 return nullptr;
7642
7643 // Length-changing splats are ok, so adjust the constants as needed:
7644 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7645 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7646 int MaskSplatIndex;
7647 if (ScalarC && match(Mask: M, P: m_SplatOrPoisonMask(MaskSplatIndex))) {
7648 // We allow poison in matching, but this transform removes it for safety.
7649 // Demanded elements analysis should be able to recover some/all of that.
7650 C = ConstantVector::getSplat(EC: cast<VectorType>(Val: V1Ty)->getElementCount(),
7651 Elt: ScalarC);
7652 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7653 Value *NewCmp = Builder.CreateCmp(Pred, LHS: V1, RHS: C);
7654 return new ShuffleVectorInst(NewCmp, NewM);
7655 }
7656
7657 return nullptr;
7658}
7659
7660// extract(uadd.with.overflow(A, B), 0) ult A
7661// -> extract(uadd.with.overflow(A, B), 1)
7662static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
7663 CmpInst::Predicate Pred = I.getPredicate();
7664 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7665
7666 Value *UAddOv;
7667 Value *A, *B;
7668 auto UAddOvResultPat = m_ExtractValue<0>(
7669 V: m_Intrinsic<Intrinsic::uadd_with_overflow>(Ops: m_Value(V&: A), Ops: m_Value(V&: B)));
7670 if (match(V: Op0, P: UAddOvResultPat) &&
7671 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7672 (Pred == ICmpInst::ICMP_EQ && match(V: Op1, P: m_ZeroInt()) &&
7673 (match(V: A, P: m_One()) || match(V: B, P: m_One()))) ||
7674 (Pred == ICmpInst::ICMP_NE && match(V: Op1, P: m_AllOnes()) &&
7675 (match(V: A, P: m_AllOnes()) || match(V: B, P: m_AllOnes())))))
7676 // extract(uadd.with.overflow(A, B), 0) < A
7677 // extract(uadd.with.overflow(A, 1), 0) == 0
7678 // extract(uadd.with.overflow(A, -1), 0) != -1
7679 UAddOv = cast<ExtractValueInst>(Val: Op0)->getAggregateOperand();
7680 else if (match(V: Op1, P: UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7681 (Op0 == A || Op0 == B))
7682 // A > extract(uadd.with.overflow(A, B), 0)
7683 UAddOv = cast<ExtractValueInst>(Val: Op1)->getAggregateOperand();
7684 else
7685 return nullptr;
7686
7687 return ExtractValueInst::Create(Agg: UAddOv, Idxs: 1);
7688}
7689
7690static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
7691 if (!I.getOperand(i_nocapture: 0)->getType()->isPointerTy() ||
7692 NullPointerIsDefined(
7693 F: I.getParent()->getParent(),
7694 AS: I.getOperand(i_nocapture: 0)->getType()->getPointerAddressSpace())) {
7695 return nullptr;
7696 }
7697 Instruction *Op;
7698 if (match(V: I.getOperand(i_nocapture: 0), P: m_Instruction(I&: Op)) &&
7699 match(V: I.getOperand(i_nocapture: 1), P: m_Zero()) &&
7700 Op->isLaunderOrStripInvariantGroup()) {
7701 return ICmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7702 S1: Op->getOperand(i: 0), S2: I.getOperand(i_nocapture: 1));
7703 }
7704 return nullptr;
7705}
7706
7707static Instruction *foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL,
7708 IRBuilderBase &Builder) {
7709 if (!ICmpInst::isEquality(P: I.getPredicate()))
7710 return nullptr;
7711
7712 // The caller puts constants after non-constants.
7713 Value *Op = I.getOperand(i_nocapture: 0);
7714 Value *Const = I.getOperand(i_nocapture: 1);
7715
7716 // For Cond an equality condition, fold
7717 //
7718 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7719 // icmp (eq|ne) Op, (Zero|AllOnes)
7720 //
7721 // with a bitcast.
7722 Value *Vec;
7723 if ((match(V: Const, P: m_ZeroInt()) &&
7724 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_or>(
7725 Ops: m_Value(V&: Vec))))) ||
7726 (match(V: Const, P: m_AllOnes()) &&
7727 match(V: Op, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::vector_reduce_and>(
7728 Ops: m_Value(V&: Vec)))))) {
7729 auto *VecTy = dyn_cast<FixedVectorType>(Val: Vec->getType());
7730 if (!VecTy)
7731 return nullptr;
7732 Type *VecEltTy = VecTy->getElementType();
7733 unsigned ScalarBW =
7734 DL.getTypeSizeInBits(Ty: VecEltTy) * VecTy->getNumElements();
7735 if (!DL.fitsInLegalInteger(Width: ScalarBW))
7736 return nullptr;
7737 Type *ScalarTy = IntegerType::get(C&: I.getContext(), NumBits: ScalarBW);
7738 Value *NewConst = match(V: Const, P: m_ZeroInt())
7739 ? ConstantInt::get(Ty: ScalarTy, V: 0)
7740 : ConstantInt::getAllOnesValue(Ty: ScalarTy);
7741 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(),
7742 S1: Builder.CreateBitCast(V: Vec, DestTy: ScalarTy), S2: NewConst);
7743 }
7744 return nullptr;
7745}
7746
7747/// This function folds patterns produced by lowering of reduce idioms, such as
7748/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7749/// attempts to generate fewer number of scalar comparisons instead of vector
7750/// comparisons when possible.
7751static Instruction *foldReductionIdiom(ICmpInst &I,
7752 InstCombiner::BuilderTy &Builder,
7753 const DataLayout &DL) {
7754 if (I.getType()->isVectorTy())
7755 return nullptr;
7756 CmpPredicate OuterPred, InnerPred;
7757 Value *LHS, *RHS;
7758
7759 // Match lowering of @llvm.vector.reduce.and. Turn
7760 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7761 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7762 /// %res = icmp <pred> i8 %scalar_ne, 0
7763 ///
7764 /// into
7765 ///
7766 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7767 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7768 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7769 ///
7770 /// for <pred> in {ne, eq}.
7771 if (!match(V: &I, P: m_ICmp(Pred&: OuterPred,
7772 L: m_OneUse(SubPattern: m_BitCast(Op: m_OneUse(
7773 SubPattern: m_ICmp(Pred&: InnerPred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))),
7774 R: m_Zero())))
7775 return nullptr;
7776 auto *LHSTy = dyn_cast<FixedVectorType>(Val: LHS->getType());
7777 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7778 return nullptr;
7779 unsigned NumBits =
7780 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7781 // TODO: Relax this to "not wider than max legal integer type"?
7782 if (!DL.isLegalInteger(Width: NumBits))
7783 return nullptr;
7784
7785 if (ICmpInst::isEquality(P: OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7786 auto *ScalarTy = Builder.getIntNTy(N: NumBits);
7787 LHS = Builder.CreateBitCast(V: LHS, DestTy: ScalarTy, Name: LHS->getName() + ".scalar");
7788 RHS = Builder.CreateBitCast(V: RHS, DestTy: ScalarTy, Name: RHS->getName() + ".scalar");
7789 return ICmpInst::Create(Op: Instruction::ICmp, Pred: OuterPred, S1: LHS, S2: RHS,
7790 Name: I.getName());
7791 }
7792
7793 return nullptr;
7794}
7795
7796// This helper will be called with icmp operands in both orders.
7797Instruction *InstCombinerImpl::foldICmpCommutative(CmpPredicate Pred,
7798 Value *Op0, Value *Op1,
7799 ICmpInst &CxtI) {
7800 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7801 if (auto *GEP = dyn_cast<GEPOperator>(Val: Op0))
7802 if (Instruction *NI = foldGEPICmp(GEPLHS: GEP, RHS: Op1, Cond: Pred, I&: CxtI))
7803 return NI;
7804
7805 if (auto *SI = dyn_cast<SelectInst>(Val: Op0))
7806 if (Instruction *NI = foldSelectICmp(Pred, SI, RHS: Op1, I: CxtI))
7807 return NI;
7808
7809 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Val: Op0)) {
7810 if (Instruction *Res = foldICmpWithMinMax(I&: CxtI, MinMax, Z: Op1, Pred))
7811 return Res;
7812
7813 if (Instruction *Res = foldICmpWithClamp(I&: CxtI, X: Op1, Min: MinMax))
7814 return Res;
7815 }
7816
7817 {
7818 Value *X;
7819 const APInt *C;
7820 // icmp X+Cst, X
7821 if (match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C))) && Op1 == X)
7822 return foldICmpAddOpConst(X, C: *C, Pred);
7823 }
7824
7825 // abs(X) >= X --> true
7826 // abs(X) u<= X --> true
7827 // abs(X) < X --> false
7828 // abs(X) u> X --> false
7829 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7830 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7831 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7832 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7833 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7834 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7835 {
7836 Value *X;
7837 Constant *C;
7838 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Ops: m_Value(V&: X), Ops: m_Constant(C))) &&
7839 match(V: Op1, P: m_Specific(V: X))) {
7840 Value *NullValue = Constant::getNullValue(Ty: X->getType());
7841 Value *AllOnesValue = Constant::getAllOnesValue(Ty: X->getType());
7842 const APInt SMin =
7843 APInt::getSignedMinValue(numBits: X->getType()->getScalarSizeInBits());
7844 bool IsIntMinPosion = C->isAllOnesValue();
7845 switch (Pred) {
7846 case CmpInst::ICMP_ULE:
7847 case CmpInst::ICMP_SGE:
7848 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getTrue(Ty: CxtI.getType()));
7849 case CmpInst::ICMP_UGT:
7850 case CmpInst::ICMP_SLT:
7851 return replaceInstUsesWith(I&: CxtI, V: ConstantInt::getFalse(Ty: CxtI.getType()));
7852 case CmpInst::ICMP_UGE:
7853 case CmpInst::ICMP_SLE:
7854 case CmpInst::ICMP_EQ: {
7855 return replaceInstUsesWith(
7856 I&: CxtI, V: IsIntMinPosion
7857 ? Builder.CreateICmpSGT(LHS: X, RHS: AllOnesValue)
7858 : Builder.CreateICmpULT(
7859 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin + 1)));
7860 }
7861 case CmpInst::ICMP_ULT:
7862 case CmpInst::ICMP_SGT:
7863 case CmpInst::ICMP_NE: {
7864 return replaceInstUsesWith(
7865 I&: CxtI, V: IsIntMinPosion
7866 ? Builder.CreateICmpSLT(LHS: X, RHS: NullValue)
7867 : Builder.CreateICmpUGT(
7868 LHS: X, RHS: ConstantInt::get(Ty: X->getType(), V: SMin)));
7869 }
7870 default:
7871 llvm_unreachable("Invalid predicate!");
7872 }
7873 }
7874 }
7875
7876 const SimplifyQuery Q = SQ.getWithInstruction(I: &CxtI);
7877 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, IC&: *this))
7878 return replaceInstUsesWith(I&: CxtI, V);
7879
7880 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7881 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(RHS: 1); };
7882 {
7883 if (match(V: Op0, P: m_UDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7884 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7885 Constant::getNullValue(Ty: Op1->getType()));
7886 }
7887
7888 if (!ICmpInst::isUnsigned(Pred) &&
7889 match(V: Op0, P: m_SDiv(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckUGT1)))) {
7890 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7891 Constant::getNullValue(Ty: Op1->getType()));
7892 }
7893 }
7894
7895 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7896 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7897 {
7898 if (match(V: Op0, P: m_LShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7899 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7900 Constant::getNullValue(Ty: Op1->getType()));
7901 }
7902
7903 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7904 match(V: Op0, P: m_AShr(L: m_Specific(V: Op1), R: m_CheckedInt(CheckFn: CheckNE0)))) {
7905 return new ICmpInst(ICmpInst::getSwappedPredicate(pred: Pred), Op1,
7906 Constant::getNullValue(Ty: Op1->getType()));
7907 }
7908 }
7909
7910 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7911 // -> icmp X, (add nsw/nuw Y, K >> L)
7912 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7913 Value *X;
7914 uint64_t ShAmt;
7915 if (match(V: Op0, P: m_NUWShl(L: m_Value(V&: X), R: m_ConstantInt(V&: ShAmt))) &&
7916 !CxtI.isSigned()) {
7917 if (ShAmt >= X->getType()->getScalarSizeInBits())
7918 return nullptr;
7919 if (canEvaluateShifted(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7920 Semantics: ShiftSemantics::Unsigned, CxtI: &CxtI)) {
7921 Value *NewOp1 = getShiftedValue(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7922 Semantics: ShiftSemantics::Unsigned);
7923 return new ICmpInst(Pred, X, NewOp1);
7924 }
7925 }
7926
7927 if (match(V: Op0, P: m_NSWShl(L: m_Value(V&: X), R: m_ConstantInt(V&: ShAmt))) &&
7928 !CxtI.isUnsigned()) {
7929 if (ShAmt >= X->getType()->getScalarSizeInBits())
7930 return nullptr;
7931 if (canEvaluateShifted(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7932 Semantics: ShiftSemantics::Signed, CxtI: &CxtI)) {
7933 Value *NewOp1 = getShiftedValue(V: Op1, NumBits: ShAmt, /*IsLeftShift=*/false,
7934 Semantics: ShiftSemantics::Signed);
7935 return new ICmpInst(Pred, X, NewOp1);
7936 }
7937 }
7938 return nullptr;
7939}
7940
7941Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
7942 bool Changed = false;
7943 const SimplifyQuery Q = SQ.getWithInstruction(I: &I);
7944 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
7945 unsigned Op0Cplxity = getComplexity(V: Op0);
7946 unsigned Op1Cplxity = getComplexity(V: Op1);
7947
7948 /// Orders the operands of the compare so that they are listed from most
7949 /// complex to least complex. This puts constants before unary operators,
7950 /// before binary operators.
7951 if (Op0Cplxity < Op1Cplxity) {
7952 I.swapOperands();
7953 std::swap(a&: Op0, b&: Op1);
7954 Changed = true;
7955 }
7956
7957 if (Value *V = simplifyICmpInst(Pred: I.getCmpPredicate(), LHS: Op0, RHS: Op1, Q))
7958 return replaceInstUsesWith(I, V);
7959
7960 // Comparing -val or val with non-zero is the same as just comparing val
7961 // ie, abs(val) != 0 -> val != 0
7962 if (I.getPredicate() == ICmpInst::ICMP_NE && match(V: Op1, P: m_Zero())) {
7963 Value *Cond, *SelectTrue, *SelectFalse;
7964 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: SelectTrue),
7965 R: m_Value(V&: SelectFalse)))) {
7966 if (Value *V = dyn_castNegVal(V: SelectTrue)) {
7967 if (V == SelectFalse)
7968 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7969 } else if (Value *V = dyn_castNegVal(V: SelectFalse)) {
7970 if (V == SelectTrue)
7971 return CmpInst::Create(Op: Instruction::ICmp, Pred: I.getPredicate(), S1: V, S2: Op1);
7972 }
7973 }
7974 }
7975
7976 if (Instruction *Res = foldICmpTruncWithTruncOrExt(Cmp&: I, Q))
7977 return Res;
7978
7979 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
7980 if (Instruction *Res = canonicalizeICmpBool(I, Builder))
7981 return Res;
7982
7983 if (Instruction *Res = canonicalizeCmpWithConstant(I))
7984 return Res;
7985
7986 if (Instruction *Res = canonicalizeICmpPredicate(I))
7987 return Res;
7988
7989 if (Instruction *Res = foldICmpWithConstant(Cmp&: I))
7990 return Res;
7991
7992 if (Instruction *Res = foldICmpWithDominatingICmp(Cmp&: I))
7993 return Res;
7994
7995 if (Instruction *Res = foldICmpUsingBoolRange(I))
7996 return Res;
7997
7998 if (Instruction *Res = foldICmpUsingKnownBits(I))
7999 return Res;
8000
8001 if (Instruction *Res = foldIsMultipleOfAPowerOfTwo(Cmp&: I))
8002 return Res;
8003
8004 // Test if the ICmpInst instruction is used exclusively by a select as
8005 // part of a minimum or maximum operation. If so, refrain from doing
8006 // any other folding. This helps out other analyses which understand
8007 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8008 // and CodeGen. And in this case, at least one of the comparison
8009 // operands has at least one user besides the compare (the select),
8010 // which would often largely negate the benefit of folding anyway.
8011 //
8012 // Do the same for the other patterns recognized by matchSelectPattern.
8013 if (I.hasOneUse())
8014 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
8015 Value *A, *B;
8016 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
8017 if (SPR.Flavor != SPF_UNKNOWN)
8018 return nullptr;
8019 }
8020
8021 // Do this after checking for min/max to prevent infinite looping.
8022 if (Instruction *Res = foldICmpWithZero(Cmp&: I))
8023 return Res;
8024
8025 Value *X;
8026 const APInt *C;
8027 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8028 match(V: Op0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C))) &&
8029 match(V: Op1, P: m_Not(V: m_Specific(V: X)))) {
8030 if (C->isNonNegative())
8031 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8032 Constant::getNullValue(Ty: X->getType()));
8033 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8034 ConstantInt::get(Ty: X->getType(), V: ~*C));
8035 }
8036
8037 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8038 match(V: Op0, P: m_UMax(Op0: m_Value(V&: X), Op1: m_APInt(Res&: C))) &&
8039 match(V: Op1, P: m_Not(V: m_Specific(V: X)))) {
8040 if (C->isNonNegative())
8041 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8042 Constant::getAllOnesValue(Ty: X->getType()));
8043 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8044 ConstantInt::get(Ty: X->getType(), V: ~*C));
8045 }
8046
8047 // FIXME: We only do this after checking for min/max to prevent infinite
8048 // looping caused by a reverse canonicalization of these patterns for min/max.
8049 // FIXME: The organization of folds is a mess. These would naturally go into
8050 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8051 // down here after the min/max restriction.
8052 ICmpInst::Predicate Pred = I.getPredicate();
8053 if (match(V: Op1, P: m_APInt(Res&: C))) {
8054 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8055 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8056 Constant *Zero = Constant::getNullValue(Ty: Op0->getType());
8057 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8058 }
8059
8060 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8061 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8062 Constant *AllOnes = Constant::getAllOnesValue(Ty: Op0->getType());
8063 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8064 }
8065 }
8066
8067 // The folds in here may rely on wrapping flags and special constants, so
8068 // they can break up min/max idioms in some cases but not seemingly similar
8069 // patterns.
8070 // FIXME: It may be possible to enhance select folding to make this
8071 // unnecessary. It may also be moot if we canonicalize to min/max
8072 // intrinsics.
8073 if (Instruction *Res = foldICmpBinOp(I, SQ: Q))
8074 return Res;
8075
8076 if (Instruction *Res = foldICmpInstWithConstant(Cmp&: I))
8077 return Res;
8078
8079 // Try to match comparison as a sign bit test. Intentionally do this after
8080 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8081 if (Instruction *New = foldSignBitTest(I))
8082 return New;
8083
8084 if (auto *PN = dyn_cast<PHINode>(Val: Op0))
8085 if (Instruction *NV = foldOpIntoPhi(I, PN))
8086 return NV;
8087 if (auto *PN = dyn_cast<PHINode>(Val: Op1))
8088 if (Instruction *NV = foldOpIntoPhi(I, PN))
8089 return NV;
8090
8091 if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
8092 return Res;
8093
8094 if (Instruction *Res = foldICmpCommutative(Pred: I.getCmpPredicate(), Op0, Op1, CxtI&: I))
8095 return Res;
8096 if (Instruction *Res =
8097 foldICmpCommutative(Pred: I.getSwappedCmpPredicate(), Op0: Op1, Op1: Op0, CxtI&: I))
8098 return Res;
8099
8100 if (I.isCommutative()) {
8101 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
8102 replaceOperand(I, OpNum: 0, V: Pair->first);
8103 replaceOperand(I, OpNum: 1, V: Pair->second);
8104 return &I;
8105 }
8106 }
8107
8108 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8109 // when all select arms are constants, via truth table.
8110 if (Instruction *R = foldCmpSelectOfConstants(I))
8111 return R;
8112
8113 // In case of a comparison with two select instructions having the same
8114 // condition, check whether one of the resulting branches can be simplified.
8115 // If so, just compare the other branch and select the appropriate result.
8116 // For example:
8117 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8118 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8119 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8120 // The icmp will result false for the false value of selects and the result
8121 // will depend upon the comparison of true values of selects if %cmp is
8122 // true. Thus, transform this into:
8123 // %cmp = icmp slt i32 %y, %z
8124 // %sel = select i1 %cond, i1 %cmp, i1 false
8125 // This handles similar cases to transform.
8126 {
8127 Value *Cond, *A, *B, *C, *D;
8128 if (match(V: Op0, P: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: A), R: m_Value(V&: B))) &&
8129 match(V: Op1, P: m_Select(C: m_Specific(V: Cond), L: m_Value(V&: C), R: m_Value(V&: D))) &&
8130 (Op0->hasOneUse() || Op1->hasOneUse())) {
8131 // Check whether comparison of TrueValues can be simplified
8132 if (Value *Res = simplifyICmpInst(Pred, LHS: A, RHS: C, Q: SQ)) {
8133 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: B, RHS: D);
8134 return SelectInst::Create(C: Cond, S1: Res, S2: NewICMP, /*NameStr=*/"",
8135 /*InsertBefore=*/nullptr,
8136 MDFrom: cast<Instruction>(Val: Op0));
8137 }
8138 // Check whether comparison of FalseValues can be simplified
8139 if (Value *Res = simplifyICmpInst(Pred, LHS: B, RHS: D, Q: SQ)) {
8140 Value *NewICMP = Builder.CreateICmp(P: Pred, LHS: A, RHS: C);
8141 return SelectInst::Create(C: Cond, S1: NewICMP, S2: Res, /*NameStr=*/"",
8142 /*InsertBefore=*/nullptr,
8143 MDFrom: cast<Instruction>(Val: Op0));
8144 }
8145 }
8146 }
8147
8148 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8149 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8150 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8151 {
8152 Value *A, *B;
8153 CmpPredicate CmpPred;
8154 if (match(V: &I, P: m_c_ICmp(Pred&: CmpPred, L: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)),
8155 R: m_c_Add(L: m_Deferred(V: A), R: m_Deferred(V: B))))) {
8156 auto *I0 = cast<OverflowingBinaryOperator>(Val: Op0);
8157 auto *I1 = cast<OverflowingBinaryOperator>(Val: Op1);
8158 bool I0NUW = I0->hasNoUnsignedWrap();
8159 bool I1NUW = I1->hasNoUnsignedWrap();
8160 bool I0NSW = I0->hasNoSignedWrap();
8161 bool I1NSW = I1->hasNoSignedWrap();
8162 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8163 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8164 (ICmpInst::isEquality(P: Pred) &&
8165 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8166 return new ICmpInst(CmpPredicate::getSwapped(P: CmpPred), B,
8167 ConstantInt::get(Ty: Op0->getType(), V: 0));
8168 }
8169 }
8170 }
8171
8172 // Try to optimize equality comparisons against alloca-based pointers.
8173 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8174 assert(Op1->getType()->isPointerTy() &&
8175 "Comparing pointer with non-pointer?");
8176 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op0)))
8177 if (foldAllocaCmp(Alloca))
8178 return nullptr;
8179 if (auto *Alloca = dyn_cast<AllocaInst>(Val: getUnderlyingObject(V: Op1)))
8180 if (foldAllocaCmp(Alloca))
8181 return nullptr;
8182 }
8183
8184 if (Instruction *Res = foldICmpBitCast(Cmp&: I))
8185 return Res;
8186
8187 // TODO: Hoist this above the min/max bailout.
8188 if (Instruction *R = foldICmpWithCastOp(ICmp&: I))
8189 return R;
8190
8191 {
8192 Value *X, *Y;
8193 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8194 // and (X & ~Y) != 0 --> (X & Y) == 0
8195 // if A is a power of 2.
8196 if (match(V: Op0, P: m_And(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
8197 match(V: Op1, P: m_Zero()) && isKnownToBeAPowerOfTwo(V: X, OrZero: false, CxtI: &I) &&
8198 I.isEquality())
8199 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(LHS: X, RHS: Y),
8200 Op1);
8201
8202 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8203 if (Op0->getType()->isIntOrIntVectorTy()) {
8204 bool ConsumesOp0, ConsumesOp1;
8205 if (isFreeToInvert(V: Op0, WillInvertAllUses: Op0->hasOneUse(), DoesConsume&: ConsumesOp0) &&
8206 isFreeToInvert(V: Op1, WillInvertAllUses: Op1->hasOneUse(), DoesConsume&: ConsumesOp1) &&
8207 (ConsumesOp0 || ConsumesOp1)) {
8208 Value *InvOp0 = getFreelyInverted(V: Op0, WillInvertAllUses: Op0->hasOneUse(), Builder: &Builder);
8209 Value *InvOp1 = getFreelyInverted(V: Op1, WillInvertAllUses: Op1->hasOneUse(), Builder: &Builder);
8210 assert(InvOp0 && InvOp1 &&
8211 "Mismatch between isFreeToInvert and getFreelyInverted");
8212 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8213 }
8214 }
8215
8216 Instruction *AddI = nullptr;
8217 if (match(V: &I, P: m_UAddWithOverflow(L: m_Value(V&: X), R: m_Value(V&: Y),
8218 S: m_Instruction(I&: AddI))) &&
8219 isa<IntegerType>(Val: X->getType())) {
8220 Value *Result;
8221 Constant *Overflow;
8222 // m_UAddWithOverflow can match patterns that do not include an explicit
8223 // "add" instruction, so check the opcode of the matched op.
8224 if (AddI->getOpcode() == Instruction::Add &&
8225 OptimizeOverflowCheck(BinaryOp: Instruction::Add, /*Signed*/ IsSigned: false, LHS: X, RHS: Y, OrigI&: *AddI,
8226 Result, Overflow)) {
8227 replaceInstUsesWith(I&: *AddI, V: Result);
8228 eraseInstFromFunction(I&: *AddI);
8229 return replaceInstUsesWith(I, V: Overflow);
8230 }
8231 }
8232
8233 // (zext X) + (zext Y) --> add + overflow check.
8234 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8235 if ((match(V: Op0, P: m_NUWAdd(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y)))) ||
8236 match(V: Op0, P: m_NUWMul(L: m_ZExt(Op: m_Value(V&: X)), R: m_ZExt(Op: m_Value(V&: Y))))) &&
8237 match(V: Op1, P: m_APInt(Res&: C))) {
8238 if (Instruction *R = processUZExtIdiom(I, Val: Op0, OtherVal: C, IC&: *this))
8239 return R;
8240 }
8241
8242 // Signbit test folds
8243 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8244 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8245 Instruction *ExtI;
8246 if ((I.isUnsigned() || I.isEquality()) &&
8247 match(V: Op1,
8248 P: m_CombineAnd(Ps: m_Instruction(I&: ExtI), Ps: m_ZExtOrSExt(Op: m_Value(V&: Y)))) &&
8249 Y->getType()->getScalarSizeInBits() == 1 &&
8250 (Op0->hasOneUse() || Op1->hasOneUse())) {
8251 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8252 Instruction *ShiftI;
8253 if (match(V: Op0, P: m_CombineAnd(Ps: m_Instruction(I&: ShiftI),
8254 Ps: m_Shr(L: m_Value(V&: X), R: m_SpecificIntAllowPoison(
8255 V: OpWidth - 1))))) {
8256 unsigned ExtOpc = ExtI->getOpcode();
8257 unsigned ShiftOpc = ShiftI->getOpcode();
8258 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8259 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8260 Value *SLTZero =
8261 Builder.CreateICmpSLT(LHS: X, RHS: Constant::getNullValue(Ty: X->getType()));
8262 Value *Cmp = Builder.CreateICmp(P: Pred, LHS: SLTZero, RHS: Y, Name: I.getName());
8263 return replaceInstUsesWith(I, V: Cmp);
8264 }
8265 }
8266 }
8267 }
8268
8269 if (Instruction *Res = foldICmpEquality(I))
8270 return Res;
8271
8272 if (Instruction *Res = foldICmpPow2Test(I, Builder))
8273 return Res;
8274
8275 if (Instruction *Res = foldICmpOfUAddOv(I))
8276 return Res;
8277
8278 if (Instruction *Res = foldICmpOfVectorReduce(I, DL, Builder))
8279 return Res;
8280
8281 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8282 // an i1 which indicates whether or not we successfully did the swap.
8283 //
8284 // Replace comparisons between the old value and the expected value with the
8285 // indicator that 'cmpxchg' returns.
8286 //
8287 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8288 // spuriously fail. In those cases, the old value may equal the expected
8289 // value but it is possible for the swap to not occur.
8290 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8291 if (auto *EVI = dyn_cast<ExtractValueInst>(Val: Op0))
8292 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(Val: EVI->getAggregateOperand()))
8293 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8294 !ACXI->isWeak())
8295 return ExtractValueInst::Create(Agg: ACXI, Idxs: 1);
8296
8297 if (Instruction *Res = foldICmpWithHighBitMask(Cmp&: I, Builder))
8298 return Res;
8299
8300 if (I.getType()->isVectorTy())
8301 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
8302 return Res;
8303
8304 if (Instruction *Res = foldICmpInvariantGroup(I))
8305 return Res;
8306
8307 if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
8308 return Res;
8309
8310 {
8311 Value *A;
8312 const APInt *C1, *C2;
8313 ICmpInst::Predicate Pred = I.getPredicate();
8314 if (ICmpInst::isEquality(P: Pred)) {
8315 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8316 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8317 if (match(V: Op0, P: m_And(L: m_SExt(Op: m_Value(V&: A)), R: m_APInt(Res&: C1))) &&
8318 match(V: Op1, P: m_APInt(Res&: C2))) {
8319 Type *InputTy = A->getType();
8320 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8321 // c2 must be non-negative at the bitwidth of a.
8322 if (C2->getActiveBits() < InputBitWidth) {
8323 APInt TruncC1 = C1->trunc(width: InputBitWidth);
8324 // Check if there are 1s in C1 high bits of size InputBitWidth.
8325 if (C1->uge(RHS: APInt::getOneBitSet(numBits: C1->getBitWidth(), BitNo: InputBitWidth)))
8326 TruncC1.setBit(InputBitWidth - 1);
8327 Value *AndInst = Builder.CreateAnd(LHS: A, RHS: TruncC1);
8328 return new ICmpInst(
8329 Pred, AndInst,
8330 ConstantInt::get(Ty: InputTy, V: C2->trunc(width: InputBitWidth)));
8331 }
8332 }
8333 }
8334 }
8335
8336 return Changed ? &I : nullptr;
8337}
8338
8339/// Fold fcmp ([us]itofp x, cst) if possible.
8340Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
8341 Instruction *LHSI,
8342 Constant *RHSC) {
8343 const APFloat *RHS;
8344 if (!match(V: RHSC, P: m_APFloat(Res&: RHS)))
8345 return nullptr;
8346
8347 // Get the width of the mantissa. We don't want to hack on conversions that
8348 // might lose information from the integer, e.g. "i64 -> float"
8349 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8350 if (MantissaWidth == -1)
8351 return nullptr; // Unknown.
8352
8353 Type *IntTy = LHSI->getOperand(i: 0)->getType();
8354 unsigned IntWidth = IntTy->getScalarSizeInBits();
8355 bool LHSUnsigned = isa<UIToFPInst>(Val: LHSI);
8356
8357 if (I.isEquality()) {
8358 FCmpInst::Predicate P = I.getPredicate();
8359 bool IsExact = false;
8360 APSInt RHSCvt(IntWidth, LHSUnsigned);
8361 RHS->convertToInteger(Result&: RHSCvt, RM: APFloat::rmNearestTiesToEven, IsExact: &IsExact);
8362
8363 // If the floating point constant isn't an integer value, we know if we will
8364 // ever compare equal / not equal to it.
8365 if (!IsExact) {
8366 // TODO: Can never be -0.0 and other non-representable values
8367 APFloat RHSRoundInt(*RHS);
8368 RHSRoundInt.roundToIntegral(RM: APFloat::rmNearestTiesToEven);
8369 if (*RHS != RHSRoundInt) {
8370 if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
8371 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8372
8373 assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
8374 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8375 }
8376 }
8377
8378 // TODO: If the constant is exactly representable, is it always OK to do
8379 // equality compares as integer?
8380 }
8381
8382 // Check to see that the input is converted from an integer type that is small
8383 // enough that preserves all bits. TODO: check here for "known" sign bits.
8384 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8385
8386 // Following test does NOT adjust IntWidth downwards for signed inputs,
8387 // because the most negative value still requires all the mantissa bits
8388 // to distinguish it from one less than that value.
8389 if ((int)IntWidth > MantissaWidth) {
8390 // Conversion would lose accuracy. Check if loss can impact comparison.
8391 int Exp = ilogb(Arg: *RHS);
8392 if (Exp == APFloat::IEK_Inf) {
8393 int MaxExponent = ilogb(Arg: APFloat::getLargest(Sem: RHS->getSemantics()));
8394 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8395 // Conversion could create infinity.
8396 return nullptr;
8397 } else {
8398 // Note that if RHS is zero or NaN, then Exp is negative
8399 // and first condition is trivially false.
8400 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8401 // Conversion could affect comparison.
8402 return nullptr;
8403 }
8404 }
8405
8406 // Otherwise, we can potentially simplify the comparison. We know that it
8407 // will always come through as an integer value and we know the constant is
8408 // not a NAN (it would have been previously simplified).
8409 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8410
8411 ICmpInst::Predicate Pred;
8412 switch (I.getPredicate()) {
8413 default:
8414 llvm_unreachable("Unexpected predicate!");
8415 case FCmpInst::FCMP_UEQ:
8416 case FCmpInst::FCMP_OEQ:
8417 Pred = ICmpInst::ICMP_EQ;
8418 break;
8419 case FCmpInst::FCMP_UGT:
8420 case FCmpInst::FCMP_OGT:
8421 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8422 break;
8423 case FCmpInst::FCMP_UGE:
8424 case FCmpInst::FCMP_OGE:
8425 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8426 break;
8427 case FCmpInst::FCMP_ULT:
8428 case FCmpInst::FCMP_OLT:
8429 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8430 break;
8431 case FCmpInst::FCMP_ULE:
8432 case FCmpInst::FCMP_OLE:
8433 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8434 break;
8435 case FCmpInst::FCMP_UNE:
8436 case FCmpInst::FCMP_ONE:
8437 Pred = ICmpInst::ICMP_NE;
8438 break;
8439 case FCmpInst::FCMP_ORD:
8440 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8441 case FCmpInst::FCMP_UNO:
8442 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8443 }
8444
8445 // Now we know that the APFloat is a normal number, zero or inf.
8446
8447 // See if the FP constant is too large for the integer. For example,
8448 // comparing an i8 to 300.0.
8449 if (!LHSUnsigned) {
8450 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8451 // and large values.
8452 APFloat SMax(RHS->getSemantics());
8453 SMax.convertFromAPInt(Input: APInt::getSignedMaxValue(numBits: IntWidth), IsSigned: true,
8454 RM: APFloat::rmNearestTiesToEven);
8455 if (SMax < *RHS) { // smax < 13123.0
8456 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8457 Pred == ICmpInst::ICMP_SLE)
8458 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8459 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8460 }
8461 } else {
8462 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8463 // +INF and large values.
8464 APFloat UMax(RHS->getSemantics());
8465 UMax.convertFromAPInt(Input: APInt::getMaxValue(numBits: IntWidth), IsSigned: false,
8466 RM: APFloat::rmNearestTiesToEven);
8467 if (UMax < *RHS) { // umax < 13123.0
8468 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8469 Pred == ICmpInst::ICMP_ULE)
8470 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8471 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8472 }
8473 }
8474
8475 if (!LHSUnsigned) {
8476 // See if the RHS value is < SignedMin.
8477 APFloat SMin(RHS->getSemantics());
8478 SMin.convertFromAPInt(Input: APInt::getSignedMinValue(numBits: IntWidth), IsSigned: true,
8479 RM: APFloat::rmNearestTiesToEven);
8480 if (SMin > *RHS) { // smin > 12312.0
8481 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8482 Pred == ICmpInst::ICMP_SGE)
8483 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8484 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8485 }
8486 } else {
8487 // See if the RHS value is < UnsignedMin.
8488 APFloat UMin(RHS->getSemantics());
8489 UMin.convertFromAPInt(Input: APInt::getMinValue(numBits: IntWidth), IsSigned: false,
8490 RM: APFloat::rmNearestTiesToEven);
8491 if (UMin > *RHS) { // umin > 12312.0
8492 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8493 Pred == ICmpInst::ICMP_UGE)
8494 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8495 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8496 }
8497 }
8498
8499 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8500 // [0, UMAX], but it may still be fractional. Check whether this is the case
8501 // using the IsExact flag.
8502 // Don't do this for zero, because -0.0 is not fractional.
8503 APSInt RHSInt(IntWidth, LHSUnsigned);
8504 bool IsExact;
8505 RHS->convertToInteger(Result&: RHSInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
8506 if (!RHS->isZero()) {
8507 if (!IsExact) {
8508 // If we had a comparison against a fractional value, we have to adjust
8509 // the compare predicate and sometimes the value. RHSC is rounded towards
8510 // zero at this point.
8511 switch (Pred) {
8512 default:
8513 llvm_unreachable("Unexpected integer comparison!");
8514 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8515 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8516 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8517 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8518 case ICmpInst::ICMP_ULE:
8519 // (float)int <= 4.4 --> int <= 4
8520 // (float)int <= -4.4 --> false
8521 if (RHS->isNegative())
8522 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8523 break;
8524 case ICmpInst::ICMP_SLE:
8525 // (float)int <= 4.4 --> int <= 4
8526 // (float)int <= -4.4 --> int < -4
8527 if (RHS->isNegative())
8528 Pred = ICmpInst::ICMP_SLT;
8529 break;
8530 case ICmpInst::ICMP_ULT:
8531 // (float)int < -4.4 --> false
8532 // (float)int < 4.4 --> int <= 4
8533 if (RHS->isNegative())
8534 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
8535 Pred = ICmpInst::ICMP_ULE;
8536 break;
8537 case ICmpInst::ICMP_SLT:
8538 // (float)int < -4.4 --> int < -4
8539 // (float)int < 4.4 --> int <= 4
8540 if (!RHS->isNegative())
8541 Pred = ICmpInst::ICMP_SLE;
8542 break;
8543 case ICmpInst::ICMP_UGT:
8544 // (float)int > 4.4 --> int > 4
8545 // (float)int > -4.4 --> true
8546 if (RHS->isNegative())
8547 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8548 break;
8549 case ICmpInst::ICMP_SGT:
8550 // (float)int > 4.4 --> int > 4
8551 // (float)int > -4.4 --> int >= -4
8552 if (RHS->isNegative())
8553 Pred = ICmpInst::ICMP_SGE;
8554 break;
8555 case ICmpInst::ICMP_UGE:
8556 // (float)int >= -4.4 --> true
8557 // (float)int >= 4.4 --> int > 4
8558 if (RHS->isNegative())
8559 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
8560 Pred = ICmpInst::ICMP_UGT;
8561 break;
8562 case ICmpInst::ICMP_SGE:
8563 // (float)int >= -4.4 --> int >= -4
8564 // (float)int >= 4.4 --> int > 4
8565 if (!RHS->isNegative())
8566 Pred = ICmpInst::ICMP_SGT;
8567 break;
8568 }
8569 }
8570 }
8571
8572 // Lower this FP comparison into an appropriate integer version of the
8573 // comparison.
8574 return new ICmpInst(Pred, LHSI->getOperand(i: 0),
8575 ConstantInt::get(Ty: LHSI->getOperand(i: 0)->getType(), V: RHSInt));
8576}
8577
8578/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8579/// where all true/false values are constants that allow the compare to be
8580/// constant-folded for every combination of C1 and C2.
8581/// We compute a 4-entry truth table and use createLogicFromTable to
8582/// synthesize a boolean expression of C1 and C2.
8583Instruction *InstCombinerImpl::foldCmpSelectOfConstants(CmpInst &I) {
8584 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8585 Value *C1, *C2;
8586 Constant *TV1, *FV1, *TV2, *FV2;
8587
8588 if (!match(V: Op0, P: m_Select(C: m_Value(V&: C1), L: m_Constant(C&: TV1), R: m_Constant(C&: FV1))) ||
8589 !match(V: Op1, P: m_Select(C: m_Value(V&: C2), L: m_Constant(C&: TV2), R: m_Constant(C&: FV2))))
8590 return nullptr;
8591
8592 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8593 return nullptr;
8594
8595 unsigned Pred = I.getPredicate();
8596 const DataLayout &DL = I.getDataLayout();
8597
8598 Constant *Res00 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: FV1, RHS: FV2, DL);
8599 Constant *Res01 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: FV1, RHS: TV2, DL);
8600 Constant *Res10 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: TV1, RHS: FV2, DL);
8601 Constant *Res11 = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: TV1, RHS: TV2, DL);
8602
8603 if (!Res00 || !Res01 || !Res10 || !Res11)
8604 return nullptr;
8605
8606 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8607 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8608 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8609 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8610 return nullptr;
8611
8612 std::bitset<4> Table;
8613 if (!Res00->isNullValue())
8614 Table.set(position: 0);
8615 if (!Res01->isNullValue())
8616 Table.set(position: 1);
8617 if (!Res10->isNullValue())
8618 Table.set(position: 2);
8619 if (!Res11->isNullValue())
8620 Table.set(position: 3);
8621
8622 Value *Res = createLogicFromTable(Table, Op0: C1, Op1: C2, Builder,
8623 HasOneUse: Op0->hasOneUse() && Op1->hasOneUse());
8624 if (!Res)
8625 return nullptr;
8626 return replaceInstUsesWith(I, V: Res);
8627}
8628
8629/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8630static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
8631 Constant *RHSC) {
8632 // When C is not 0.0 and infinities are not allowed:
8633 // (C / X) < 0.0 is a sign-bit test of X
8634 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8635 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8636 //
8637 // Proof:
8638 // Multiply (C / X) < 0.0 by X * X / C.
8639 // - X is non zero, if it is the flag 'ninf' is violated.
8640 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8641 // the predicate. C is also non zero by definition.
8642 //
8643 // Thus X * X / C is non zero and the transformation is valid. [qed]
8644
8645 FCmpInst::Predicate Pred = I.getPredicate();
8646
8647 // Check that predicates are valid.
8648 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8649 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8650 return nullptr;
8651
8652 // Check that RHS operand is zero.
8653 if (!match(V: RHSC, P: m_AnyZeroFP()))
8654 return nullptr;
8655
8656 // Check fastmath flags ('ninf').
8657 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8658 return nullptr;
8659
8660 // Check the properties of the dividend. It must not be zero to avoid a
8661 // division by zero (see Proof).
8662 const APFloat *C;
8663 if (!match(V: LHSI->getOperand(i: 0), P: m_APFloat(Res&: C)))
8664 return nullptr;
8665
8666 if (C->isZero())
8667 return nullptr;
8668
8669 // Get swapped predicate if necessary.
8670 if (C->isNegative())
8671 Pred = I.getSwappedPredicate();
8672
8673 return new FCmpInst(Pred, LHSI->getOperand(i: 1), RHSC, "", &I);
8674}
8675
8676// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8677// Patterns include:
8678// fptrunc(x) < C --> x < ext(C)
8679// fptrunc(x) <= C --> x <= ext(C)
8680// fptrunc(x) > C --> x > ext(C)
8681// fptrunc(x) >= C --> x >= ext(C)
8682// fptrunc(x) ord/uno C --> x ord/uno 0
8683// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8684// due to precision loss.
8685static Instruction *foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc,
8686 const Constant &C) {
8687 FCmpInst::Predicate Pred = I.getPredicate();
8688 Type *DestType = FPTrunc.getOperand(i: 0)->getType();
8689
8690 const APFloat *CValue;
8691 // TODO: support vec
8692 if (!match(V: &C, P: m_APFloat(Res&: CValue)))
8693 return nullptr;
8694
8695 // Handle ord/uno
8696 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8697 assert(!CValue->isNaN() &&
8698 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8699 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8700 ConstantFP::getZero(Ty: DestType), "", &I);
8701 }
8702
8703 // Handle <, >, <=, >=
8704 bool RoundDown = false;
8705
8706 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8707 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8708 RoundDown = true;
8709 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8710 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8711 RoundDown = false;
8712 else
8713 return nullptr;
8714
8715 if (CValue->isNaN() || CValue->isInfinity())
8716 return nullptr;
8717
8718 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8719 bool LosesInfo;
8720 APFloat Dest = Src;
8721 Dest.convert(ToSemantics: Sema, RM: APFloat::rmNearestTiesToEven, losesInfo: &LosesInfo);
8722 return Dest;
8723 };
8724
8725 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8726 APFloat NextValue = Value;
8727 NextValue.next(nextDown: RoundDown);
8728 return NextValue;
8729 };
8730
8731 APFloat NextCValue = NextValue(*CValue, RoundDown);
8732
8733 const fltSemantics &DestFltSema =
8734 DestType->getScalarType()->getFltSemantics();
8735
8736 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8737 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8738
8739 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8740 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8741 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8742 // value of 'CValue'.
8743 if (NextCValue.isInfinity()) {
8744 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8745 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8746
8747 ExtNextCValue = ExtCValue + Bias;
8748 }
8749
8750 APFloat ExtMidValue =
8751 scalbn(X: ExtCValue + ExtNextCValue, Exp: -1, RM: APFloat::rmNearestTiesToEven);
8752
8753 const fltSemantics &SrcFltSema =
8754 C.getType()->getScalarType()->getFltSemantics();
8755
8756 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8757 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8758 if (MidValue != *CValue)
8759 ExtMidValue.next(nextDown: !RoundDown);
8760
8761 // Check whether 'ExtMidValue' is a valid result since the assumption on
8762 // imaged 'NextCValue' might not hold for new float types.
8763 // ppc_fp128 can't pass here when converting from max float because of
8764 // APFloat implementation.
8765 if (NextCValue.isInfinity()) {
8766 // ExtMidValue --- narrowed ---> Finite
8767 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8768 return nullptr;
8769
8770 // NextExtMidValue --- narrowed ---> Infinity
8771 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8772 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8773 return nullptr;
8774 }
8775
8776 return new FCmpInst(Pred, FPTrunc.getOperand(i: 0),
8777 ConstantFP::get(Ty: DestType, V: ExtMidValue), "", &I);
8778}
8779
8780/// Optimize fabs(X) compared with zero.
8781static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8782 Value *X;
8783 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: X))))
8784 return nullptr;
8785
8786 const APFloat *C;
8787 if (!match(V: I.getOperand(i_nocapture: 1), P: m_APFloat(Res&: C)))
8788 return nullptr;
8789
8790 if (!C->isPosZero()) {
8791 if (!C->isSmallestNormalized())
8792 return nullptr;
8793
8794 const Function *F = I.getFunction();
8795 DenormalMode Mode = F->getDenormalMode(FPType: C->getSemantics());
8796 if (Mode.Input == DenormalMode::PreserveSign ||
8797 Mode.Input == DenormalMode::PositiveZero) {
8798
8799 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8800 Constant *Zero = ConstantFP::getZero(Ty: X->getType());
8801 return new FCmpInst(P, X, Zero, "", I);
8802 };
8803
8804 switch (I.getPredicate()) {
8805 case FCmpInst::FCMP_OLT:
8806 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8807 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8808 case FCmpInst::FCMP_UGE:
8809 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8810 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8811 case FCmpInst::FCMP_OGE:
8812 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8813 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8814 case FCmpInst::FCMP_ULT:
8815 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8816 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8817 default:
8818 break;
8819 }
8820 }
8821
8822 return nullptr;
8823 }
8824
8825 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8826 I->setPredicate(P);
8827 return IC.replaceOperand(I&: *I, OpNum: 0, V: X);
8828 };
8829
8830 switch (I.getPredicate()) {
8831 case FCmpInst::FCMP_UGE:
8832 case FCmpInst::FCMP_OLT:
8833 // fabs(X) >= 0.0 --> true
8834 // fabs(X) < 0.0 --> false
8835 llvm_unreachable("fcmp should have simplified");
8836
8837 case FCmpInst::FCMP_OGT:
8838 // fabs(X) > 0.0 --> X != 0.0
8839 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8840
8841 case FCmpInst::FCMP_UGT:
8842 // fabs(X) u> 0.0 --> X u!= 0.0
8843 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8844
8845 case FCmpInst::FCMP_OLE:
8846 // fabs(X) <= 0.0 --> X == 0.0
8847 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8848
8849 case FCmpInst::FCMP_ULE:
8850 // fabs(X) u<= 0.0 --> X u== 0.0
8851 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8852
8853 case FCmpInst::FCMP_OGE:
8854 // fabs(X) >= 0.0 --> !isnan(X)
8855 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8856 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8857
8858 case FCmpInst::FCMP_ULT:
8859 // fabs(X) u< 0.0 --> isnan(X)
8860 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8861 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8862
8863 case FCmpInst::FCMP_OEQ:
8864 case FCmpInst::FCMP_UEQ:
8865 case FCmpInst::FCMP_ONE:
8866 case FCmpInst::FCMP_UNE:
8867 case FCmpInst::FCMP_ORD:
8868 case FCmpInst::FCMP_UNO:
8869 // Look through the fabs() because it doesn't change anything but the sign.
8870 // fabs(X) == 0.0 --> X == 0.0,
8871 // fabs(X) != 0.0 --> X != 0.0
8872 // isnan(fabs(X)) --> isnan(X)
8873 // !isnan(fabs(X) --> !isnan(X)
8874 return replacePredAndOp0(&I, I.getPredicate(), X);
8875
8876 default:
8877 return nullptr;
8878 }
8879}
8880
8881/// Optimize sqrt(X) compared with zero.
8882static Instruction *foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
8883 Value *X;
8884 if (!match(V: I.getOperand(i_nocapture: 0), P: m_Sqrt(Op0: m_Value(V&: X))))
8885 return nullptr;
8886
8887 if (!match(V: I.getOperand(i_nocapture: 1), P: m_PosZeroFP()))
8888 return nullptr;
8889
8890 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8891 I.setPredicate(P);
8892 return IC.replaceOperand(I, OpNum: 0, V: X);
8893 };
8894
8895 // Clear ninf flag if sqrt doesn't have it.
8896 if (!cast<Instruction>(Val: I.getOperand(i_nocapture: 0))->hasNoInfs())
8897 I.setHasNoInfs(false);
8898
8899 switch (I.getPredicate()) {
8900 case FCmpInst::FCMP_OLT:
8901 case FCmpInst::FCMP_UGE:
8902 // sqrt(X) < 0.0 --> false
8903 // sqrt(X) u>= 0.0 --> true
8904 llvm_unreachable("fcmp should have simplified");
8905 case FCmpInst::FCMP_ULT:
8906 case FCmpInst::FCMP_ULE:
8907 case FCmpInst::FCMP_OGT:
8908 case FCmpInst::FCMP_OGE:
8909 case FCmpInst::FCMP_OEQ:
8910 case FCmpInst::FCMP_UNE:
8911 // sqrt(X) u< 0.0 --> X u< 0.0
8912 // sqrt(X) u<= 0.0 --> X u<= 0.0
8913 // sqrt(X) > 0.0 --> X > 0.0
8914 // sqrt(X) >= 0.0 --> X >= 0.0
8915 // sqrt(X) == 0.0 --> X == 0.0
8916 // sqrt(X) u!= 0.0 --> X u!= 0.0
8917 return IC.replaceOperand(I, OpNum: 0, V: X);
8918
8919 case FCmpInst::FCMP_OLE:
8920 // sqrt(X) <= 0.0 --> X == 0.0
8921 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8922 case FCmpInst::FCMP_UGT:
8923 // sqrt(X) u> 0.0 --> X u!= 0.0
8924 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8925 case FCmpInst::FCMP_UEQ:
8926 // sqrt(X) u== 0.0 --> X u<= 0.0
8927 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8928 case FCmpInst::FCMP_ONE:
8929 // sqrt(X) != 0.0 --> X > 0.0
8930 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8931 case FCmpInst::FCMP_ORD:
8932 // !isnan(sqrt(X)) --> X >= 0.0
8933 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8934 case FCmpInst::FCMP_UNO:
8935 // isnan(sqrt(X)) --> X u< 0.0
8936 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8937 default:
8938 llvm_unreachable("Unexpected predicate!");
8939 }
8940}
8941
8942static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
8943 CmpInst::Predicate Pred = I.getPredicate();
8944 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
8945
8946 // Canonicalize fneg as Op1.
8947 if (match(V: Op0, P: m_FNeg(X: m_Value())) && !match(V: Op1, P: m_FNeg(X: m_Value()))) {
8948 std::swap(a&: Op0, b&: Op1);
8949 Pred = I.getSwappedPredicate();
8950 }
8951
8952 if (!match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
8953 return nullptr;
8954
8955 // Replace the negated operand with 0.0:
8956 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8957 Constant *Zero = ConstantFP::getZero(Ty: Op0->getType());
8958 return new FCmpInst(Pred, Op0, Zero, "", &I);
8959}
8960
8961static Instruction *foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI,
8962 Constant *RHSC, InstCombinerImpl &CI) {
8963 const CmpInst::Predicate Pred = I.getPredicate();
8964 Value *X = LHSI->getOperand(i: 0);
8965 Value *Y = LHSI->getOperand(i: 1);
8966 switch (Pred) {
8967 default:
8968 break;
8969 case FCmpInst::FCMP_UGT:
8970 case FCmpInst::FCMP_ULT:
8971 case FCmpInst::FCMP_UNE:
8972 case FCmpInst::FCMP_OEQ:
8973 case FCmpInst::FCMP_OGE:
8974 case FCmpInst::FCMP_OLE:
8975 // The optimization is not valid if X and Y are infinities of the same
8976 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8977 // flag then we can assume we do not have that case. Otherwise we might be
8978 // able to prove that either X or Y is not infinity.
8979 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8980 !isKnownNeverInfinity(V: Y,
8981 SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)) &&
8982 !isKnownNeverInfinity(V: X, SQ: CI.getSimplifyQuery().getWithInstruction(I: &I)))
8983 break;
8984
8985 [[fallthrough]];
8986 case FCmpInst::FCMP_OGT:
8987 case FCmpInst::FCMP_OLT:
8988 case FCmpInst::FCMP_ONE:
8989 case FCmpInst::FCMP_UEQ:
8990 case FCmpInst::FCMP_UGE:
8991 case FCmpInst::FCMP_ULE:
8992 // fcmp pred (x - y), 0 --> fcmp pred x, y
8993 if (match(V: RHSC, P: m_AnyZeroFP()) &&
8994 I.getFunction()->getDenormalMode(
8995 FPType: LHSI->getType()->getScalarType()->getFltSemantics()) ==
8996 DenormalMode::getIEEE()) {
8997 CI.replaceOperand(I, OpNum: 0, V: X);
8998 CI.replaceOperand(I, OpNum: 1, V: Y);
8999 I.setHasNoInfs(LHSI->hasNoInfs());
9000 if (LHSI->hasNoNaNs())
9001 I.setHasNoNaNs(true);
9002 return &I;
9003 }
9004 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9005 // where C and Y can't be arbitrary floating-point values.
9006 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9007 // to `1.0f`, so the source compare is false while the rewritten compare is
9008 // true.
9009 // We need to make sure (C - Y) never rounds back to C
9010 const APFloat *C;
9011 Value *IntSrc;
9012 if (match(V: RHSC, P: m_APFloat(Res&: C)) &&
9013 match(V: LHSI, P: m_FSub(L: m_Specific(V: RHSC), R: m_IToFP(Op: m_Value(V&: IntSrc)))) &&
9014 C->isNormal()) {
9015 // Requirements on C and Y:
9016 // 1. C is finite, nonzero, normal.
9017 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9018 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9019 // must be integer-valued with an absolute value of at least 1;
9020 // as long as the step size near C does not exceed 1,
9021 // C - Y cannot be rounded back to C when Y != 0.
9022 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9023 // 0, 0` for ordered and unordered predicates as long as C is finite and
9024 // nonzero.
9025 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9026 if (MantissaWidth != -1 && ilogb(Arg: *C) < MantissaWidth) {
9027 Constant *ZeroC = ConstantFP::getZero(Ty: LHSI->getType());
9028 I.setPredicate(I.getSwappedPredicate());
9029 CI.replaceOperand(I, OpNum: 0, V: Y);
9030 CI.replaceOperand(I, OpNum: 1, V: ZeroC);
9031 return &I;
9032 }
9033 }
9034 break;
9035 }
9036
9037 return nullptr;
9038}
9039
9040/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9041/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9042/// float when the uitofp casts are exact and C is in the valid range.
9043///
9044/// Since exact uitofp means distinct integers map to distinct floats, the only
9045/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9046/// There are no values in the open interval (0, 1), so:
9047/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9048// fabs(..) >= C where C >= 1.0 -> a != b
9049///
9050/// The same logic applies to sitofp.
9051static Instruction *foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC) {
9052 Value *FAbsArg;
9053 if (!match(V: I.getOperand(i_nocapture: 0), P: m_FAbs(Op0: m_Value(V&: FAbsArg))))
9054 return nullptr;
9055
9056 const APFloat *C;
9057 if (!match(V: I.getOperand(i_nocapture: 1), P: PatternMatch::m_FiniteNonZero(V&: C)))
9058 return nullptr;
9059
9060 FCmpInst::Predicate Pred = I.getPredicate();
9061 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9062 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9063 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9064 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9065 if (!IsStrictLt && !IsStrictGt && !IsGe)
9066 return nullptr;
9067
9068 APFloat One = APFloat::getOne(Sem: C->getSemantics());
9069 APFloat::cmpResult Cmp = C->compare(RHS: One);
9070
9071 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9072 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9073 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9074 return nullptr;
9075 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9076 return nullptr;
9077 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9078 return nullptr;
9079 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9080 return nullptr;
9081
9082 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9083 Value *A, *B;
9084 bool IsSigned;
9085 if (match(V: FAbsArg, P: m_FSub(L: m_UIToFP(Op: m_Value(V&: A)), R: m_UIToFP(Op: m_Value(V&: B))))) {
9086 IsSigned = false;
9087 } else if (match(V: FAbsArg,
9088 P: m_FSub(L: m_SIToFP(Op: m_Value(V&: A)), R: m_SIToFP(Op: m_Value(V&: B))))) {
9089 IsSigned = true;
9090 } else {
9091 return nullptr;
9092 }
9093
9094 // A and B must have the same integer type
9095 if (A->getType() != B->getType())
9096 return nullptr;
9097
9098 Type *FPTy = FAbsArg->getType();
9099 if (!IC.canBeCastedExactlyIntToFP(V: A, FPTy, IsSigned, CxtI: &I) ||
9100 !IC.canBeCastedExactlyIntToFP(V: B, FPTy, IsSigned, CxtI: &I))
9101 return nullptr;
9102 ICmpInst::Predicate ResultPred =
9103 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9104 return new ICmpInst(ResultPred, A, B);
9105}
9106
9107static Instruction *foldFCmpWithFloorAndCeil(FCmpInst &I,
9108 InstCombinerImpl &IC) {
9109 Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1);
9110 Type *OpType = LHS->getType();
9111 CmpInst::Predicate Pred = I.getPredicate();
9112
9113 bool FloorX = match(V: LHS, P: m_Intrinsic<Intrinsic::floor>(Ops: m_Specific(V: RHS)));
9114 bool CeilX = match(V: LHS, P: m_Intrinsic<Intrinsic::ceil>(Ops: m_Specific(V: RHS)));
9115
9116 if (!FloorX && !CeilX) {
9117 if ((FloorX = match(V: RHS, P: m_Intrinsic<Intrinsic::floor>(Ops: m_Specific(V: LHS)))) ||
9118 (CeilX = match(V: RHS, P: m_Intrinsic<Intrinsic::ceil>(Ops: m_Specific(V: LHS))))) {
9119 std::swap(a&: LHS, b&: RHS);
9120 Pred = I.getSwappedPredicate();
9121 }
9122 }
9123
9124 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9125 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9126 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9127 // where pred is oeq, one, ord, ueq, une, uno.
9128 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(ID: Intrinsic::trunc, Op: RHS);
9129 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9130 }
9131
9132 switch (Pred) {
9133 case FCmpInst::FCMP_OLE:
9134 // fcmp ole floor(x), x => fcmp ord x, 0
9135 if (FloorX)
9136 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
9137 "", &I);
9138 break;
9139 case FCmpInst::FCMP_OGT:
9140 // fcmp ogt floor(x), x => false
9141 if (FloorX)
9142 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9143 break;
9144 case FCmpInst::FCMP_OGE:
9145 // fcmp oge ceil(x), x => fcmp ord x, 0
9146 if (CeilX)
9147 return new FCmpInst(FCmpInst::FCMP_ORD, RHS, ConstantFP::getZero(Ty: OpType),
9148 "", &I);
9149 break;
9150 case FCmpInst::FCMP_OLT:
9151 // fcmp olt ceil(x), x => false
9152 if (CeilX)
9153 return IC.replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9154 break;
9155 case FCmpInst::FCMP_ULE:
9156 // fcmp ule floor(x), x => true
9157 if (FloorX)
9158 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9159 break;
9160 case FCmpInst::FCMP_UGT:
9161 // fcmp ugt floor(x), x => fcmp uno x, 0
9162 if (FloorX)
9163 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
9164 "", &I);
9165 break;
9166 case FCmpInst::FCMP_UGE:
9167 // fcmp uge ceil(x), x => true
9168 if (CeilX)
9169 return IC.replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9170 break;
9171 case FCmpInst::FCMP_ULT:
9172 // fcmp ult ceil(x), x => fcmp uno x, 0
9173 if (CeilX)
9174 return new FCmpInst(FCmpInst::FCMP_UNO, RHS, ConstantFP::getZero(Ty: OpType),
9175 "", &I);
9176 break;
9177 default:
9178 break;
9179 }
9180
9181 return nullptr;
9182}
9183
9184/// Returns true if a select that implements a min/max is redundant and
9185/// select result can be replaced with its non-constant operand, e.g.,
9186/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9187/// where C is the FP constant equal to the minimum integer value
9188/// representable by A.
9189static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A,
9190 Value *B) {
9191 const APFloat *APF;
9192 if (!match(V: B, P: m_APFloat(Res&: APF)))
9193 return false;
9194
9195 auto *I = dyn_cast<Instruction>(Val: A);
9196 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9197 I->getOpcode() == Instruction::UIToFP))
9198 return false;
9199
9200 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9201 unsigned BitWidth = I->getOperand(i: 0)->getType()->getScalarSizeInBits();
9202 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9203 ? APSInt::getMinValue(numBits: BitWidth, Unsigned: IsUnsigned)
9204 : APSInt::getMaxValue(numBits: BitWidth, Unsigned: IsUnsigned);
9205 APSInt ConvertedInt(BitWidth, IsUnsigned);
9206 bool IsExact;
9207 APFloat::opStatus Status =
9208 APF->convertToInteger(Result&: ConvertedInt, RM: APFloat::rmTowardZero, IsExact: &IsExact);
9209 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9210}
9211
9212Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
9213 bool Changed = false;
9214
9215 /// Orders the operands of the compare so that they are listed from most
9216 /// complex to least complex. This puts constants before unary operators,
9217 /// before binary operators.
9218 if (getComplexity(V: I.getOperand(i_nocapture: 0)) < getComplexity(V: I.getOperand(i_nocapture: 1))) {
9219 I.swapOperands();
9220 Changed = true;
9221 }
9222
9223 const CmpInst::Predicate Pred = I.getPredicate();
9224 Value *Op0 = I.getOperand(i_nocapture: 0), *Op1 = I.getOperand(i_nocapture: 1);
9225 if (Value *V = simplifyFCmpInst(Predicate: Pred, LHS: Op0, RHS: Op1, FMF: I.getFastMathFlags(),
9226 Q: SQ.getWithInstruction(I: &I)))
9227 return replaceInstUsesWith(I, V);
9228
9229 // Simplify 'fcmp pred X, X'
9230 Type *OpType = Op0->getType();
9231 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9232 if (Op0 == Op1) {
9233 switch (Pred) {
9234 default:
9235 break;
9236 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9237 case FCmpInst::FCMP_ULT: // True if unordered or less than
9238 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9239 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9240 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9241 I.setPredicate(FCmpInst::FCMP_UNO);
9242 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
9243 return &I;
9244
9245 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9246 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9247 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9248 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9249 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9250 I.setPredicate(FCmpInst::FCMP_ORD);
9251 I.setOperand(i_nocapture: 1, Val_nocapture: Constant::getNullValue(Ty: OpType));
9252 return &I;
9253 }
9254 }
9255
9256 if (I.isCommutative()) {
9257 if (auto Pair = matchSymmetricPair(LHS: I.getOperand(i_nocapture: 0), RHS: I.getOperand(i_nocapture: 1))) {
9258 replaceOperand(I, OpNum: 0, V: Pair->first);
9259 replaceOperand(I, OpNum: 1, V: Pair->second);
9260 return &I;
9261 }
9262 }
9263
9264 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9265 // then canonicalize the operand to 0.0.
9266 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9267 if (!match(V: Op0, P: m_PosZeroFP()) &&
9268 isKnownNeverNaN(V: Op0, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
9269 return replaceOperand(I, OpNum: 0, V: ConstantFP::getZero(Ty: OpType));
9270
9271 if (!match(V: Op1, P: m_PosZeroFP()) &&
9272 isKnownNeverNaN(V: Op1, SQ: getSimplifyQuery().getWithInstruction(I: &I)))
9273 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
9274 }
9275
9276 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9277 Value *X, *Y;
9278 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X))) && match(V: Op1, P: m_FNeg(X: m_Value(V&: Y))))
9279 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9280
9281 if (Instruction *R = foldFCmpFNegCommonOp(I))
9282 return R;
9283
9284 // Test if the FCmpInst instruction is used exclusively by a select as
9285 // part of a minimum or maximum operation. If so, refrain from doing
9286 // any other folding. This helps out other analyses which understand
9287 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9288 // and CodeGen. And in this case, at least one of the comparison
9289 // operands has at least one user besides the compare (the select),
9290 // which would often largely negate the benefit of folding anyway.
9291 if (I.hasOneUse())
9292 if (SelectInst *SI = dyn_cast<SelectInst>(Val: I.user_back())) {
9293 Value *A, *B;
9294 SelectPatternResult SPR = matchSelectPattern(V: SI, LHS&: A, RHS&: B);
9295 bool IsRedundantMinMaxClamp =
9296 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9297 isMinMaxCmpSelectEliminable(Flavor: SPR.Flavor, A, B);
9298 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9299 return nullptr;
9300 }
9301
9302 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9303 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9304 if (match(V: Op1, P: m_AnyZeroFP()) && !match(V: Op1, P: m_PosZeroFP()))
9305 return replaceOperand(I, OpNum: 1, V: ConstantFP::getZero(Ty: OpType));
9306
9307 // Canonicalize:
9308 // fcmp olt X, +inf -> fcmp one X, +inf
9309 // fcmp ole X, +inf -> fcmp ord X, 0
9310 // fcmp ogt X, +inf -> false
9311 // fcmp oge X, +inf -> fcmp oeq X, +inf
9312 // fcmp ult X, +inf -> fcmp une X, +inf
9313 // fcmp ule X, +inf -> true
9314 // fcmp ugt X, +inf -> fcmp uno X, 0
9315 // fcmp uge X, +inf -> fcmp ueq X, +inf
9316 // fcmp olt X, -inf -> false
9317 // fcmp ole X, -inf -> fcmp oeq X, -inf
9318 // fcmp ogt X, -inf -> fcmp one X, -inf
9319 // fcmp oge X, -inf -> fcmp ord X, 0
9320 // fcmp ult X, -inf -> fcmp uno X, 0
9321 // fcmp ule X, -inf -> fcmp ueq X, -inf
9322 // fcmp ugt X, -inf -> fcmp une X, -inf
9323 // fcmp uge X, -inf -> true
9324 const APFloat *C;
9325 if (match(V: Op1, P: m_APFloat(Res&: C)) && C->isInfinity()) {
9326 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(pred: Pred) : Pred) {
9327 default:
9328 break;
9329 case FCmpInst::FCMP_ORD:
9330 case FCmpInst::FCMP_UNO:
9331 case FCmpInst::FCMP_TRUE:
9332 case FCmpInst::FCMP_FALSE:
9333 case FCmpInst::FCMP_OGT:
9334 case FCmpInst::FCMP_ULE:
9335 llvm_unreachable("Should be simplified by InstSimplify");
9336 case FCmpInst::FCMP_OLT:
9337 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9338 case FCmpInst::FCMP_OLE:
9339 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(Ty: OpType),
9340 "", &I);
9341 case FCmpInst::FCMP_OGE:
9342 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9343 case FCmpInst::FCMP_ULT:
9344 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9345 case FCmpInst::FCMP_UGT:
9346 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(Ty: OpType),
9347 "", &I);
9348 case FCmpInst::FCMP_UGE:
9349 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9350 }
9351 }
9352
9353 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9354 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9355 if (match(V: Op1, P: m_PosZeroFP()) &&
9356 match(V: Op0, P: m_OneUse(SubPattern: m_ElementWiseBitCast(Op: m_Value(V&: X)))) &&
9357 X->getType()->isIntOrIntVectorTy() &&
9358 !F.getDenormalMode(FPType: Op1->getType()->getScalarType()->getFltSemantics())
9359 .inputsMayBeZero()) {
9360 ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
9361 if (Pred == FCmpInst::FCMP_OEQ)
9362 IntPred = ICmpInst::ICMP_EQ;
9363 else if (Pred == FCmpInst::FCMP_UNE)
9364 IntPred = ICmpInst::ICMP_NE;
9365
9366 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9367 Type *IntTy = X->getType();
9368 const APInt &SignMask = ~APInt::getSignMask(BitWidth: IntTy->getScalarSizeInBits());
9369 Value *MaskX = Builder.CreateAnd(LHS: X, RHS: ConstantInt::get(Ty: IntTy, V: SignMask));
9370 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(Ty: IntTy));
9371 }
9372 }
9373
9374 // Handle fcmp with instruction LHS and constant RHS.
9375 Instruction *LHSI;
9376 Constant *RHSC;
9377 if (match(V: Op0, P: m_Instruction(I&: LHSI)) && match(V: Op1, P: m_Constant(C&: RHSC))) {
9378 switch (LHSI->getOpcode()) {
9379 case Instruction::Select:
9380 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9381 if (FCmpInst::isEquality(Pred) && match(V: RHSC, P: m_AnyZeroFP()) &&
9382 match(V: LHSI, P: m_c_Select(L: m_FNeg(X: m_Value(V&: X)), R: m_Deferred(V: X))))
9383 return replaceOperand(I, OpNum: 0, V: X);
9384 if (Instruction *NV = FoldOpIntoSelect(Op&: I, SI: cast<SelectInst>(Val: LHSI)))
9385 return NV;
9386 break;
9387 case Instruction::FSub:
9388 if (LHSI->hasOneUse())
9389 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, CI&: *this))
9390 return NV;
9391 break;
9392 case Instruction::PHI:
9393 if (Instruction *NV = foldOpIntoPhi(I, PN: cast<PHINode>(Val: LHSI)))
9394 return NV;
9395 break;
9396 case Instruction::SIToFP:
9397 case Instruction::UIToFP:
9398 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9399 return NV;
9400 break;
9401 case Instruction::FDiv:
9402 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9403 return NV;
9404 break;
9405 case Instruction::Load:
9406 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: LHSI->getOperand(i: 0)))
9407 if (Instruction *Res =
9408 foldCmpLoadFromIndexedGlobal(LI: cast<LoadInst>(Val: LHSI), GEP, ICI&: I))
9409 return Res;
9410 break;
9411 case Instruction::FPTrunc:
9412 if (Instruction *NV = foldFCmpFpTrunc(I, FPTrunc: *LHSI, C: *RHSC))
9413 return NV;
9414 break;
9415 }
9416 }
9417
9418 if (Instruction *R = foldFabsWithFcmpZero(I, IC&: *this))
9419 return R;
9420
9421 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, IC&: *this))
9422 return R;
9423
9424 if (Instruction *R = foldSqrtWithFcmpZero(I, IC&: *this))
9425 return R;
9426
9427 if (Instruction *R = foldFCmpWithFloorAndCeil(I, IC&: *this))
9428 return R;
9429
9430 if (Instruction *R = foldCmpSelectOfConstants(I))
9431 return R;
9432
9433 if (match(V: Op0, P: m_FNeg(X: m_Value(V&: X)))) {
9434 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9435 Constant *C;
9436 if (match(V: Op1, P: m_Constant(C)))
9437 if (Constant *NegC = ConstantFoldUnaryOpOperand(Opcode: Instruction::FNeg, Op: C, DL))
9438 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9439 }
9440
9441 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9442 if (match(V: Op0, P: m_FAdd(L: m_Value(V&: X), R: m_AnyZeroFP())))
9443 return new FCmpInst(Pred, X, Op1, "", &I);
9444
9445 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9446 if (match(V: Op1, P: m_FAdd(L: m_Value(V&: Y), R: m_AnyZeroFP())))
9447 return new FCmpInst(Pred, Op0, Y, "", &I);
9448
9449 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9450 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9451 match(V: Op0, P: m_FPTrunc(Op: m_Value(V&: X))) && match(V: Op1, P: m_FPTrunc(Op: m_Value(V&: Y))) &&
9452 X->getType() == Y->getType())
9453 return new FCmpInst(Pred, X, Y, "", &I);
9454
9455 if (match(V: Op0, P: m_FPExt(Op: m_Value(V&: X)))) {
9456 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9457 if (match(V: Op1, P: m_FPExt(Op: m_Value(V&: Y))) && X->getType() == Y->getType())
9458 return new FCmpInst(Pred, X, Y, "", &I);
9459
9460 const APFloat *C;
9461 if (match(V: Op1, P: m_APFloat(Res&: C))) {
9462 const fltSemantics &FPSem =
9463 X->getType()->getScalarType()->getFltSemantics();
9464 bool Lossy;
9465 APFloat TruncC = *C;
9466 TruncC.convert(ToSemantics: FPSem, RM: APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
9467
9468 if (Lossy) {
9469 // X can't possibly equal the higher-precision constant, so reduce any
9470 // equality comparison.
9471 // TODO: Other predicates can be handled via getFCmpCode().
9472 switch (Pred) {
9473 case FCmpInst::FCMP_OEQ:
9474 // X is ordered and equal to an impossible constant --> false
9475 return replaceInstUsesWith(I, V: ConstantInt::getFalse(Ty: I.getType()));
9476 case FCmpInst::FCMP_ONE:
9477 // X is ordered and not equal to an impossible constant --> ordered
9478 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9479 ConstantFP::getZero(Ty: X->getType()));
9480 case FCmpInst::FCMP_UEQ:
9481 // X is unordered or equal to an impossible constant --> unordered
9482 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9483 ConstantFP::getZero(Ty: X->getType()));
9484 case FCmpInst::FCMP_UNE:
9485 // X is unordered or not equal to an impossible constant --> true
9486 return replaceInstUsesWith(I, V: ConstantInt::getTrue(Ty: I.getType()));
9487 default:
9488 break;
9489 }
9490 }
9491
9492 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9493 // Avoid lossy conversions and denormals.
9494 // Zero is a special case that's OK to convert.
9495 APFloat Fabs = TruncC;
9496 Fabs.clearSign();
9497 if (!Lossy &&
9498 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(Sem: FPSem)))) {
9499 Constant *NewC = ConstantFP::get(Ty: X->getType(), V: TruncC);
9500 return new FCmpInst(Pred, X, NewC, "", &I);
9501 }
9502 }
9503 }
9504
9505 // Convert a sign-bit test of an FP value into a cast and integer compare.
9506 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9507 // TODO: Handle non-zero compare constants.
9508 // TODO: Handle other predicates.
9509 if (match(V: Op0, P: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::copysign>(Ops: m_APFloat(Res&: C),
9510 Ops: m_Value(V&: X)))) &&
9511 match(V: Op1, P: m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9512 Type *IntType = Builder.getIntNTy(N: X->getType()->getScalarSizeInBits());
9513 if (auto *VecTy = dyn_cast<VectorType>(Val: OpType))
9514 IntType = VectorType::get(ElementType: IntType, EC: VecTy->getElementCount());
9515
9516 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9517 if (Pred == FCmpInst::FCMP_OLT) {
9518 Value *IntX = Builder.CreateBitCast(V: X, DestTy: IntType);
9519 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9520 ConstantInt::getNullValue(Ty: IntType));
9521 }
9522 }
9523
9524 {
9525 Value *CanonLHS = nullptr;
9526 match(V: Op0, P: m_Intrinsic<Intrinsic::canonicalize>(Ops: m_Value(V&: CanonLHS)));
9527 // (canonicalize(x) == x) => (x == x)
9528 if (CanonLHS == Op1)
9529 return new FCmpInst(Pred, Op1, Op1, "", &I);
9530
9531 Value *CanonRHS = nullptr;
9532 match(V: Op1, P: m_Intrinsic<Intrinsic::canonicalize>(Ops: m_Value(V&: CanonRHS)));
9533 // (x == canonicalize(x)) => (x == x)
9534 if (CanonRHS == Op0)
9535 return new FCmpInst(Pred, Op0, Op0, "", &I);
9536
9537 // (canonicalize(x) == canonicalize(y)) => (x == y)
9538 if (CanonLHS && CanonRHS)
9539 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9540 }
9541
9542 if (I.getType()->isVectorTy())
9543 if (Instruction *Res = foldVectorCmp(Cmp&: I, Builder))
9544 return Res;
9545
9546 return Changed ? &I : nullptr;
9547}
9548