LLVM 24.0.0git
InstCombineCompares.cpp
Go to the documentation of this file.
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"
22#include "llvm/Analysis/Loads.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"
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
45namespace llvm {
47}
48
49/// Compute Result = In1+In2, returning true if the result overflowed for this
50/// type.
51static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
52 bool IsSigned = false) {
53 bool Overflow;
54 if (IsSigned)
55 Result = In1.sadd_ov(In2, Overflow);
56 else
57 Result = In1.uadd_ov(In2, Overflow);
58
59 return Overflow;
60}
61
62/// Compute Result = In1-In2, returning true if the result overflowed for this
63/// type.
64static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
65 bool IsSigned = false) {
66 bool Overflow;
67 if (IsSigned)
68 Result = In1.ssub_ov(In2, Overflow);
69 else
70 Result = In1.usub_ov(In2, Overflow);
71
72 return Overflow;
73}
74
75/// Given an icmp instruction, return true if any use of this comparison is a
76/// branch on sign bit comparison.
77static bool hasBranchUse(ICmpInst &I) {
78 for (auto *U : I.users())
79 if (isa<CondBrInst>(U))
80 return true;
81 return false;
82}
83
84/// Returns true if the exploded icmp can be expressed as a signed comparison
85/// to zero and updates the predicate accordingly.
86/// The signedness of the comparison is preserved.
87/// TODO: Refactor with decomposeBitTestICmp()?
88static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
89 if (!ICmpInst::isSigned(Pred))
90 return false;
91
92 if (C.isZero())
93 return ICmpInst::isRelational(Pred);
94
95 if (C.isOne()) {
96 if (Pred == ICmpInst::ICMP_SLT) {
97 Pred = ICmpInst::ICMP_SLE;
98 return true;
99 }
100 } else if (C.isAllOnes()) {
101 if (Pred == ICmpInst::ICMP_SGT) {
102 Pred = ICmpInst::ICMP_SGE;
103 return true;
104 }
105 }
106
107 return false;
108}
109
110/// This is called when we see this pattern:
111/// cmp pred (load (gep GV, ...)), cmpcst
112/// where GV is a global variable with a constant initializer. Try to simplify
113/// this into some simple computation that does not need the load. For example
114/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
115///
116/// If AndCst is non-null, then the loaded value is masked with that constant
117/// before doing the comparison. This handles cases like "A[i]&4 == 0".
118///
119/// We allow multi-use cases in this fold, even though it can increase
120/// instruction count, because it appears to be mostly beneficial in practice.
121/// Even if there are multiple uses, they can often be sunk into the block
122/// guarded by the icmp.
124 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
126 if (LI->isVolatile() || !GV || !GV->isConstant() ||
127 !GV->hasDefinitiveInitializer())
128 return nullptr;
129
130 Type *EltTy = LI->getType();
131 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
132 if (EltSize.isScalable())
133 return nullptr;
134
136 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
137 return nullptr;
138
139 Constant *Init = GV->getInitializer();
140 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
141
142 Value *Idx = Expr.Index;
143 const APInt &Stride = Expr.Scale;
144 const APInt &ConstOffset = Expr.Offset;
145
146 // Allow an additional context offset, but only within the stride.
147 if (!ConstOffset.ult(Stride))
148 return nullptr;
149
150 // Don't handle overlapping loads for now.
151 if (!Stride.uge(EltSize.getFixedValue()))
152 return nullptr;
153
154 // Don't blow up on huge arrays.
155 uint64_t ArrayElementCount =
156 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
157 Stride.getZExtValue());
158 if (ArrayElementCount > MaxArraySizeForCombine)
159 return nullptr;
160
161 enum { Overdefined = -3, Undefined = -2 };
162
163 // Variables for our state machines.
164
165 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
166 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
167 // and 87 is the second (and last) index. FirstTrueElement is -2 when
168 // undefined, otherwise set to the first true element. SecondTrueElement is
169 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
170 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
171
172 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
173 // form "i != 47 & i != 87". Same state transitions as for true elements.
174 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
175
176 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
177 /// define a state machine that triggers for ranges of values that the index
178 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
179 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
180 /// index in the range (inclusive). We use -2 for undefined here because we
181 /// use relative comparisons and don't want 0-1 to match -1.
182 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
183
184 // MagicBitvector - This is a magic bitvector where we set a bit if the
185 // comparison is true for element 'i'. If there are 64 elements or less in
186 // the array, this will fully represent all the comparison results.
187 uint64_t MagicBitvector = 0;
188
189 // Scan the array and see if one of our patterns matches.
190 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
191 APInt Offset = ConstOffset;
192 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
194 if (!Elt)
195 return nullptr;
196
197 // If the element is masked, handle it.
198 if (AndCst) {
199 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
200 if (!Elt)
201 return nullptr;
202 }
203
204 // Find out if the comparison would be true or false for the i'th element.
206 CompareRHS, DL, &TLI);
207 if (!C)
208 return nullptr;
209
210 // If the result is undef for this element, ignore it.
211 if (isa<UndefValue>(C)) {
212 // Extend range state machines to cover this element in case there is an
213 // undef in the middle of the range.
214 if (TrueRangeEnd == (int)i - 1)
215 TrueRangeEnd = i;
216 if (FalseRangeEnd == (int)i - 1)
217 FalseRangeEnd = i;
218 continue;
219 }
220
221 // If we can't compute the result for any of the elements, we have to give
222 // up evaluating the entire conditional.
223 if (!isa<ConstantInt>(C))
224 return nullptr;
225
226 // Otherwise, we know if the comparison is true or false for this element,
227 // update our state machines.
228 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
229
230 // State machine for single/double/range index comparison.
231 if (IsTrueForElt) {
232 // Update the TrueElement state machine.
233 if (FirstTrueElement == Undefined)
234 FirstTrueElement = TrueRangeEnd = i; // First true element.
235 else {
236 // Update double-compare state machine.
237 if (SecondTrueElement == Undefined)
238 SecondTrueElement = i;
239 else
240 SecondTrueElement = Overdefined;
241
242 // Update range state machine.
243 if (TrueRangeEnd == (int)i - 1)
244 TrueRangeEnd = i;
245 else
246 TrueRangeEnd = Overdefined;
247 }
248 } else {
249 // Update the FalseElement state machine.
250 if (FirstFalseElement == Undefined)
251 FirstFalseElement = FalseRangeEnd = i; // First false element.
252 else {
253 // Update double-compare state machine.
254 if (SecondFalseElement == Undefined)
255 SecondFalseElement = i;
256 else
257 SecondFalseElement = Overdefined;
258
259 // Update range state machine.
260 if (FalseRangeEnd == (int)i - 1)
261 FalseRangeEnd = i;
262 else
263 FalseRangeEnd = Overdefined;
264 }
265 }
266
267 // If this element is in range, update our magic bitvector.
268 if (i < 64 && IsTrueForElt)
269 MagicBitvector |= 1ULL << i;
270
271 // If all of our states become overdefined, bail out early. Since the
272 // predicate is expensive, only check it every 8 elements. This is only
273 // really useful for really huge arrays.
274 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
275 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
276 FalseRangeEnd == Overdefined)
277 return nullptr;
278 }
279
280 // Now that we've scanned the entire array, emit our new comparison(s). We
281 // order the state machines in complexity of the generated code.
282
283 // If inbounds keyword is not present, Idx * Stride can overflow.
284 // Let's assume that Stride is 2 and the wanted value is at offset 0.
285 // Then, there are two possible values for Idx to match offset 0:
286 // 0x00..00, 0x80..00.
287 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
288 // comparison is false if Idx was 0x80..00.
289 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
290 auto MaskIdx = [&](Value *Idx) {
291 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
293 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
294 Idx = Builder.CreateAnd(Idx, Mask);
295 }
296 return Idx;
297 };
298
299 // If the comparison is only true for one or two elements, emit direct
300 // comparisons.
301 if (SecondTrueElement != Overdefined) {
302 Idx = MaskIdx(Idx);
303 // None true -> false.
304 if (FirstTrueElement == Undefined)
305 return replaceInstUsesWith(ICI, Builder.getFalse());
306
307 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
308
309 // True for one element -> 'i == 47'.
310 if (SecondTrueElement == Undefined)
311 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
312
313 // True for two elements -> 'i == 47 | i == 72'.
314 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
315 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
316 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
317 return BinaryOperator::CreateOr(C1, C2);
318 }
319
320 // If the comparison is only false for one or two elements, emit direct
321 // comparisons.
322 if (SecondFalseElement != Overdefined) {
323 Idx = MaskIdx(Idx);
324 // None false -> true.
325 if (FirstFalseElement == Undefined)
326 return replaceInstUsesWith(ICI, Builder.getTrue());
327
328 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
329
330 // False for one element -> 'i != 47'.
331 if (SecondFalseElement == Undefined)
332 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
333
334 // False for two elements -> 'i != 47 & i != 72'.
335 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
336 Value *SecondFalseIdx =
337 ConstantInt::get(Idx->getType(), SecondFalseElement);
338 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
339 return BinaryOperator::CreateAnd(C1, C2);
340 }
341
342 // If the comparison can be replaced with a range comparison for the elements
343 // where it is true, emit the range check.
344 if (TrueRangeEnd != Overdefined) {
345 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
346 Idx = MaskIdx(Idx);
347
348 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
349 if (FirstTrueElement) {
350 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
351 Idx = Builder.CreateAdd(Idx, Offs);
352 }
353
354 Value *End =
355 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
356 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
357 }
358
359 // False range check.
360 if (FalseRangeEnd != Overdefined) {
361 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
362 Idx = MaskIdx(Idx);
363 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
364 if (FirstFalseElement) {
365 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
366 Idx = Builder.CreateAdd(Idx, Offs);
367 }
368
369 Value *End =
370 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
371 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
372 }
373
374 // If a magic bitvector captures the entire comparison state
375 // of this load, replace it with computation that does:
376 // ((magic_cst >> i) & 1) != 0
377 {
378 Type *Ty = nullptr;
379
380 // Look for an appropriate type:
381 // - The type of Idx if the magic fits
382 // - The smallest fitting legal type
383 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
384 Ty = Idx->getType();
385 else
386 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
387
388 if (Ty) {
389 Idx = MaskIdx(Idx);
390 Value *V = Builder.CreateIntCast(Idx, Ty, false);
391 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
392 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
393 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
394 }
395 }
396
397 return nullptr;
398}
399
400/// Returns true if we can rewrite Start as a GEP with pointer Base
401/// and some integer offset. The nodes that need to be re-written
402/// for this transformation will be added to Explored.
404 const DataLayout &DL,
405 SetVector<Value *> &Explored) {
406 SmallVector<Value *, 16> WorkList(1, Start);
407 Explored.insert(Base);
408
409 // The following traversal gives us an order which can be used
410 // when doing the final transformation. Since in the final
411 // transformation we create the PHI replacement instructions first,
412 // we don't have to get them in any particular order.
413 //
414 // However, for other instructions we will have to traverse the
415 // operands of an instruction first, which means that we have to
416 // do a post-order traversal.
417 while (!WorkList.empty()) {
419
420 while (!WorkList.empty()) {
421 if (Explored.size() >= 100)
422 return false;
423
424 Value *V = WorkList.back();
425
426 if (Explored.contains(V)) {
427 WorkList.pop_back();
428 continue;
429 }
430
432 // We've found some value that we can't explore which is different from
433 // the base. Therefore we can't do this transformation.
434 return false;
435
436 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
437 // Only allow inbounds GEPs with at most one variable offset.
438 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
439 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
440 return false;
441
442 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
443 if (!Explored.contains(GEP->getOperand(0)))
444 WorkList.push_back(GEP->getOperand(0));
445 }
446
447 if (WorkList.back() == V) {
448 WorkList.pop_back();
449 // We've finished visiting this node, mark it as such.
450 Explored.insert(V);
451 }
452
453 if (auto *PN = dyn_cast<PHINode>(V)) {
454 // We cannot transform PHIs on unsplittable basic blocks.
455 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
456 return false;
457 Explored.insert(PN);
458 PHIs.insert(PN);
459 }
460 }
461
462 // Explore the PHI nodes further.
463 for (auto *PN : PHIs)
464 for (Value *Op : PN->incoming_values())
465 if (!Explored.contains(Op))
466 WorkList.push_back(Op);
467 }
468
469 // Make sure that we can do this. Since we can't insert GEPs in a basic
470 // block before a PHI node, we can't easily do this transformation if
471 // we have PHI node users of transformed instructions.
472 for (Value *Val : Explored) {
473 for (Value *Use : Val->uses()) {
474
475 auto *PHI = dyn_cast<PHINode>(Use);
476 auto *Inst = dyn_cast<Instruction>(Val);
477
478 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
479 !Explored.contains(PHI))
480 continue;
481
482 if (PHI->getParent() == Inst->getParent())
483 return false;
484 }
485 }
486 return true;
487}
488
489// Sets the appropriate insert point on Builder where we can add
490// a replacement Instruction for V (if that is possible).
491static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
492 bool Before = true) {
493 if (auto *PHI = dyn_cast<PHINode>(V)) {
494 BasicBlock *Parent = PHI->getParent();
495 Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
496 return;
497 }
498 if (auto *I = dyn_cast<Instruction>(V)) {
499 if (!Before)
500 I = &*std::next(I->getIterator());
501 Builder.SetInsertPoint(I);
502 return;
503 }
504 if (auto *A = dyn_cast<Argument>(V)) {
505 // Set the insertion point in the entry block.
506 BasicBlock &Entry = A->getParent()->getEntryBlock();
507 Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
508 return;
509 }
510 // Otherwise, this is a constant and we don't need to set a new
511 // insertion point.
512 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
513}
514
515/// Returns a re-written value of Start as an indexed GEP using Base as a
516/// pointer.
518 const DataLayout &DL,
519 SetVector<Value *> &Explored,
520 InstCombiner &IC) {
521 // Perform all the substitutions. This is a bit tricky because we can
522 // have cycles in our use-def chains.
523 // 1. Create the PHI nodes without any incoming values.
524 // 2. Create all the other values.
525 // 3. Add the edges for the PHI nodes.
526 // 4. Emit GEPs to get the original pointers.
527 // 5. Remove the original instructions.
528 Type *IndexType = IntegerType::get(
529 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
530
532 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
533
534 // Create the new PHI nodes, without adding any incoming values.
535 for (Value *Val : Explored) {
536 if (Val == Base)
537 continue;
538 // Create empty phi nodes. This avoids cyclic dependencies when creating
539 // the remaining instructions.
540 if (auto *PHI = dyn_cast<PHINode>(Val))
541 NewInsts[PHI] =
542 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
543 PHI->getName() + ".idx", PHI->getIterator());
544 }
545 IRBuilder<> Builder(Base->getContext());
546
547 // Create all the other instructions.
548 for (Value *Val : Explored) {
549 if (NewInsts.contains(Val))
550 continue;
551
552 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
553 setInsertionPoint(Builder, GEP);
554 Value *Op = NewInsts[GEP->getOperand(0)];
555 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
557 NewInsts[GEP] = OffsetV;
558 else
559 NewInsts[GEP] = Builder.CreateAdd(
560 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
561 /*NUW=*/NW.hasNoUnsignedWrap(),
562 /*NSW=*/NW.hasNoUnsignedSignedWrap());
563 continue;
564 }
565 if (isa<PHINode>(Val))
566 continue;
567
568 llvm_unreachable("Unexpected instruction type");
569 }
570
571 // Add the incoming values to the PHI nodes.
572 for (Value *Val : Explored) {
573 if (Val == Base)
574 continue;
575 // All the instructions have been created, we can now add edges to the
576 // phi nodes.
577 if (auto *PHI = dyn_cast<PHINode>(Val)) {
578 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
579 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
580 Value *NewIncoming = PHI->getIncomingValue(I);
581
582 auto It = NewInsts.find(NewIncoming);
583 if (It != NewInsts.end())
584 NewIncoming = It->second;
585
586 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
587 }
588 }
589 }
590
591 for (Value *Val : Explored) {
592 if (Val == Base)
593 continue;
594
595 setInsertionPoint(Builder, Val, false);
596 // Create GEP for external users.
597 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
598 Val->getName() + ".ptr", NW);
599 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
600 // Add old instruction to worklist for DCE. We don't directly remove it
601 // here because the original compare is one of the users.
603 }
604
605 return NewInsts[Start];
606}
607
608/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
609/// We can look through PHIs, GEPs and casts in order to determine a common base
610/// between GEPLHS and RHS.
613 const DataLayout &DL,
614 InstCombiner &IC) {
615 // FIXME: Support vector of pointers.
616 if (GEPLHS->getType()->isVectorTy())
617 return nullptr;
618
619 if (!GEPLHS->hasAllConstantIndices())
620 return nullptr;
621
622 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
623 Value *PtrBase =
625 /*AllowNonInbounds*/ false);
626
627 // Bail if we looked through addrspacecast.
628 if (PtrBase->getType() != GEPLHS->getType())
629 return nullptr;
630
631 // The set of nodes that will take part in this transformation.
632 SetVector<Value *> Nodes;
633 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
634 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
635 return nullptr;
636
637 // We know we can re-write this as
638 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
639 // Since we've only looked through inbouds GEPs we know that we
640 // can't have overflow on either side. We can therefore re-write
641 // this as:
642 // OFFSET1 cmp OFFSET2
643 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
644
645 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
646 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
647 // offset. Since Index is the offset of LHS to the base pointer, we will now
648 // compare the offsets instead of comparing the pointers.
650 IC.Builder.getInt(Offset), NewRHS);
651}
652
653/// Fold comparisons between a GEP instruction and something else. At this point
654/// we know that the GEP is on the LHS of the comparison.
657 // Don't transform signed compares of GEPs into index compares. Even if the
658 // GEP is inbounds, the final add of the base pointer can have signed overflow
659 // and would change the result of the icmp.
660 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
661 // the maximum signed value for the pointer type.
663 return nullptr;
664
665 // Look through bitcasts and addrspacecasts. We do not however want to remove
666 // 0 GEPs.
667 if (!isa<GetElementPtrInst>(RHS))
668 RHS = RHS->stripPointerCasts();
669
670 auto CanFold = [Cond](GEPNoWrapFlags NW) {
672 return true;
673
674 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
676 return NW != GEPNoWrapFlags::none();
677 };
678
679 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
680 if (!NW.hasNoUnsignedWrap()) {
681 // Convert signed to unsigned comparison.
682 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
683 }
684
685 auto *I = new ICmpInst(Cond, Op1, Op2);
686 I->setSameSign(NW.hasNoUnsignedSignedWrap());
687 return I;
688 };
689
691 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
692 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
693 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
694 Value *Offset =
695 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
696 return NewICmp(Base.LHSNW, Offset,
697 Constant::getNullValue(Offset->getType()));
698 }
699
700 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
702 !NullPointerIsDefined(I.getFunction(),
703 RHS->getType()->getPointerAddressSpace())) {
704 // For most address spaces, an allocation can't be placed at null, but null
705 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
706 // the only valid inbounds address derived from null, is null itself.
707 // Thus, we have four cases to consider:
708 // 1) Base == nullptr, Offset == 0 -> inbounds, null
709 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
710 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
711 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
712 //
713 // (Note if we're indexing a type of size 0, that simply collapses into one
714 // of the buckets above.)
715 //
716 // In general, we're allowed to make values less poison (i.e. remove
717 // sources of full UB), so in this case, we just select between the two
718 // non-poison cases (1 and 4 above).
719 //
720 // For vectors, we apply the same reasoning on a per-lane basis.
721 auto *Base = GEPLHS->getPointerOperand();
722 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
723 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
724 Base = Builder.CreateVectorSplat(EC, Base);
725 }
726 return new ICmpInst(Cond, Base,
728 cast<Constant>(RHS), Base->getType()));
729 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
730 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
731
732 // If the base pointers are different, but the indices are the same, just
733 // compare the base pointer.
734 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
735 bool IndicesTheSame =
736 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
737 GEPLHS->getPointerOperand()->getType() ==
738 GEPRHS->getPointerOperand()->getType() &&
739 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
740 if (IndicesTheSame)
741 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
742 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
743 IndicesTheSame = false;
744 break;
745 }
746
747 // If all indices are the same, just compare the base pointers.
748 Type *BaseType = GEPLHS->getOperand(0)->getType();
749 if (IndicesTheSame &&
750 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
751 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
752
753 // If we're comparing GEPs with two base pointers that only differ in type
754 // and both GEPs have only constant indices or just one use, then fold
755 // the compare with the adjusted indices.
756 // FIXME: Support vector of pointers.
757 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
758 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
759 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
760 GEPLHS->getOperand(0)->stripPointerCasts() ==
761 GEPRHS->getOperand(0)->stripPointerCasts() &&
762 !GEPLHS->getType()->isVectorTy()) {
763 Value *LOffset = EmitGEPOffset(GEPLHS);
764 Value *ROffset = EmitGEPOffset(GEPRHS);
765
766 // If we looked through an addrspacecast between different sized address
767 // spaces, the LHS and RHS pointers are different sized
768 // integers. Truncate to the smaller one.
769 Type *LHSIndexTy = LOffset->getType();
770 Type *RHSIndexTy = ROffset->getType();
771 if (LHSIndexTy != RHSIndexTy) {
772 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
773 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
774 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
775 } else
776 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
777 }
778
780 LOffset, ROffset);
781 return replaceInstUsesWith(I, Cmp);
782 }
783 }
784
785 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
786 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
787 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
788 // If the GEPs only differ by one index, compare it.
789 unsigned NumDifferences = 0; // Keep track of # differences.
790 unsigned DiffOperand = 0; // The operand that differs.
791 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
792 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
793 Type *LHSType = GEPLHS->getOperand(i)->getType();
794 Type *RHSType = GEPRHS->getOperand(i)->getType();
795 // FIXME: Better support for vector of pointers.
796 if (LHSType->getPrimitiveSizeInBits() !=
797 RHSType->getPrimitiveSizeInBits() ||
798 (GEPLHS->getType()->isVectorTy() &&
799 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
800 // Irreconcilable differences.
801 NumDifferences = 2;
802 break;
803 }
804
805 if (NumDifferences++)
806 break;
807 DiffOperand = i;
808 }
809
810 if (NumDifferences == 0) // SAME GEP?
811 return replaceInstUsesWith(
812 I, // No comparison is needed here.
813 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
814 // If two GEPs only differ by an index, compare them.
815 // Note that nowrap flags are always needed when comparing two indices.
816 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
817 Value *LHSV = GEPLHS->getOperand(DiffOperand);
818 Value *RHSV = GEPRHS->getOperand(DiffOperand);
819 return NewICmp(NW, LHSV, RHSV);
820 }
821 }
822
823 if (Base.Ptr && !Base.isExpensive()) {
824 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
825 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
826
827 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
828 // Without the flags, we can still fold if the offsets are constant and
829 // they cross the base's alignment boundary the same number of times, so
830 // either both arguments will wrap, or none of them will.
831 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
832 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
833 APInt LOff(BW, 0);
834 APInt ROff(BW, 0);
836 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
837 RHS->stripAndAccumulateConstantOffsets(
838 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
839 DoFold =
842 }
843
844 if (DoFold) {
845 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
846 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
847 /*RewriteGEP=*/true);
848 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
849 /*RewriteGEP=*/true);
850 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
851 }
852 }
853 }
854
855 // Try convert this to an indexed compare by looking through PHIs/casts as a
856 // last resort.
857 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
858}
859
861 // It would be tempting to fold away comparisons between allocas and any
862 // pointer not based on that alloca (e.g. an argument). However, even
863 // though such pointers cannot alias, they can still compare equal.
864 //
865 // But LLVM doesn't specify where allocas get their memory, so if the alloca
866 // doesn't escape we can argue that it's impossible to guess its value, and we
867 // can therefore act as if any such guesses are wrong.
868 //
869 // However, we need to ensure that this folding is consistent: We can't fold
870 // one comparison to false, and then leave a different comparison against the
871 // same value alone (as it might evaluate to true at runtime, leading to a
872 // contradiction). As such, this code ensures that all comparisons are folded
873 // at the same time, and there are no other escapes.
874
875 struct CmpCaptureTracker : public CaptureTracker {
876 AllocaInst *Alloca;
877 bool Captured = false;
878 /// The value of the map is a bit mask of which icmp operands the alloca is
879 /// used in.
881
882 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
883
884 void tooManyUses() override { Captured = true; }
885
886 Action captured(const Use *U, UseCaptureInfo CI) override {
887 // TODO(captures): Use UseCaptureInfo.
888 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
889 // We need to check that U is based *only* on the alloca, and doesn't
890 // have other contributions from a select/phi operand.
891 // TODO: We could check whether getUnderlyingObjects() reduces to one
892 // object, which would allow looking through phi nodes.
893 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
894 // Collect equality icmps of the alloca, and don't treat them as
895 // captures.
896 ICmps[ICmp] |= 1u << U->getOperandNo();
897 return Continue;
898 }
899
900 Captured = true;
901 return Stop;
902 }
903 };
904
905 CmpCaptureTracker Tracker(Alloca);
906 PointerMayBeCaptured(Alloca, &Tracker);
907 if (Tracker.Captured)
908 return false;
909
910 bool Changed = false;
911 for (auto [ICmp, Operands] : Tracker.ICmps) {
912 switch (Operands) {
913 case 1:
914 case 2: {
915 // The alloca is only used in one icmp operand. Assume that the
916 // equality is false.
917 auto *Res = ConstantInt::get(ICmp->getType(),
918 ICmp->getPredicate() == ICmpInst::ICMP_NE);
919 replaceInstUsesWith(*ICmp, Res);
921 Changed = true;
922 break;
923 }
924 case 3:
925 // Both icmp operands are based on the alloca, so this is comparing
926 // pointer offsets, without leaking any information about the address
927 // of the alloca. Ignore such comparisons.
928 break;
929 default:
930 llvm_unreachable("Cannot happen");
931 }
932 }
933
934 return Changed;
935}
936
937/// Fold "icmp pred (X+C), X".
939 CmpPredicate Pred) {
940 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
941 // so the values can never be equal. Similarly for all other "or equals"
942 // operators.
943 assert(!!C && "C should not be zero!");
944
945 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
946 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
947 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
948 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
949 Constant *R =
950 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
951 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
952 }
953
954 // (X+1) >u X --> X <u (0-1) --> X != 255
955 // (X+2) >u X --> X <u (0-2) --> X <u 254
956 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
957 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
958 return new ICmpInst(ICmpInst::ICMP_ULT, X,
959 ConstantInt::get(X->getType(), -C));
960
961 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
962
963 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
964 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
965 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
966 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
967 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
968 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
969 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
970 return new ICmpInst(ICmpInst::ICMP_SGT, X,
971 ConstantInt::get(X->getType(), SMax - C));
972
973 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
974 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
975 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
976 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
977 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
978 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
979
980 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
981 return new ICmpInst(ICmpInst::ICMP_SLT, X,
982 ConstantInt::get(X->getType(), SMax - (C - 1)));
983}
984
985/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
986/// (icmp eq/ne A, Log2(AP2/AP1)) ->
987/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
989 const APInt &AP1,
990 const APInt &AP2) {
991 assert(I.isEquality() && "Cannot fold icmp gt/lt");
992
993 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
994 if (I.getPredicate() == I.ICMP_NE)
995 Pred = CmpInst::getInversePredicate(Pred);
996 return new ICmpInst(Pred, LHS, RHS);
997 };
998
999 // Don't bother doing any work for cases which InstSimplify handles.
1000 if (AP2.isZero())
1001 return nullptr;
1002
1003 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1004 if (IsAShr) {
1005 if (AP2.isAllOnes())
1006 return nullptr;
1007 if (AP2.isNegative() != AP1.isNegative())
1008 return nullptr;
1009 if (AP2.sgt(AP1))
1010 return nullptr;
1011 }
1012
1013 if (!AP1)
1014 // 'A' must be large enough to shift out the highest set bit.
1015 return getICmp(I.ICMP_UGT, A,
1016 ConstantInt::get(A->getType(), AP2.logBase2()));
1017
1018 if (AP1 == AP2)
1019 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1020
1021 int Shift;
1022 if (IsAShr && AP1.isNegative())
1023 Shift = AP1.countl_one() - AP2.countl_one();
1024 else
1025 Shift = AP1.countl_zero() - AP2.countl_zero();
1026
1027 if (Shift > 0) {
1028 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1029 // There are multiple solutions if we are comparing against -1 and the LHS
1030 // of the ashr is not a power of two.
1031 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1032 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1033 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1034 } else if (AP1 == AP2.lshr(Shift)) {
1035 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1036 }
1037 }
1038
1039 // Shifting const2 will never be equal to const1.
1040 // FIXME: This should always be handled by InstSimplify?
1041 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1042 return replaceInstUsesWith(I, TorF);
1043}
1044
1045/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1046/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1048 const APInt &AP1,
1049 const APInt &AP2) {
1050 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1051
1052 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1053 if (I.getPredicate() == I.ICMP_NE)
1054 Pred = CmpInst::getInversePredicate(Pred);
1055 return new ICmpInst(Pred, LHS, RHS);
1056 };
1057
1058 // Don't bother doing any work for cases which InstSimplify handles.
1059 if (AP2.isZero())
1060 return nullptr;
1061
1062 unsigned AP2TrailingZeros = AP2.countr_zero();
1063
1064 if (!AP1 && AP2TrailingZeros != 0)
1065 return getICmp(
1066 I.ICMP_UGE, A,
1067 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1068
1069 if (AP1 == AP2)
1070 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1071
1072 // Get the distance between the lowest bits that are set.
1073 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1074
1075 if (Shift > 0 && AP2.shl(Shift) == AP1)
1076 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1077
1078 // Shifting const2 will never be equal to const1.
1079 // FIXME: This should always be handled by InstSimplify?
1080 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1081 return replaceInstUsesWith(I, TorF);
1082}
1083
1084/// The caller has matched a pattern of the form:
1085/// I = icmp ugt (add (add A, B), CI2), CI1
1086/// If this is of the form:
1087/// sum = a + b
1088/// if (sum+128 >u 255)
1089/// Then replace it with llvm.sadd.with.overflow.i8.
1090///
1092 ConstantInt *CI2, ConstantInt *CI1,
1093 InstCombinerImpl &IC) {
1094 // The transformation we're trying to do here is to transform this into an
1095 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1096 // with a narrower add, and discard the add-with-constant that is part of the
1097 // range check (if we can't eliminate it, this isn't profitable).
1098
1099 // In order to eliminate the add-with-constant, the compare can be its only
1100 // use.
1101 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1102 if (!AddWithCst->hasOneUse())
1103 return nullptr;
1104
1105 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1106 if (!CI2->getValue().isPowerOf2())
1107 return nullptr;
1108 unsigned NewWidth = CI2->getValue().countr_zero();
1109 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1110 return nullptr;
1111
1112 // The width of the new add formed is 1 more than the bias.
1113 ++NewWidth;
1114
1115 // Check to see that CI1 is an all-ones value with NewWidth bits.
1116 if (CI1->getBitWidth() == NewWidth ||
1117 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1118 return nullptr;
1119
1120 // This is only really a signed overflow check if the inputs have been
1121 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1122 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1123 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1124 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1125 return nullptr;
1126
1127 // In order to replace the original add with a narrower
1128 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1129 // and truncates that discard the high bits of the add. Verify that this is
1130 // the case.
1131 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1132 for (User *U : OrigAdd->users()) {
1133 if (U == AddWithCst)
1134 continue;
1135
1136 // Only accept truncates for now. We would really like a nice recursive
1137 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1138 // chain to see which bits of a value are actually demanded. If the
1139 // original add had another add which was then immediately truncated, we
1140 // could still do the transformation.
1142 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1143 return nullptr;
1144 }
1145
1146 // If the pattern matches, truncate the inputs to the narrower type and
1147 // use the sadd_with_overflow intrinsic to efficiently compute both the
1148 // result and the overflow bit.
1149 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1151 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1152
1153 InstCombiner::BuilderTy &Builder = IC.Builder;
1154
1155 // Put the new code above the original add, in case there are any uses of the
1156 // add between the add and the compare.
1157 Builder.SetInsertPoint(OrigAdd);
1158
1159 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1160 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1161 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1162 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1163 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1164
1165 // The inner add was the result of the narrow add, zero extended to the
1166 // wider type. Replace it with the result computed by the intrinsic.
1167 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1168 IC.eraseInstFromFunction(*OrigAdd);
1169
1170 // The original icmp gets replaced with the overflow value.
1171 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1172}
1173
1174/// If we have:
1175/// icmp eq/ne (urem/srem %x, %y), 0
1176/// iff %y is a power-of-two, we can replace this with a bit test:
1177/// icmp eq/ne (and %x, (add %y, -1)), 0
1179 // This fold is only valid for equality predicates.
1180 if (!I.isEquality())
1181 return nullptr;
1182 CmpPredicate Pred;
1183 Value *X, *Y, *Zero;
1184 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1185 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1186 return nullptr;
1187 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1188 return nullptr;
1189 // This may increase instruction count, we don't enforce that Y is a constant.
1190 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1191 Value *Masked = Builder.CreateAnd(X, Mask);
1192 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1193}
1194
1195/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1196/// by one-less-than-bitwidth into a sign test on the original value.
1198 Instruction *Val;
1199 CmpPredicate Pred;
1200 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1201 return nullptr;
1202
1203 Value *X;
1204 Type *XTy;
1205
1206 Constant *C;
1207 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1208 XTy = X->getType();
1209 unsigned XBitWidth = XTy->getScalarSizeInBits();
1211 APInt(XBitWidth, XBitWidth - 1))))
1212 return nullptr;
1213 } else if (isa<BinaryOperator>(Val) &&
1215 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1216 /*AnalyzeForSignBitExtraction=*/true))) {
1217 XTy = X->getType();
1218 } else
1219 return nullptr;
1220
1221 return ICmpInst::Create(Instruction::ICmp,
1225}
1226
1227// Handle icmp pred X, 0
1229 CmpInst::Predicate Pred = Cmp.getPredicate();
1230 if (!match(Cmp.getOperand(1), m_Zero()))
1231 return nullptr;
1232
1233 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1234 if (Pred == ICmpInst::ICMP_SGT) {
1235 Value *A, *B;
1236 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1237 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1238 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1239 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1240 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1241 }
1242 }
1243
1245 return New;
1246
1247 // Given:
1248 // icmp eq/ne (urem %x, %y), 0
1249 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1250 // icmp eq/ne %x, 0
1251 Value *X, *Y;
1252 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1253 ICmpInst::isEquality(Pred)) {
1254 KnownBits XKnown = computeKnownBits(X, &Cmp);
1255 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1256 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1257 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1258 }
1259
1260 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1261 // odd/non-zero/there is no overflow.
1262 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1263 ICmpInst::isEquality(Pred)) {
1264
1265 KnownBits XKnown = computeKnownBits(X, &Cmp);
1266 // if X % 2 != 0
1267 // (icmp eq/ne Y)
1268 if (XKnown.countMaxTrailingZeros() == 0)
1269 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1270
1271 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1272 // if Y % 2 != 0
1273 // (icmp eq/ne X)
1274 if (YKnown.countMaxTrailingZeros() == 0)
1275 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1276
1277 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1278 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1279 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1280 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1281 // but to avoid unnecessary work, first just if this is an obvious case.
1282
1283 // if X non-zero and NoOverflow(X * Y)
1284 // (icmp eq/ne Y)
1285 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1286 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1287
1288 // if Y non-zero and NoOverflow(X * Y)
1289 // (icmp eq/ne X)
1290 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1291 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1292 }
1293 // Note, we are skipping cases:
1294 // if Y % 2 != 0 AND X % 2 != 0
1295 // (false/true)
1296 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1297 // (false/true)
1298 // Those can be simplified later as we would have already replaced the (icmp
1299 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1300 // will fold to a constant elsewhere.
1301 }
1302
1303 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1304 // where f(X) == 0 if and only if X == 0
1305 if (ICmpInst::isEquality(Pred))
1306 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1307 return new ICmpInst(Pred, Stripped,
1308 Constant::getNullValue(Stripped->getType()));
1309
1310 return nullptr;
1311}
1312
1313/// Fold icmp eq (num + mask) & ~mask, num
1314/// to
1315/// icmp eq (and num, mask), 0
1316/// Where mask is a low bit mask.
1318 Value *Num;
1319 CmpPredicate Pred;
1320 const APInt *Mask, *Neg;
1321
1322 if (!match(&Cmp,
1323 m_c_ICmp(Pred, m_Value(Num),
1325 m_LowBitMask(Mask))),
1326 m_APInt(Neg))))))
1327 return nullptr;
1328
1329 if (*Neg != ~*Mask)
1330 return nullptr;
1331
1332 if (!ICmpInst::isEquality(Pred))
1333 return nullptr;
1334
1335 // Create new icmp eq (num & mask), 0
1336 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1337 auto *Zero = Constant::getNullValue(Num->getType());
1338
1339 return new ICmpInst(Pred, NewAnd, Zero);
1340}
1341
1342/// Fold icmp Pred X, C.
1343/// TODO: This code structure does not make sense. The saturating add fold
1344/// should be moved to some other helper and extended as noted below (it is also
1345/// possible that code has been made unnecessary - do we canonicalize IR to
1346/// overflow/saturating intrinsics or not?).
1348 // Match the following pattern, which is a common idiom when writing
1349 // overflow-safe integer arithmetic functions. The source performs an addition
1350 // in wider type and explicitly checks for overflow using comparisons against
1351 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1352 //
1353 // TODO: This could probably be generalized to handle other overflow-safe
1354 // operations if we worked out the formulas to compute the appropriate magic
1355 // constants.
1356 //
1357 // sum = a + b
1358 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1359 CmpInst::Predicate Pred = Cmp.getPredicate();
1360 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1361 Value *A, *B;
1362 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1363 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1364 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1365 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1366 return Res;
1367
1368 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1370 if (!C)
1371 return nullptr;
1372
1373 if (auto *Phi = dyn_cast<PHINode>(Op0))
1374 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1376 for (Value *V : Phi->incoming_values()) {
1377 Constant *Res =
1379 if (!Res)
1380 return nullptr;
1381 Ops.push_back(Res);
1382 }
1383 Builder.SetInsertPoint(Phi);
1384 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1385 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1386 NewPhi->addIncoming(V, Pred);
1387 return replaceInstUsesWith(Cmp, NewPhi);
1388 }
1389
1391 return R;
1392
1393 return nullptr;
1394}
1395
1396/// Canonicalize icmp instructions based on dominating conditions.
1398 // We already checked simple implication in InstSimplify, only handle complex
1399 // cases here.
1400 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1401 const APInt *C;
1402 if (!match(Y, m_APInt(C)))
1403 return nullptr;
1404
1405 CmpInst::Predicate Pred = Cmp.getPredicate();
1407
1408 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1409 const APInt *DomC) -> Instruction * {
1410 // We have 2 compares of a variable with constants. Calculate the constant
1411 // ranges of those compares to see if we can transform the 2nd compare:
1412 // DomBB:
1413 // DomCond = icmp DomPred X, DomC
1414 // br DomCond, CmpBB, FalseBB
1415 // CmpBB:
1416 // Cmp = icmp Pred X, C
1417 ConstantRange DominatingCR =
1418 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1419 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1420 ConstantRange Difference = DominatingCR.difference(CR);
1421 if (Intersection.isEmptySet())
1422 return replaceInstUsesWith(Cmp, Builder.getFalse());
1423 if (Difference.isEmptySet())
1424 return replaceInstUsesWith(Cmp, Builder.getTrue());
1425
1426 // Canonicalizing a sign bit comparison that gets used in a branch,
1427 // pessimizes codegen by generating branch on zero instruction instead
1428 // of a test and branch. So we avoid canonicalizing in such situations
1429 // because test and branch instruction has better branch displacement
1430 // than compare and branch instruction.
1431 bool UnusedBit;
1432 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1433 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1434 return nullptr;
1435
1436 // Avoid an infinite loop with min/max canonicalization.
1437 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1438 if (Cmp.hasOneUse() &&
1439 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1440 return nullptr;
1441
1442 if (const APInt *EqC = Intersection.getSingleElement())
1443 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1444 if (const APInt *NeC = Difference.getSingleElement())
1445 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1446 return nullptr;
1447 };
1448
1449 for (CondBrInst *BI : DC.conditionsFor(X)) {
1450 CmpPredicate DomPred;
1451 const APInt *DomC;
1452 if (!match(BI->getCondition(),
1453 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1454 continue;
1455
1456 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1457 if (DT.dominates(Edge0, Cmp.getParent())) {
1458 if (auto *V = handleDomCond(DomPred, DomC))
1459 return V;
1460 } else {
1461 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1462 if (DT.dominates(Edge1, Cmp.getParent()))
1463 if (auto *V =
1464 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1465 return V;
1466 }
1467 }
1468
1469 return nullptr;
1470}
1471
1472/// Fold icmp (trunc X), C.
1474 TruncInst *Trunc,
1475 const APInt &C) {
1476 ICmpInst::Predicate Pred = Cmp.getPredicate();
1477 Value *X = Trunc->getOperand(0);
1478 Type *SrcTy = X->getType();
1479 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1480 SrcBits = SrcTy->getScalarSizeInBits();
1481
1482 // Match (icmp pred (trunc nuw/nsw X), C)
1483 // Which we can convert to (icmp pred X, (sext/zext C))
1484 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1485 if (Trunc->hasNoSignedWrap())
1486 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1487 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1488 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1489 }
1490
1491 if (C.isOne() && C.getBitWidth() > 1) {
1492 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1493 Value *V = nullptr;
1494 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1495 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1496 ConstantInt::get(V->getType(), 1));
1497 }
1498
1499 // TODO: Handle non-equality predicates.
1500 Value *Y;
1501 const APInt *Pow2;
1502 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1503 DstBits > Pow2->logBase2()) {
1504 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1505 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1506 // iff N > log2(Pow2)
1507 if (C.isZero()) {
1508 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1509 return new ICmpInst(NewPred, Y,
1510 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1511 }
1512 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1513 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1514 if (C.isPowerOf2())
1515 return new ICmpInst(
1516 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1517 }
1518
1519 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1520 // Canonicalize to a mask and wider compare if the wide type is suitable:
1521 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1522 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1523 Constant *Mask =
1524 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1525 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1526 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1527 return new ICmpInst(Pred, And, WideC);
1528 }
1529
1530 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1531 // of the high bits truncated out of x are known.
1533
1534 // If all the high bits are known, we can do this xform.
1535 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1536 // Pull in the high bits from known-ones set.
1537 APInt NewRHS = C.zext(SrcBits);
1538 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1539 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1540 }
1541 }
1542
1543 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1544 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1545 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1546 Value *ShOp;
1547 uint64_t ShAmt;
1548 bool TrueIfSigned;
1549 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1550 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1551 DstBits == SrcBits - ShAmt) {
1552 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1554 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1556 }
1557
1558 return nullptr;
1559}
1560
1561/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1562/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1565 const SimplifyQuery &Q) {
1566 Value *X, *Y;
1567 CmpPredicate Pred;
1568 bool YIsSExt = false;
1569 // Try to match icmp (trunc X), (trunc Y)
1570 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1571 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1572 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1573 if (Cmp.isSigned()) {
1574 // For signed comparisons, both truncs must be nsw.
1575 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1576 return nullptr;
1577 } else {
1578 // For unsigned and equality comparisons, either both must be nuw or
1579 // both must be nsw, we don't care which.
1580 if (!NoWrapFlags)
1581 return nullptr;
1582 }
1583
1584 if (X->getType() != Y->getType() &&
1585 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1586 return nullptr;
1587 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1588 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1589 std::swap(X, Y);
1590 Pred = Cmp.getSwappedPredicate(Pred);
1591 }
1592 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1593 }
1594 // Try to match icmp (trunc nuw X), (zext Y)
1595 else if (!Cmp.isSigned() &&
1596 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1597 m_OneUse(m_ZExt(m_Value(Y)))))) {
1598 // Can fold trunc nuw + zext for unsigned and equality predicates.
1599 }
1600 // Try to match icmp (trunc nsw X), (sext Y)
1601 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1603 // Can fold trunc nsw + zext/sext for all predicates.
1604 YIsSExt =
1605 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1606 } else
1607 return nullptr;
1608
1609 Type *TruncTy = Cmp.getOperand(0)->getType();
1610 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1611
1612 // If this transform will end up changing from desirable types -> undesirable
1613 // types skip it.
1614 if (isDesirableIntType(TruncBits) &&
1615 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1616 return nullptr;
1617
1618 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1619 return new ICmpInst(Pred, X, NewY);
1620}
1621
1622/// Fold icmp (xor X, Y), C.
1625 const APInt &C) {
1626 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1627 return I;
1628
1629 Value *X = Xor->getOperand(0);
1630 Value *Y = Xor->getOperand(1);
1631 const APInt *XorC;
1632 if (!match(Y, m_APInt(XorC)))
1633 return nullptr;
1634
1635 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1636 // fold the xor.
1637 ICmpInst::Predicate Pred = Cmp.getPredicate();
1638 bool TrueIfSigned = false;
1639 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1640
1641 // If the sign bit of the XorCst is not set, there is no change to
1642 // the operation, just stop using the Xor.
1643 if (!XorC->isNegative())
1644 return replaceOperand(Cmp, 0, X);
1645
1646 // Emit the opposite comparison.
1647 if (TrueIfSigned)
1648 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1649 ConstantInt::getAllOnesValue(X->getType()));
1650 else
1651 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1652 ConstantInt::getNullValue(X->getType()));
1653 }
1654
1655 if (Xor->hasOneUse()) {
1656 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1657 if (!Cmp.isEquality() && XorC->isSignMask()) {
1658 Pred = Cmp.getFlippedSignednessPredicate();
1659 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1660 }
1661
1662 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1663 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1664 Pred = Cmp.getFlippedSignednessPredicate();
1665 Pred = Cmp.getSwappedPredicate(Pred);
1666 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1667 }
1668 }
1669
1670 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1671 if (Pred == ICmpInst::ICMP_UGT) {
1672 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1673 if (*XorC == ~C && (C + 1).isPowerOf2())
1674 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1675 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1676 if (*XorC == C && (C + 1).isPowerOf2())
1677 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1678 }
1679 if (Pred == ICmpInst::ICMP_ULT) {
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(X->getType(), ~C));
1684 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1685 if (*XorC == C && (-C).isPowerOf2())
1686 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1687 ConstantInt::get(X->getType(), ~C));
1688 }
1689 return nullptr;
1690}
1691
1692/// For power-of-2 C:
1693/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1694/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1697 const APInt &C) {
1698 CmpInst::Predicate Pred = Cmp.getPredicate();
1699 APInt PowerOf2;
1700 if (Pred == ICmpInst::ICMP_ULT)
1701 PowerOf2 = C;
1702 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1703 PowerOf2 = C + 1;
1704 else
1705 return nullptr;
1706 if (!PowerOf2.isPowerOf2())
1707 return nullptr;
1708 Value *X;
1709 const APInt *ShiftC;
1711 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1712 return nullptr;
1713 uint64_t Shift = ShiftC->getLimitedValue();
1714 Type *XType = X->getType();
1715 if (Shift == 0 || PowerOf2.isMinSignedValue())
1716 return nullptr;
1717 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1718 APInt Bound =
1719 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1720 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1721}
1722
1723/// Fold icmp (and (sh X, Y), C2), C1.
1726 const APInt &C1,
1727 const APInt &C2) {
1728 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1729 if (!Shift || !Shift->isShift())
1730 return nullptr;
1731
1732 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1733 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1734 // code produced by the clang front-end, for bitfield access.
1735 // This seemingly simple opportunity to fold away a shift turns out to be
1736 // rather complicated. See PR17827 for details.
1737 unsigned ShiftOpcode = Shift->getOpcode();
1738 bool IsShl = ShiftOpcode == Instruction::Shl;
1739 const APInt *C3;
1740 if (match(Shift->getOperand(1), m_APInt(C3))) {
1741 APInt NewAndCst, NewCmpCst;
1742 bool AnyCmpCstBitsShiftedOut;
1743 if (ShiftOpcode == Instruction::Shl) {
1744 // For a left shift, we can fold if the comparison is not signed. We can
1745 // also fold a signed comparison if the mask value and comparison value
1746 // are not negative. These constraints may not be obvious, but we can
1747 // prove that they are correct using an SMT solver.
1748 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1749 return nullptr;
1750
1751 NewCmpCst = C1.lshr(*C3);
1752 NewAndCst = C2.lshr(*C3);
1753 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1754 } else if (ShiftOpcode == Instruction::LShr) {
1755 // For a logical right shift, we can fold if the comparison is not signed.
1756 // We can also fold a signed comparison if the shifted mask value and the
1757 // shifted comparison value are not negative. These constraints may not be
1758 // obvious, but we can prove that they are correct using an SMT solver.
1759 NewCmpCst = C1.shl(*C3);
1760 NewAndCst = C2.shl(*C3);
1761 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1762 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1763 return nullptr;
1764 } else {
1765 // For an arithmetic shift, check that both constants don't use (in a
1766 // signed sense) the top bits being shifted out.
1767 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1768 NewCmpCst = C1.shl(*C3);
1769 NewAndCst = C2.shl(*C3);
1770 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1771 if (NewAndCst.ashr(*C3) != C2)
1772 return nullptr;
1773 }
1774
1775 if (AnyCmpCstBitsShiftedOut) {
1776 // If we shifted bits out, the fold is not going to work out. As a
1777 // special case, check to see if this means that the result is always
1778 // true or false now.
1779 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1780 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1781 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1782 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1783 } else {
1784 Value *NewAnd = Builder.CreateAnd(
1785 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1786 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1787 ConstantInt::get(And->getType(), NewCmpCst));
1788 }
1789 }
1790
1791 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1792 // preferable because it allows the C2 << Y expression to be hoisted out of a
1793 // loop if Y is invariant and X is not.
1794 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1795 !Shift->isArithmeticShift() &&
1796 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1797 // Compute C2 << Y.
1798 Value *NewShift =
1799 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1800 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1801
1802 // Compute X & (C2 << Y).
1803 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1804 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1805 }
1806
1807 return nullptr;
1808}
1809
1810/// Fold icmp (and X, C2), C1.
1813 const APInt &C1) {
1814 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1815
1816 // icmp ne (and X, 1), 0 --> trunc X to i1
1817 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1818 return new TruncInst(And->getOperand(0), Cmp.getType());
1819
1820 const APInt *C2;
1821 Value *X;
1822 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1823 return nullptr;
1824
1825 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1826 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1827 C2->isNegatedPowerOf2())
1828 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1829 ConstantInt::get(X->getType(), ~*C2));
1830 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1831 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1832 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1833 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1834 ConstantInt::get(X->getType(), -*C2));
1835
1836 // Don't perform the following transforms if the AND has multiple uses
1837 if (!And->hasOneUse())
1838 return nullptr;
1839
1840 if (Cmp.isEquality() && C1.isZero()) {
1841 // Restrict this fold to single-use 'and' (PR10267).
1842 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1843 if (C2->isSignMask()) {
1844 Constant *Zero = Constant::getNullValue(X->getType());
1845 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1846 return new ICmpInst(NewPred, X, Zero);
1847 }
1848
1849 APInt NewC2 = *C2;
1850 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1851 // Set high zeros of C2 to allow matching negated power-of-2.
1852 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1853 Know.countMinLeadingZeros());
1854
1855 // Restrict this fold only for single-use 'and' (PR10267).
1856 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1857 if (NewC2.isNegatedPowerOf2()) {
1858 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1859 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1860 return new ICmpInst(NewPred, X, NegBOC);
1861 }
1862 }
1863
1864 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1865 // the input width without changing the value produced, eliminate the cast:
1866 //
1867 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1868 //
1869 // We can do this transformation if the constants do not have their sign bits
1870 // set or if it is an equality comparison. Extending a relational comparison
1871 // when we're checking the sign bit would not work.
1872 Value *W;
1873 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1874 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1875 // TODO: Is this a good transform for vectors? Wider types may reduce
1876 // throughput. Should this transform be limited (even for scalars) by using
1877 // shouldChangeType()?
1878 if (!Cmp.getType()->isVectorTy()) {
1879 Type *WideType = W->getType();
1880 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1881 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1882 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1883 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1884 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1885 }
1886 }
1887
1888 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1889 return I;
1890
1891 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1892 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1893 //
1894 // iff pred isn't signed
1895 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1896 match(And->getOperand(1), m_One())) {
1897 Constant *One = cast<Constant>(And->getOperand(1));
1898 Value *Or = And->getOperand(0);
1899 Value *A, *B, *LShr;
1900 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1901 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1902 unsigned UsesRemoved = 0;
1903 if (And->hasOneUse())
1904 ++UsesRemoved;
1905 if (Or->hasOneUse())
1906 ++UsesRemoved;
1907 if (LShr->hasOneUse())
1908 ++UsesRemoved;
1909
1910 // Compute A & ((1 << B) | 1)
1911 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1912 if (UsesRemoved >= RequireUsesRemoved) {
1913 Value *NewOr =
1914 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1915 /*HasNUW=*/true),
1916 One, Or->getName());
1917 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1918 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1919 }
1920 }
1921 }
1922
1923 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1924 // llvm.is.fpclass(X, fcInf|fcNan)
1925 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1926 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1927 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1928 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1929 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1930 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1931 Value *V;
1932 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1933 Attribute::NoImplicitFloat) &&
1934 Cmp.isEquality() &&
1936 Type *FPType = V->getType()->getScalarType();
1937 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1938 APInt ExponentMask =
1939 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1940 if (*C2 == ExponentMask) {
1941 unsigned Mask = C1.isZero()
1944 if (isICMP_NE)
1945 Mask = ~Mask & fcAllFlags;
1946 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1947 }
1948 }
1949 }
1950
1951 return nullptr;
1952}
1953
1954/// Fold icmp (and X, Y), C.
1957 const APInt &C) {
1958 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1959 return I;
1960
1961 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1962 bool TrueIfNeg;
1963 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1964 // ((X - 1) & ~X) < 0 --> X == 0
1965 // ((X - 1) & ~X) >= 0 --> X != 0
1966 Value *X;
1967 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1968 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1969 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1970 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1971 }
1972 // (X & -X) < 0 --> X == MinSignedC
1973 // (X & -X) > -1 --> X != MinSignedC
1974 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1975 Constant *MinSignedC = ConstantInt::get(
1976 X->getType(),
1977 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1978 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1979 return new ICmpInst(NewPred, X, MinSignedC);
1980 }
1981 }
1982
1983 // TODO: These all require that Y is constant too, so refactor with the above.
1984
1985 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1986 Value *X = And->getOperand(0);
1987 Value *Y = And->getOperand(1);
1988 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1989 if (auto *LI = dyn_cast<LoadInst>(X))
1990 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1991 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, Cmp, C2))
1992 return Res;
1993
1994 if (!Cmp.isEquality())
1995 return nullptr;
1996
1997 // (X & -X) == 0 --> X == 0
1998 // (X & -X) != 0 --> X != 0
1999 // (X & -X) == 1 --> trunc X to i1
2000 // (X & -X) != 1 --> !(trunc X to i1)
2001 // Cmp is == or != by the check above.
2002 Value *MatchedX;
2003 // Match X & -X in either operand order.
2004 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2005 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
2006 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2007 if (C.isZero())
2008 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
2009
2010 // (X & -X) == 1 iff the low bit of X is set.
2011 if (Pred == CmpInst::ICMP_EQ)
2012 return new TruncInst(MatchedX, Cmp.getType());
2013
2014 // The remaining case needs a trunc and not. Require the original and
2015 // to become dead to avoid increasing the instruction count.
2016 if (And->hasOneUse()) {
2017 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
2018 return BinaryOperator::CreateNot(Trunc);
2019 }
2020 }
2021
2022 // X & -C == -C -> X > u ~C
2023 // X & -C != -C -> X <= u ~C
2024 // iff C is a power of 2
2025 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
2026 auto NewPred =
2028 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
2029 }
2030
2031 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2032 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2033 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2034 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2036 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2037 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2038 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2039 Value *And = Builder.CreateAnd(TruncY, X);
2041 }
2042 return BinaryOperator::CreateAnd(TruncY, X);
2043 }
2044
2045 // (icmp eq/ne (and (shl -1, X), Y), 0)
2046 // -> (icmp eq/ne (lshr Y, X), 0)
2047 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2048 // highly unlikely the non-zero case will ever show up in code.
2049 if (C.isZero() &&
2051 m_Value(Y))))) {
2052 Value *LShr = Builder.CreateLShr(Y, X);
2053 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2054 }
2055
2056 // (icmp eq/ne (and (add A, Addend), Msk), C)
2057 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2058 {
2059 Value *A;
2060 const APInt *Addend, *Msk;
2062 m_LowBitMask(Msk)))) &&
2063 C.ule(*Msk)) {
2064 APInt NewComperand = (C - *Addend) & *Msk;
2065 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2066 return new ICmpInst(Pred, MaskA,
2067 ConstantInt::get(MaskA->getType(), NewComperand));
2068 }
2069 }
2070
2071 return nullptr;
2072}
2073
2074/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2076 InstCombiner::BuilderTy &Builder) {
2077 // Are we using xors or subs to bitwise check for a pair or pairs of
2078 // (in)equalities? Convert to a shorter form that has more potential to be
2079 // folded even further.
2080 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2081 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2082 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2083 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2084 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2085 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2087 SmallVector<Value *, 16> WorkList(1, Or);
2088
2089 while (!WorkList.empty()) {
2090 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2091 Value *Lhs, *Rhs;
2092
2093 if (match(OrOperatorArgument,
2094 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2095 CmpValues.emplace_back(Lhs, Rhs);
2096 return;
2097 }
2098
2099 if (match(OrOperatorArgument,
2100 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2101 CmpValues.emplace_back(Lhs, Rhs);
2102 return;
2103 }
2104
2105 WorkList.push_back(OrOperatorArgument);
2106 };
2107
2108 Value *CurrentValue = WorkList.pop_back_val();
2109 Value *OrOperatorLhs, *OrOperatorRhs;
2110
2111 if (!match(CurrentValue,
2112 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2113 return nullptr;
2114 }
2115
2116 MatchOrOperatorArgument(OrOperatorRhs);
2117 MatchOrOperatorArgument(OrOperatorLhs);
2118 }
2119
2120 ICmpInst::Predicate Pred = Cmp.getPredicate();
2121 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2122 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2123 CmpValues.rbegin()->second);
2124
2125 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2126 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2127 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2128 }
2129
2130 return LhsCmp;
2131}
2132
2133/// Fold icmp (or X, Y), C.
2136 const APInt &C) {
2137 ICmpInst::Predicate Pred = Cmp.getPredicate();
2138 if (C.isOne()) {
2139 // icmp slt signum(V) 1 --> icmp slt V, 1
2140 Value *V = nullptr;
2141 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2142 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2143 ConstantInt::get(V->getType(), 1));
2144 }
2145
2146 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2147
2148 // (icmp eq/ne (or disjoint x, C0), C1)
2149 // -> (icmp eq/ne x, C0^C1)
2150 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2151 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2152 Value *NewC =
2153 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2154 return new ICmpInst(Pred, OrOp0, NewC);
2155 }
2156
2157 const APInt *MaskC;
2158 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2159 if (*MaskC == C && (C + 1).isPowerOf2()) {
2160 // X | C == C --> X <=u C
2161 // X | C != C --> X >u C
2162 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2164 return new ICmpInst(Pred, OrOp0, OrOp1);
2165 }
2166
2167 // More general: canonicalize 'equality with set bits mask' to
2168 // 'equality with clear bits mask'.
2169 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2170 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2171 if (Or->hasOneUse()) {
2172 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2173 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2174 return new ICmpInst(Pred, And, NewC);
2175 }
2176 }
2177
2178 // (X | (X-1)) s< 0 --> X s< 1
2179 // (X | (X-1)) s> -1 --> X s> 0
2180 Value *X;
2181 bool TrueIfSigned;
2182 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2184 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2185 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2186 return new ICmpInst(NewPred, X, NewC);
2187 }
2188
2189 const APInt *OrC;
2190 // icmp(X | OrC, C) --> icmp(X, 0)
2191 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2192 switch (Pred) {
2193 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2194 case ICmpInst::ICMP_SLT:
2195 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2196 case ICmpInst::ICMP_SGE:
2197 if (OrC->sge(C))
2198 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2199 break;
2200 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2201 case ICmpInst::ICMP_SLE:
2202 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2203 case ICmpInst::ICMP_SGT:
2204 if (OrC->sgt(C))
2206 ConstantInt::getNullValue(X->getType()));
2207 break;
2208 default:
2209 break;
2210 }
2211 }
2212
2213 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2214 return nullptr;
2215
2216 Value *P, *Q;
2218 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2219 // -> and (icmp eq P, null), (icmp eq Q, null).
2220 Value *CmpP =
2221 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2222 Value *CmpQ =
2223 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2224 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2225 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2226 }
2227
2228 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2229 return replaceInstUsesWith(Cmp, V);
2230
2231 return nullptr;
2232}
2233
2234/// Fold icmp (mul X, Y), C.
2237 const APInt &C) {
2238 ICmpInst::Predicate Pred = Cmp.getPredicate();
2239 Type *MulTy = Mul->getType();
2240 Value *X = Mul->getOperand(0);
2241
2242 // If comparing a square with a constant, try simplifying to comparing square
2243 // roots.
2244 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2245 APInt R = C.sqrtFloor();
2246 bool IsSqr = C == R * R;
2247
2248 // X * X eq/ne C
2249 if (Cmp.isEquality() &&
2250 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2251
2252 // If constant is not a square, eq/ne is false/true respectively
2253 if (!IsSqr)
2254 return replaceInstUsesWith(
2255 Cmp,
2256 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2257
2258 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2259 }
2260
2261 // If the multiply does not wrap
2262 // X * X pred C --> X pred R
2263 if (Mul->hasNoUnsignedWrap()) {
2264
2265 if (IsSqr)
2266 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2267
2268 // If C is not a square, we use floor/ceil of sqrt(C).
2269 //
2270 // If LT or LE, we need R to be an overestimate of sqrt(C),
2271 // then use the strict predicate (LT->LT, LE->LT).
2272 //
2273 // If GT or GE, we need R to be an underestimate of sqrt(C),
2274 // then use the strict predicate (GT->GT, GE->GT).
2275 //
2276 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2277 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2278 ++R;
2279
2280 return new ICmpInst(Cmp.getStrictPredicate(), X,
2281 ConstantInt::get(MulTy, R));
2282 }
2283 }
2284
2285 const APInt *MulC;
2286 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2287 return nullptr;
2288
2289 // If this is a test of the sign bit and the multiply is sign-preserving with
2290 // a constant operand, use the multiply LHS operand instead:
2291 // (X * +MulC) < 0 --> X < 0
2292 // (X * -MulC) < 0 --> X > 0
2293 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2294 if (MulC->isNegative())
2295 Pred = ICmpInst::getSwappedPredicate(Pred);
2296 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2297 }
2298
2299 if (MulC->isZero())
2300 return nullptr;
2301
2302 // If the multiply does not wrap or the constant is odd, try to divide the
2303 // compare constant by the multiplication factor.
2304 if (Cmp.isEquality()) {
2305 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2306 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2307 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2308 return new ICmpInst(Pred, X, NewC);
2309 }
2310
2311 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2312 // correct to transform if MulC * N == C including overflow. I.e with i8
2313 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2314 // miss that case.
2315 if (C.urem(*MulC).isZero()) {
2316 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2317 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2318 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2319 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2320 return new ICmpInst(Pred, X, NewC);
2321 }
2322 }
2323 }
2324
2325 // With a matching no-overflow guarantee, fold the constants:
2326 // (X * MulC) < C --> X < (C / MulC)
2327 // (X * MulC) > C --> X > (C / MulC)
2328 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2329 Constant *NewC = nullptr;
2330 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2331 // MININT / -1 --> overflow.
2332 if (C.isMinSignedValue() && MulC->isAllOnes())
2333 return nullptr;
2334 if (MulC->isNegative())
2335 Pred = ICmpInst::getSwappedPredicate(Pred);
2336
2337 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2338 NewC = ConstantInt::get(
2340 } else {
2341 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2342 "Unexpected predicate");
2343 NewC = ConstantInt::get(
2345 }
2346 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2347 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2348 NewC = ConstantInt::get(
2350 } else {
2351 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2352 "Unexpected predicate");
2353 NewC = ConstantInt::get(
2355 }
2356 }
2357
2358 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2359}
2360
2361/// Fold icmp (shl nuw C2, Y), C.
2363 const APInt &C) {
2364 Value *Y;
2365 const APInt *C2;
2366 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2367 return nullptr;
2368
2369 Type *ShiftType = Shl->getType();
2370 unsigned TypeBits = C.getBitWidth();
2371 ICmpInst::Predicate Pred = Cmp.getPredicate();
2372 if (Cmp.isUnsigned()) {
2373 if (C2->isZero() || C2->ugt(C))
2374 return nullptr;
2375 APInt Div, Rem;
2376 APInt::udivrem(C, *C2, Div, Rem);
2377 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2378
2379 // (1 << Y) pred C -> Y pred Log2(C)
2380 if (!CIsPowerOf2) {
2381 // (1 << Y) < 30 -> Y <= 4
2382 // (1 << Y) <= 30 -> Y <= 4
2383 // (1 << Y) >= 30 -> Y > 4
2384 // (1 << Y) > 30 -> Y > 4
2385 if (Pred == ICmpInst::ICMP_ULT)
2386 Pred = ICmpInst::ICMP_ULE;
2387 else if (Pred == ICmpInst::ICMP_UGE)
2388 Pred = ICmpInst::ICMP_UGT;
2389 }
2390
2391 unsigned CLog2 = Div.logBase2();
2392 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2393 } else if (Cmp.isSigned() && C2->isOne()) {
2394 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2395 // (1 << Y) > 0 -> Y != 31
2396 // (1 << Y) > C -> Y != 31 if C is negative.
2397 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2398 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2399
2400 // (1 << Y) < 0 -> Y == 31
2401 // (1 << Y) < 1 -> Y == 31
2402 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2403 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2404 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2405 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2406 }
2407
2408 return nullptr;
2409}
2410
2411/// Fold icmp (shl X, Y), C.
2413 BinaryOperator *Shl,
2414 const APInt &C) {
2415 const APInt *ShiftVal;
2416 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2417 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2418
2419 ICmpInst::Predicate Pred = Cmp.getPredicate();
2420 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2421 // -> (icmp pred X, Csle0)
2422 //
2423 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2424 // so X's must be what is used.
2425 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2426 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2427
2428 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2429 // -> (icmp eq/ne X, 0)
2430 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2431 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2432 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2433
2434 // (icmp slt (shl nsw X, Y), 0/1)
2435 // -> (icmp slt X, 0/1)
2436 // (icmp sgt (shl nsw X, Y), 0/-1)
2437 // -> (icmp sgt X, 0/-1)
2438 //
2439 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2440 if (Shl->hasNoSignedWrap() &&
2441 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2442 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2443 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2444
2445 const APInt *ShiftAmt;
2446 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2447 return foldICmpShlLHSC(Cmp, Shl, C);
2448
2449 // Check that the shift amount is in range. If not, don't perform undefined
2450 // shifts. When the shift is visited, it will be simplified.
2451 unsigned TypeBits = C.getBitWidth();
2452 if (ShiftAmt->uge(TypeBits))
2453 return nullptr;
2454
2455 Value *X = Shl->getOperand(0);
2456 Type *ShType = Shl->getType();
2457
2458 // NSW guarantees that we are only shifting out sign bits from the high bits,
2459 // so we can ASHR the compare constant without needing a mask and eliminate
2460 // the shift.
2461 if (Shl->hasNoSignedWrap()) {
2462 if (Pred == ICmpInst::ICMP_SGT) {
2463 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2464 APInt ShiftedC = C.ashr(*ShiftAmt);
2465 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2466 }
2467 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2468 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2469 APInt ShiftedC = C.ashr(*ShiftAmt);
2470 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2471 }
2472 if (Pred == ICmpInst::ICMP_SLT) {
2473 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2474 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2475 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2476 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2477 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2478 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2479 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2480 }
2481 }
2482
2483 // NUW guarantees that we are only shifting out zero bits from the high bits,
2484 // so we can LSHR the compare constant without needing a mask and eliminate
2485 // the shift.
2486 if (Shl->hasNoUnsignedWrap()) {
2487 if (Pred == ICmpInst::ICMP_UGT) {
2488 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2489 APInt ShiftedC = C.lshr(*ShiftAmt);
2490 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2491 }
2492 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2493 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2494 APInt ShiftedC = C.lshr(*ShiftAmt);
2495 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2496 }
2497 if (Pred == ICmpInst::ICMP_ULT) {
2498 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2499 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2500 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2501 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2502 assert(C.ugt(0) && "ult 0 should have been eliminated");
2503 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2504 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2505 }
2506 }
2507
2508 if (Cmp.isEquality() && Shl->hasOneUse()) {
2509 // Strength-reduce the shift into an 'and'.
2510 Constant *Mask = ConstantInt::get(
2511 ShType,
2512 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2513 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2514 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2515 return new ICmpInst(Pred, And, LShrC);
2516 }
2517
2518 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2519 bool TrueIfSigned = false;
2520 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2521 // (X << 31) <s 0 --> (X & 1) != 0
2522 Constant *Mask = ConstantInt::get(
2523 ShType,
2524 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2525 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2526 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2527 And, Constant::getNullValue(ShType));
2528 }
2529
2530 // Simplify 'shl' inequality test into 'and' equality test.
2531 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2532 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2533 if ((C + 1).isPowerOf2() &&
2534 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2535 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2536 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2538 And, Constant::getNullValue(ShType));
2539 }
2540 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2541 if (C.isPowerOf2() &&
2542 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2543 Value *And =
2544 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2545 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2547 And, Constant::getNullValue(ShType));
2548 }
2549 }
2550
2551 // Transform (icmp pred iM (shl iM %v, N), C)
2552 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2553 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2554 // This enables us to get rid of the shift in favor of a trunc that may be
2555 // free on the target. It has the additional benefit of comparing to a
2556 // smaller constant that may be more target-friendly.
2557 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2558 if (Shl->hasOneUse() && Amt != 0 &&
2559 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2560 ICmpInst::Predicate CmpPred = Pred;
2561 APInt RHSC = C;
2562
2563 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2564 // Try the flipped strictness predicate.
2565 // e.g.:
2566 // icmp ult i64 (shl X, 32), 8589934593 ->
2567 // icmp ule i64 (shl X, 32), 8589934592 ->
2568 // icmp ule i32 (trunc X, i32), 2 ->
2569 // icmp ult i32 (trunc X, i32), 3
2570 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2571 Pred, ConstantInt::get(ShType->getContext(), C))) {
2572 CmpPred = FlippedStrictness->first;
2573 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2574 }
2575 }
2576
2577 if (RHSC.countr_zero() >= Amt) {
2578 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2579 Constant *NewC =
2580 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2581 return new ICmpInst(CmpPred,
2582 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2583 Shl->hasNoSignedWrap()),
2584 NewC);
2585 }
2586 }
2587
2588 return nullptr;
2589}
2590
2591/// Fold icmp ({al}shr X, Y), C.
2593 BinaryOperator *Shr,
2594 const APInt &C) {
2595 // An exact shr only shifts out zero bits, so:
2596 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2597 Value *X = Shr->getOperand(0);
2598 CmpInst::Predicate Pred = Cmp.getPredicate();
2599 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2600 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2601
2602 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2603 const APInt *ShiftValC;
2604 if (match(X, m_APInt(ShiftValC))) {
2605 if (Cmp.isEquality())
2606 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2607
2608 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2609 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2610 bool TrueIfSigned;
2611 if (!IsAShr && ShiftValC->isNegative() &&
2612 isSignBitCheck(Pred, C, TrueIfSigned))
2613 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2614 Shr->getOperand(1),
2615 ConstantInt::getNullValue(X->getType()));
2616
2617 // If the shifted constant is a power-of-2, test the shift amount directly:
2618 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2619 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2620 if (!IsAShr && ShiftValC->isPowerOf2() &&
2621 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2622 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2623 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2624 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2625
2626 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2627 unsigned ShiftLZ = ShiftValC->countl_zero();
2628 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2629 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2630 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2631 }
2632 }
2633
2634 const APInt *ShiftAmtC;
2635 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2636 return nullptr;
2637
2638 // Check that the shift amount is in range. If not, don't perform undefined
2639 // shifts. When the shift is visited it will be simplified.
2640 unsigned TypeBits = C.getBitWidth();
2641 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2642 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2643 return nullptr;
2644
2645 bool IsExact = Shr->isExact();
2646 Type *ShrTy = Shr->getType();
2647 // TODO: If we could guarantee that InstSimplify would handle all of the
2648 // constant-value-based preconditions in the folds below, then we could assert
2649 // those conditions rather than checking them. This is difficult because of
2650 // undef/poison (PR34838).
2651 if (IsAShr && Shr->hasOneUse()) {
2652 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2653 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2654 // When C - 1 is a power of two and the transform can be legally
2655 // performed, prefer this form so the produced constant is close to a
2656 // power of two.
2657 // icmp slt/ult (ashr exact X, ShAmtC), C
2658 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2659 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2660 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2661 }
2662 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2663 // When ShAmtC can be shifted losslessly:
2664 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2665 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2666 APInt ShiftedC = C.shl(ShAmtVal);
2667 if (ShiftedC.ashr(ShAmtVal) == C)
2668 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2669 }
2670 if (Pred == CmpInst::ICMP_SGT) {
2671 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2672 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2673 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2674 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2675 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2676 }
2677 if (Pred == CmpInst::ICMP_UGT) {
2678 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2679 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2680 // clause accounts for that pattern.
2681 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2682 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2683 (C + 1).shl(ShAmtVal).isMinSignedValue())
2684 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2685 }
2686
2687 // If the compare constant has significant bits above the lowest sign-bit,
2688 // then convert an unsigned cmp to a test of the sign-bit:
2689 // (ashr X, ShiftC) u> C --> X s< 0
2690 // (ashr X, ShiftC) u< C --> X s> -1
2691 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2692 if (Pred == CmpInst::ICMP_UGT) {
2693 return new ICmpInst(CmpInst::ICMP_SLT, X,
2695 }
2696 if (Pred == CmpInst::ICMP_ULT) {
2697 return new ICmpInst(CmpInst::ICMP_SGT, X,
2699 }
2700 }
2701 } else if (!IsAShr) {
2702 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2703 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2704 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2705 APInt ShiftedC = C.shl(ShAmtVal);
2706 if (ShiftedC.lshr(ShAmtVal) == C)
2707 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2708 }
2709 if (Pred == CmpInst::ICMP_UGT) {
2710 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2711 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2712 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2713 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2714 }
2715 }
2716
2717 if (!Cmp.isEquality())
2718 return nullptr;
2719
2720 // Handle equality comparisons of shift-by-constant.
2721
2722 // If the comparison constant changes with the shift, the comparison cannot
2723 // succeed (bits of the comparison constant cannot match the shifted value).
2724 // This should be known by InstSimplify and already be folded to true/false.
2725 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2726 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2727 "Expected icmp+shr simplify did not occur.");
2728
2729 // If the bits shifted out are known zero, compare the unshifted value:
2730 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2731 if (Shr->isExact())
2732 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2733
2734 if (Shr->hasOneUse()) {
2735 // Canonicalize the shift into an 'and':
2736 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2737 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2738 Constant *Mask = ConstantInt::get(ShrTy, Val);
2739 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2740 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2741 }
2742
2743 return nullptr;
2744}
2745
2747 BinaryOperator *SRem,
2748 const APInt &C) {
2749 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2750 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2751 // Canonicalize unsigned predicates to signed:
2752 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2753 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2754 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2755 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2756
2757 const APInt *DivisorC;
2758 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2759 return nullptr;
2760 if (DivisorC->isZero())
2761 return nullptr;
2762
2763 APInt NormalizedC = C;
2764 if (Pred == ICmpInst::ICMP_ULT) {
2765 assert(!NormalizedC.isZero() &&
2766 "ult X, 0 should have been simplified already.");
2767 --NormalizedC;
2768 }
2769 if (C.isNegative())
2770 NormalizedC.flipAllBits();
2771 if (!NormalizedC.uge(DivisorC->abs() - 1))
2772 return nullptr;
2773
2774 Type *Ty = SRem->getType();
2775 if (Pred == ICmpInst::ICMP_UGT)
2776 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2778 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2780 }
2781 // Match an 'is positive' or 'is negative' comparison of remainder by a
2782 // constant power-of-2 value:
2783 // (X % pow2C) sgt/slt 0
2784 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2785 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2786 return nullptr;
2787
2788 // TODO: The one-use check is standard because we do not typically want to
2789 // create longer instruction sequences, but this might be a special-case
2790 // because srem is not good for analysis or codegen.
2791 if (!SRem->hasOneUse())
2792 return nullptr;
2793
2794 const APInt *DivisorC;
2795 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2796 return nullptr;
2797
2798 // For cmp_sgt/cmp_slt only zero valued C is handled.
2799 // For cmp_eq/cmp_ne only positive valued C is handled.
2800 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2801 !C.isZero()) ||
2802 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2803 !C.isStrictlyPositive()))
2804 return nullptr;
2805
2806 // Mask off the sign bit and the modulo bits (low-bits).
2807 Type *Ty = SRem->getType();
2808 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2809 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2810 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2811
2812 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2813 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2814
2815 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2816 // bit is set. Example:
2817 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2818 if (Pred == ICmpInst::ICMP_SGT)
2820
2821 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2822 // bit is set. Example:
2823 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2824 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2825}
2826
2827/// Fold icmp (udiv X, Y), C.
2829 BinaryOperator *UDiv,
2830 const APInt &C) {
2831 ICmpInst::Predicate Pred = Cmp.getPredicate();
2832 Value *X = UDiv->getOperand(0);
2833 Value *Y = UDiv->getOperand(1);
2834 Type *Ty = UDiv->getType();
2835
2836 const APInt *C2;
2837 if (!match(X, m_APInt(C2)))
2838 return nullptr;
2839
2840 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2841
2842 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2843 if (Pred == ICmpInst::ICMP_UGT) {
2844 assert(!C.isMaxValue() &&
2845 "icmp ugt X, UINT_MAX should have been simplified already.");
2846 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2847 ConstantInt::get(Ty, C2->udiv(C + 1)));
2848 }
2849
2850 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2851 if (Pred == ICmpInst::ICMP_ULT) {
2852 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2853 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2854 ConstantInt::get(Ty, C2->udiv(C)));
2855 }
2856
2857 return nullptr;
2858}
2859
2860/// Fold icmp ({su}div X, Y), C.
2862 BinaryOperator *Div,
2863 const APInt &C) {
2864 ICmpInst::Predicate Pred = Cmp.getPredicate();
2865 Value *X = Div->getOperand(0);
2866 Value *Y = Div->getOperand(1);
2867 Type *Ty = Div->getType();
2868 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2869
2870 // If unsigned division and the compare constant is bigger than
2871 // UMAX/2 (negative), there's only one pair of values that satisfies an
2872 // equality check, so eliminate the division:
2873 // (X u/ Y) == C --> (X == C) && (Y == 1)
2874 // (X u/ Y) != C --> (X != C) || (Y != 1)
2875 // Similarly, if signed division and the compare constant is exactly SMIN:
2876 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2877 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2878 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2879 (!DivIsSigned || C.isMinSignedValue())) {
2880 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2881 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2882 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2883 return BinaryOperator::Create(Logic, XBig, YOne);
2884 }
2885
2886 // Fold: icmp pred ([us]div X, C2), C -> range test
2887 // Fold this div into the comparison, producing a range check.
2888 // Determine, based on the divide type, what the range is being
2889 // checked. If there is an overflow on the low or high side, remember
2890 // it, otherwise compute the range [low, hi) bounding the new value.
2891 // See: InsertRangeTest above for the kinds of replacements possible.
2892 const APInt *C2;
2893 if (!match(Y, m_APInt(C2)))
2894 return nullptr;
2895
2896 // FIXME: If the operand types don't match the type of the divide
2897 // then don't attempt this transform. The code below doesn't have the
2898 // logic to deal with a signed divide and an unsigned compare (and
2899 // vice versa). This is because (x /s C2) <s C produces different
2900 // results than (x /s C2) <u C or (x /u C2) <s C or even
2901 // (x /u C2) <u C. Simply casting the operands and result won't
2902 // work. :( The if statement below tests that condition and bails
2903 // if it finds it.
2904 // However, when the divisor is a positive constant and the dividend is
2905 // known non-negative, sdiv is equivalent to udiv, so we can lower
2906 // DivIsSigned and proceed through the unsigned path.
2907 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2908 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2909 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2910 return nullptr;
2911 DivIsSigned = false;
2912 }
2913
2914 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2915 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2916 // division-by-constant cases should be present, we can not assert that they
2917 // have happened before we reach this icmp instruction.
2918 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2919 return nullptr;
2920
2921 // Compute Prod = C * C2. We are essentially solving an equation of
2922 // form X / C2 = C. We solve for X by multiplying C2 and C.
2923 // By solving for X, we can turn this into a range check instead of computing
2924 // a divide.
2925 APInt Prod = C * *C2;
2926
2927 // Determine if the product overflows by seeing if the product is not equal to
2928 // the divide. Make sure we do the same kind of divide as in the LHS
2929 // instruction that we're folding.
2930 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2931
2932 // If the division is known to be exact, then there is no remainder from the
2933 // divide, so the covered range size is unit, otherwise it is the divisor.
2934 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2935
2936 // Figure out the interval that is being checked. For example, a comparison
2937 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2938 // Compute this interval based on the constants involved and the signedness of
2939 // the compare/divide. This computes a half-open interval, keeping track of
2940 // whether either value in the interval overflows. After analysis each
2941 // overflow variable is set to 0 if it's corresponding bound variable is valid
2942 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2943 int LoOverflow = 0, HiOverflow = 0;
2944 APInt LoBound, HiBound;
2945
2946 if (!DivIsSigned) { // udiv
2947 // e.g. X/5 op 3 --> [15, 20)
2948 LoBound = Prod;
2949 HiOverflow = LoOverflow = ProdOV;
2950 if (!HiOverflow) {
2951 // If this is not an exact divide, then many values in the range collapse
2952 // to the same result value.
2953 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2954 }
2955 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2956 if (C.isZero()) { // (X / pos) op 0
2957 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2958 LoBound = -(RangeSize - 1);
2959 HiBound = RangeSize;
2960 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2961 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2962 HiOverflow = LoOverflow = ProdOV;
2963 if (!HiOverflow)
2964 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2965 } else { // (X / pos) op neg
2966 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2967 HiBound = Prod + 1;
2968 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2969 if (!LoOverflow) {
2970 APInt DivNeg = -RangeSize;
2971 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2972 }
2973 }
2974 } else if (C2->isNegative()) { // Divisor is < 0.
2975 if (Div->isExact())
2976 RangeSize.negate();
2977 if (C.isZero()) { // (X / neg) op 0
2978 // e.g. X/-5 op 0 --> [-4, 5)
2979 LoBound = RangeSize + 1;
2980 HiBound = -RangeSize;
2981 if (HiBound == *C2) { // -INTMIN = INTMIN
2982 HiOverflow = 1; // [INTMIN+1, overflow)
2983 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2984 }
2985 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2986 // e.g. X/-5 op 3 --> [-19, -14)
2987 HiBound = Prod + 1;
2988 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2989 if (!LoOverflow)
2990 LoOverflow =
2991 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2992 } else { // (X / neg) op neg
2993 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2994 LoOverflow = HiOverflow = ProdOV;
2995 if (!HiOverflow)
2996 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2997 }
2998
2999 // Dividing by a negative swaps the condition. LT <-> GT
3000 Pred = ICmpInst::getSwappedPredicate(Pred);
3001 }
3002
3003 switch (Pred) {
3004 default:
3005 llvm_unreachable("Unhandled icmp predicate!");
3006 case ICmpInst::ICMP_EQ:
3007 if (LoOverflow && HiOverflow)
3008 return replaceInstUsesWith(Cmp, Builder.getFalse());
3009 if (HiOverflow)
3010 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3011 X, ConstantInt::get(Ty, LoBound));
3012 if (LoOverflow)
3013 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3014 X, ConstantInt::get(Ty, HiBound));
3015 return replaceInstUsesWith(
3016 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
3017 case ICmpInst::ICMP_NE:
3018 if (LoOverflow && HiOverflow)
3019 return replaceInstUsesWith(Cmp, Builder.getTrue());
3020 if (HiOverflow)
3021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3022 X, ConstantInt::get(Ty, LoBound));
3023 if (LoOverflow)
3024 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3025 X, ConstantInt::get(Ty, HiBound));
3026 return replaceInstUsesWith(
3027 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
3028 case ICmpInst::ICMP_ULT:
3029 case ICmpInst::ICMP_SLT:
3030 if (LoOverflow == +1) // Low bound is greater than input range.
3031 return replaceInstUsesWith(Cmp, Builder.getTrue());
3032 if (LoOverflow == -1) // Low bound is less than input range.
3033 return replaceInstUsesWith(Cmp, Builder.getFalse());
3034 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3035 case ICmpInst::ICMP_UGT:
3036 case ICmpInst::ICMP_SGT:
3037 if (HiOverflow == +1) // High bound greater than input range.
3038 return replaceInstUsesWith(Cmp, Builder.getFalse());
3039 if (HiOverflow == -1) // High bound less than input range.
3040 return replaceInstUsesWith(Cmp, Builder.getTrue());
3041 if (Pred == ICmpInst::ICMP_UGT)
3042 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3043 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3044 }
3045
3046 return nullptr;
3047}
3048
3049/// Fold icmp (sub X, Y), C.
3052 const APInt &C) {
3053 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3054 ICmpInst::Predicate Pred = Cmp.getPredicate();
3055 Type *Ty = Sub->getType();
3056
3057 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3058 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3059 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3060 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3061 const APInt *D;
3062 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3063 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3064 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3065 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3066 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3067 }
3068
3069 // (SubC - Y) == C) --> Y == (SubC - C)
3070 // (SubC - Y) != C) --> Y != (SubC - C)
3071 Constant *SubC;
3072 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3073 return new ICmpInst(Pred, Y,
3074 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3075 }
3076
3077 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3078 const APInt *C2;
3079 APInt SubResult;
3080 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3081 bool HasNSW = Sub->hasNoSignedWrap();
3082 bool HasNUW = Sub->hasNoUnsignedWrap();
3083 if (match(X, m_APInt(C2)) &&
3084 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3085 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3086 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3087
3088 // X - Y == 0 --> X == Y.
3089 // X - Y != 0 --> X != Y.
3090 // TODO: We allow this with multiple uses as long as the other uses are not
3091 // in phis. The phi use check is guarding against a codegen regression
3092 // for a loop test. If the backend could undo this (and possibly
3093 // subsequent transforms), we would not need this hack.
3094 if (Cmp.isEquality() && C.isZero() &&
3095 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3096 return new ICmpInst(Pred, X, Y);
3097
3098 // The following transforms are only worth it if the only user of the subtract
3099 // is the icmp.
3100 // TODO: This is an artificial restriction for all of the transforms below
3101 // that only need a single replacement icmp. Can these use the phi test
3102 // like the transform above here?
3103 if (!Sub->hasOneUse())
3104 return nullptr;
3105
3106 if (Sub->hasNoSignedWrap()) {
3107 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3108 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3109 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3110
3111 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3112 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3113 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3114
3115 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3116 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3117 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3118
3119 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3120 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3121 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3122 }
3123
3124 if (!match(X, m_APInt(C2)))
3125 return nullptr;
3126
3127 // C2 - Y <u C -> (Y | (C - 1)) == C2
3128 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3129 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3130 (*C2 & (C - 1)) == (C - 1))
3131 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3132
3133 // C2 - Y >u C -> (Y | C) != C2
3134 // iff C2 & C == C and C + 1 is a power of 2
3135 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3136 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3137
3138 // We have handled special cases that reduce.
3139 // Canonicalize any remaining sub to add as:
3140 // (C2 - Y) > C --> (Y + ~C2) < ~C
3141 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3142 HasNUW, HasNSW);
3143 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3144}
3145
3146static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3147 Value *Op1, IRBuilderBase &Builder,
3148 bool HasOneUse) {
3149 auto FoldConstant = [&](bool Val) {
3150 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3151 if (Op0->getType()->isVectorTy())
3153 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3154 return Res;
3155 };
3156
3157 switch (Table.to_ulong()) {
3158 case 0: // 0 0 0 0
3159 return FoldConstant(false);
3160 case 1: // 0 0 0 1
3161 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3162 case 2: // 0 0 1 0
3163 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3164 case 3: // 0 0 1 1
3165 return Builder.CreateNot(Op0);
3166 case 4: // 0 1 0 0
3167 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3168 case 5: // 0 1 0 1
3169 return Builder.CreateNot(Op1);
3170 case 6: // 0 1 1 0
3171 return Builder.CreateXor(Op0, Op1);
3172 case 7: // 0 1 1 1
3173 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3174 case 8: // 1 0 0 0
3175 return Builder.CreateAnd(Op0, Op1);
3176 case 9: // 1 0 0 1
3177 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3178 case 10: // 1 0 1 0
3179 return Op1;
3180 case 11: // 1 0 1 1
3181 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3182 case 12: // 1 1 0 0
3183 return Op0;
3184 case 13: // 1 1 0 1
3185 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3186 case 14: // 1 1 1 0
3187 return Builder.CreateOr(Op0, Op1);
3188 case 15: // 1 1 1 1
3189 return FoldConstant(true);
3190 default:
3191 llvm_unreachable("Invalid Operation");
3192 }
3193 return nullptr;
3194}
3195
3197 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3198 Value *A, *B;
3199 Constant *C1, *C2, *C3, *C4;
3200 if (!match(BO->getOperand(0),
3202 !match(BO->getOperand(1),
3204 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3205 return nullptr;
3206
3207 std::bitset<4> Table;
3208 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3209 Constant *L = First ? C1 : C2;
3210 Constant *R = Second ? C3 : C4;
3211 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3212 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3213 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3214 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3215 }
3216 return std::nullopt;
3217 };
3218
3219 for (unsigned I = 0; I < 4; ++I) {
3220 bool First = (I >> 1) & 1;
3221 bool Second = I & 1;
3222 if (auto Res = ComputeTable(First, Second))
3223 Table[I] = *Res;
3224 else
3225 return nullptr;
3226 }
3227
3228 // Synthesize optimal logic.
3229 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3230 return replaceInstUsesWith(Cmp, Cond);
3231 return nullptr;
3232}
3233
3234/// Fold icmp (add X, Y), C.
3237 const APInt &C) {
3238 Value *Y = Add->getOperand(1);
3239 Value *X = Add->getOperand(0);
3240 const CmpPredicate Pred = Cmp.getCmpPredicate();
3241
3242 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3243 // when C <= (1 << ShAmtC).
3244 const APInt *ShAmtC;
3245 Value *A;
3246 unsigned BitWidth = C.getBitWidth();
3247 if (Pred == ICmpInst::ICMP_ULT &&
3248 match(Add,
3249 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3250 ShAmtC->ult(BitWidth) &&
3251 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3252 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3253
3254 const APInt *C2;
3255 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3256 return nullptr;
3257
3258 // Fold icmp pred (add X, C2), C.
3259 Type *Ty = Add->getType();
3260
3261 // If the add does not wrap, we can always adjust the compare by subtracting
3262 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3263 // have been canonicalized to SGT/SLT/UGT/ULT.
3264 if (Add->hasNoUnsignedWrap() &&
3265 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3266 bool Overflow;
3267 APInt NewC = C.usub_ov(*C2, Overflow);
3268 // If there is overflow, the result must be true or false.
3269 if (!Overflow)
3270 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3271 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3272 }
3273
3274 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3275
3276 if (Add->hasNoSignedWrap() &&
3277 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3278 bool Overflow;
3279 APInt NewC = C.ssub_ov(*C2, Overflow);
3280 if (!Overflow)
3281 // icmp samesign ugt/ult (add nsw X, C2), C
3282 // -> icmp sgt/slt X, (C - C2)
3283 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3284 }
3285
3286 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3287 C.isNonNegative() && (C - *C2).isNonNegative() &&
3288 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3289 .add(*C2)
3290 .isAllNonNegative())
3291 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3292 ConstantInt::get(Ty, C - *C2));
3293
3294 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3295 const APInt &Upper = CR.getUpper();
3296 const APInt &Lower = CR.getLower();
3297 if (Cmp.isSigned()) {
3298 if (Lower.isSignMask())
3299 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3300 if (Upper.isSignMask())
3301 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3302 } else {
3303 if (Lower.isMinValue())
3304 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3305 if (Upper.isMinValue())
3306 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3307 }
3308
3309 // This set of folds is intentionally placed after folds that use no-wrapping
3310 // flags because those folds are likely better for later analysis/codegen.
3311 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3312 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3313
3314 // Fold compare with offset to opposite sign compare if it eliminates offset:
3315 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3316 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3317 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3318
3319 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3320 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3321 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3322
3323 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3324 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3325 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3326
3327 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3328 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3329 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3330
3331 // (X + -1) <u C --> X <=u C (if X is never null)
3332 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3333 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3334 if (llvm::isKnownNonZero(X, Q))
3335 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3336 }
3337
3338 if (!Add->hasOneUse())
3339 return nullptr;
3340
3341 // X+C <u C2 -> (X & -C2) == C
3342 // iff C & (C2-1) == 0
3343 // C2 is a power of 2
3344 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3345 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3347
3348 // X+C2 <u C -> (X & C) == 2C
3349 // iff C == -(C2)
3350 // C2 is a power of 2
3351 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3352 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3353 ConstantInt::get(Ty, C * 2));
3354
3355 // X+C >u C2 -> (X & ~C2) != C
3356 // iff C & C2 == 0
3357 // C2+1 is a power of 2
3358 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3359 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3361
3362 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3363 // to the ult form.
3364 // X+C2 >u C -> X+(C2-C-1) <u ~C
3365 if (Pred == ICmpInst::ICMP_UGT)
3366 return new ICmpInst(ICmpInst::ICMP_ULT,
3367 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3368 ConstantInt::get(Ty, ~C));
3369
3370 // zext(V) + C2 pred C -> V + C3 pred' C4
3371 Value *V;
3372 if (match(X, m_ZExt(m_Value(V)))) {
3373 Type *NewCmpTy = V->getType();
3374 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3375 if (shouldChangeType(Ty, NewCmpTy)) {
3376 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3377 CmpInst::Predicate EquivPred;
3378 APInt EquivInt;
3379 APInt EquivOffset;
3380
3381 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3382 return new ICmpInst(
3383 EquivPred,
3384 EquivOffset.isZero()
3385 ? V
3386 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3387 ConstantInt::get(NewCmpTy, EquivInt));
3388 }
3389 }
3390
3391 return nullptr;
3392}
3393
3395 Value *&RHS, ConstantInt *&Less,
3396 ConstantInt *&Equal,
3397 ConstantInt *&Greater) {
3398 // TODO: Generalize this to work with other comparison idioms or ensure
3399 // they get canonicalized into this form.
3400
3401 // select i1 (a == b),
3402 // i32 Equal,
3403 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3404 // where Equal, Less and Greater are placeholders for any three constants.
3405 CmpPredicate PredA;
3406 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3407 !ICmpInst::isEquality(PredA))
3408 return false;
3409 Value *EqualVal = SI->getTrueValue();
3410 Value *UnequalVal = SI->getFalseValue();
3411 // We still can get non-canonical predicate here, so canonicalize.
3412 if (PredA == ICmpInst::ICMP_NE)
3413 std::swap(EqualVal, UnequalVal);
3414 if (!match(EqualVal, m_ConstantInt(Equal)))
3415 return false;
3416 CmpPredicate PredB;
3417 Value *LHS2, *RHS2;
3418 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3419 m_ConstantInt(Less), m_ConstantInt(Greater))))
3420 return false;
3421 // We can get predicate mismatch here, so canonicalize if possible:
3422 // First, ensure that 'LHS' match.
3423 if (LHS2 != LHS) {
3424 // x sgt y <--> y slt x
3425 std::swap(LHS2, RHS2);
3426 PredB = ICmpInst::getSwappedPredicate(PredB);
3427 }
3428 if (LHS2 != LHS)
3429 return false;
3430 // We also need to canonicalize 'RHS'.
3431 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3432 // x sgt C-1 <--> x sge C <--> not(x slt C)
3433 auto FlippedStrictness =
3435 if (!FlippedStrictness)
3436 return false;
3437 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3438 "basic correctness failure");
3439 RHS2 = FlippedStrictness->second;
3440 // And kind-of perform the result swap.
3441 std::swap(Less, Greater);
3442 PredB = ICmpInst::ICMP_SLT;
3443 }
3444 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3445}
3446
3449 ConstantInt *C) {
3450
3451 assert(C && "Cmp RHS should be a constant int!");
3452 // If we're testing a constant value against the result of a three way
3453 // comparison, the result can be expressed directly in terms of the
3454 // original values being compared. Note: We could possibly be more
3455 // aggressive here and remove the hasOneUse test. The original select is
3456 // really likely to simplify or sink when we remove a test of the result.
3457 Value *OrigLHS, *OrigRHS;
3458 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3459 if (Cmp.hasOneUse() &&
3460 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3461 C3GreaterThan)) {
3462 assert(C1LessThan && C2Equal && C3GreaterThan);
3463
3464 bool TrueWhenLessThan = ICmpInst::compare(
3465 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3466 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3467 Cmp.getPredicate());
3468 bool TrueWhenGreaterThan = ICmpInst::compare(
3469 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3470
3471 // This generates the new instruction that will replace the original Cmp
3472 // Instruction. Instead of enumerating the various combinations when
3473 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3474 // false, we rely on chaining of ORs and future passes of InstCombine to
3475 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3476
3477 // When none of the three constants satisfy the predicate for the RHS (C),
3478 // the entire original Cmp can be simplified to a false.
3479 Value *Cond = Builder.getFalse();
3480 if (TrueWhenLessThan)
3481 Cond = Builder.CreateOr(
3482 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3483 if (TrueWhenEqual)
3484 Cond = Builder.CreateOr(
3485 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3486 if (TrueWhenGreaterThan)
3487 Cond = Builder.CreateOr(
3488 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3489
3490 return replaceInstUsesWith(Cmp, Cond);
3491 }
3492 return nullptr;
3493}
3494
3496 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3497 if (!Bitcast)
3498 return nullptr;
3499
3500 ICmpInst::Predicate Pred = Cmp.getPredicate();
3501 Value *Op1 = Cmp.getOperand(1);
3502 Value *BCSrcOp = Bitcast->getOperand(0);
3503 Type *SrcType = Bitcast->getSrcTy();
3504 Type *DstType = Bitcast->getType();
3505
3506 // Make sure the bitcast doesn't change between scalar and vector and
3507 // doesn't change the number of vector elements.
3508 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3509 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3510 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3511 Value *X;
3512 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3513 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3514 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3515 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3516 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3517 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3518 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3519 match(Op1, m_Zero()))
3520 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3521
3522 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3523 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3524 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3525
3526 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3527 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3528 return new ICmpInst(Pred, X,
3529 ConstantInt::getAllOnesValue(X->getType()));
3530 }
3531
3532 // Zero-equality checks are preserved through unsigned floating-point casts:
3533 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3534 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3535 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3536 if (Cmp.isEquality() && match(Op1, m_Zero()))
3537 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3538
3539 const APInt *C;
3540 bool TrueIfSigned;
3541 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3542 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3543 // the FP extend/truncate because that cast does not change the sign-bit.
3544 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3545 // The sign-bit is always the most significant bit in those types.
3546 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3547 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3548 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3549 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3550 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3551 Type *XType = X->getType();
3552
3553 // We can't currently handle Power style floating point operations here.
3554 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3555 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3556 if (auto *XVTy = dyn_cast<VectorType>(XType))
3557 NewType = VectorType::get(NewType, XVTy->getElementCount());
3558 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3559 if (TrueIfSigned)
3560 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3561 ConstantInt::getNullValue(NewType));
3562 else
3563 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3565 }
3566 }
3567
3568 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3569 Type *FPType = SrcType->getScalarType();
3570 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3571 Attribute::NoImplicitFloat) &&
3572 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3573 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3574 if (Mask & (fcInf | fcZero)) {
3575 if (Pred == ICmpInst::ICMP_NE)
3576 Mask = ~Mask;
3577 return replaceInstUsesWith(Cmp,
3578 Builder.createIsFPClass(BCSrcOp, Mask));
3579 }
3580 }
3581 }
3582 }
3583
3584 const APInt *C;
3585 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3586 !SrcType->isIntOrIntVectorTy())
3587 return nullptr;
3588
3589 // If this is checking if all elements of a vector compare are set or not,
3590 // invert the casted vector equality compare and test if all compare
3591 // elements are clear or not. Compare against zero is generally easier for
3592 // analysis and codegen.
3593 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3594 // Example: are all elements equal? --> are zero elements not equal?
3595 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3596 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3597 if (Value *NotBCSrcOp =
3598 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3599 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3600 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3601 }
3602 }
3603
3604 // If this is checking if all elements of an extended vector are clear or not,
3605 // compare in a narrow type to eliminate the extend:
3606 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3607 Value *X;
3608 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3609 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3610 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3611 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3612 Value *NewCast = Builder.CreateBitCast(X, NewType);
3613 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3614 }
3615 }
3616
3617 // Folding: icmp <pred> iN X, C
3618 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3619 // and C is a splat of a K-bit pattern
3620 // and SC is a constant vector = <C', C', C', ..., C'>
3621 // Into:
3622 // %E = extractelement <M x iK> %vec, i32 C'
3623 // icmp <pred> iK %E, trunc(C)
3624 Value *Vec;
3625 ArrayRef<int> Mask;
3626 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3627 // Check whether every element of Mask is the same constant
3628 if (all_equal(Mask)) {
3629 auto *VecTy = cast<VectorType>(SrcType);
3630 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3631 if (C->isSplat(EltTy->getBitWidth())) {
3632 // Fold the icmp based on the value of C
3633 // If C is M copies of an iK sized bit pattern,
3634 // then:
3635 // => %E = extractelement <N x iK> %vec, i64 Elem
3636 // icmp <pred> iK %SplatVal, <pattern>
3637 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3638 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3639 return new ICmpInst(Pred, Extract, NewC);
3640 }
3641 }
3642 }
3643 return nullptr;
3644}
3645
3646/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3647/// where X is some kind of instruction.
3649 const APInt *C;
3650
3651 if (match(Cmp.getOperand(1), m_APInt(C))) {
3652 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3653 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3654 return I;
3655
3656 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3657 // For now, we only support constant integers while folding the
3658 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3659 // similar to the cases handled by binary ops above.
3660 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3661 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3662 return I;
3663
3664 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3665 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3666 return I;
3667
3668 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3670 return I;
3671
3672 {
3673 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3674 // fcmp olt/oge (fabs X), 2^ExpVal
3675 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3676 Value *X;
3677 if (match(Cmp.getOperand(0),
3680 ICmpInst::Predicate Pred = Cmp.getPredicate();
3681 APInt Exp;
3682 FCmpInst::Predicate NewPred;
3683 bool ValidPred = true;
3684
3685 switch (Pred) {
3686 case ICmpInst::ICMP_SLT:
3687 NewPred = FCmpInst::FCMP_OLT;
3688 Exp = *C - 1;
3689 break;
3690 case ICmpInst::ICMP_SGT:
3691 NewPred = FCmpInst::FCMP_OGE;
3692 Exp = *C;
3693 break;
3694 default:
3695 ValidPred = false;
3696 break;
3697 }
3698
3699 if (ValidPred) {
3700 const fltSemantics &Sem =
3701 X->getType()->getScalarType()->getFltSemantics();
3702 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3703
3704 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3705 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3706 int ExpVal = static_cast<int>(Exp.getSExtValue());
3707 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3709 Value *Fabs = Builder.CreateFAbs(X);
3710 return new FCmpInst(NewPred, Fabs,
3711 ConstantFP::get(X->getType(), CmpConst));
3712 }
3713 }
3714 }
3715 }
3716
3717 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3718 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3719 // TODO: This checks one-use, but that is not strictly necessary.
3720 Value *Cmp0 = Cmp.getOperand(0);
3721 Value *X, *Y;
3722 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3723 (match(Cmp0,
3725 m_Value(X), m_Value(Y)))) ||
3726 match(Cmp0,
3728 m_Value(X), m_Value(Y))))))
3729 return new ICmpInst(Cmp.getPredicate(), X, Y);
3730 }
3731
3732 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3734
3735 return nullptr;
3736}
3737
3738/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3739/// icmp eq/ne BO, C.
3741 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3742 // TODO: Some of these folds could work with arbitrary constants, but this
3743 // function is limited to scalar and vector splat constants.
3744 if (!Cmp.isEquality())
3745 return nullptr;
3746
3747 ICmpInst::Predicate Pred = Cmp.getPredicate();
3748 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3749 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3750 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3751
3752 switch (BO->getOpcode()) {
3753 case Instruction::SRem:
3754 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3755 if (C.isZero() && BO->hasOneUse()) {
3756 const APInt *BOC;
3757 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3758 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3759 return new ICmpInst(Pred, NewRem,
3761 }
3762 }
3763 break;
3764 case Instruction::Add: {
3765 // (A + C2) == C --> A == (C - C2)
3766 // (A + C2) != C --> A != (C - C2)
3767 // TODO: Remove the one-use limitation? See discussion in D58633.
3768 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3769 if (BO->hasOneUse())
3770 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3771 } else if (C.isZero()) {
3772 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3773 // efficiently invertible, or if the add has just this one use.
3774 if (Value *NegVal = dyn_castNegVal(BOp1))
3775 return new ICmpInst(Pred, BOp0, NegVal);
3776 if (Value *NegVal = dyn_castNegVal(BOp0))
3777 return new ICmpInst(Pred, NegVal, BOp1);
3778 if (BO->hasOneUse()) {
3779 // (add nuw A, B) != 0 -> (or A, B) != 0
3780 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3781 Value *Or = Builder.CreateOr(BOp0, BOp1);
3782 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3783 }
3784 Value *Neg = Builder.CreateNeg(BOp1);
3785 Neg->takeName(BO);
3786 return new ICmpInst(Pred, BOp0, Neg);
3787 }
3788 }
3789 break;
3790 }
3791 case Instruction::Xor:
3792 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3793 // For the xor case, we can xor two constants together, eliminating
3794 // the explicit xor.
3795 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3796 } else if (C.isZero()) {
3797 // Replace ((xor A, B) != 0) with (A != B)
3798 return new ICmpInst(Pred, BOp0, BOp1);
3799 }
3800 break;
3801 case Instruction::Or: {
3802 const APInt *BOC;
3803 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3804 // Comparing if all bits outside of a constant mask are set?
3805 // Replace (X | C) == -1 with (X & ~C) == ~C.
3806 // This removes the -1 constant.
3808 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3809 return new ICmpInst(Pred, And, NotBOC);
3810 }
3811 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3812 // -> (and cond, (icmp eq Other, 0))
3813 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3814 // -> (or cond, (icmp ne Other, 0))
3815 Value *Cond, *TV, *FV, *Other, *Sel;
3816 if (C.isZero() &&
3817 match(BO,
3820 m_Value(FV))),
3821 m_Value(Other)))) &&
3822 Cond->getType() == Cmp.getType()) {
3823 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3824 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3825 if (Pred == ICmpInst::ICMP_EQ
3826 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3827 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3828 Value *Cmp = Builder.CreateICmp(
3829 Pred, Other, Constant::getNullValue(Other->getType()));
3831 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3832 Cond);
3833 }
3834 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3835 // case we need to invert the select condition so we need to be careful to
3836 // avoid creating extra instructions.
3837 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3838 // -> (or (not cond), (icmp ne Other, 0))
3839 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3840 // -> (and (not cond), (icmp eq Other, 0))
3841 //
3842 // Only do this if the inner select has one use, in which case we are
3843 // replacing `select` with `(not cond)`. Otherwise, we will create more
3844 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3845 // cond was freely invertable, the select arms would have been inverted.
3846 if (Sel->hasOneUse() &&
3847 (Pred == ICmpInst::ICMP_EQ
3848 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3849 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3850 Value *NotCond = Builder.CreateNot(Cond);
3851 Value *Cmp = Builder.CreateICmp(
3852 Pred, Other, Constant::getNullValue(Other->getType()));
3854 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3855 NotCond);
3856 }
3857 }
3858 break;
3859 }
3860 case Instruction::UDiv:
3861 case Instruction::SDiv:
3862 if (BO->isExact()) {
3863 // div exact X, Y eq/ne 0 -> X eq/ne 0
3864 // div exact X, Y eq/ne 1 -> X eq/ne Y
3865 // div exact X, Y eq/ne C ->
3866 // if Y * C never-overflow && OneUse:
3867 // -> Y * C eq/ne X
3868 if (C.isZero())
3869 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3870 else if (C.isOne())
3871 return new ICmpInst(Pred, BOp0, BOp1);
3872 else if (BO->hasOneUse()) {
3874 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3875 Cmp.getOperand(1), BO);
3877 Value *YC =
3878 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3879 return new ICmpInst(Pred, YC, BOp0);
3880 }
3881 }
3882 }
3883 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3884 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3885 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3886 return new ICmpInst(NewPred, BOp1, BOp0);
3887 }
3888 break;
3889 default:
3890 break;
3891 }
3892 return nullptr;
3893}
3894
3896 const APInt &CRhs,
3897 InstCombiner::BuilderTy &Builder,
3898 const SimplifyQuery &Q) {
3899 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3900 "Non-ctpop intrin in ctpop fold");
3901 if (!CtpopLhs->hasOneUse())
3902 return nullptr;
3903
3904 // Power of 2 test:
3905 // isPow2OrZero : ctpop(X) u< 2
3906 // isPow2 : ctpop(X) == 1
3907 // NotPow2OrZero: ctpop(X) u> 1
3908 // NotPow2 : ctpop(X) != 1
3909 // If we know any bit of X can be folded to:
3910 // IsPow2 : X & (~Bit) == 0
3911 // NotPow2 : X & (~Bit) != 0
3912 const ICmpInst::Predicate Pred = I.getPredicate();
3913 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3914 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3915 Value *Op = CtpopLhs->getArgOperand(0);
3916 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CxtI, Q.DT);
3917 // No need to check for count > 1, that should be already constant folded.
3918 if (OpKnown.countMinPopulation() == 1) {
3919 Value *And = Builder.CreateAnd(
3920 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3921 return new ICmpInst(
3922 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3925 And, Constant::getNullValue(Op->getType()));
3926 }
3927 }
3928
3929 return nullptr;
3930}
3931
3932/// Fold an equality icmp with LLVM intrinsic and constant operand.
3934 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3935 Type *Ty = II->getType();
3936 unsigned BitWidth = C.getBitWidth();
3937 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3938
3939 switch (II->getIntrinsicID()) {
3940 case Intrinsic::abs:
3941 // abs(A) == 0 -> A == 0
3942 // abs(A) == INT_MIN -> A == INT_MIN
3943 if (C.isZero() || C.isMinSignedValue())
3944 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3945 break;
3946
3947 case Intrinsic::bswap:
3948 // bswap(A) == C -> A == bswap(C)
3949 return new ICmpInst(Pred, II->getArgOperand(0),
3950 ConstantInt::get(Ty, C.byteSwap()));
3951
3952 case Intrinsic::bitreverse:
3953 // bitreverse(A) == C -> A == bitreverse(C)
3954 return new ICmpInst(Pred, II->getArgOperand(0),
3955 ConstantInt::get(Ty, C.reverseBits()));
3956
3957 case Intrinsic::ctlz:
3958 case Intrinsic::cttz: {
3959 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3960 if (C == BitWidth)
3961 return new ICmpInst(Pred, II->getArgOperand(0),
3963
3964 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3965 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3966 // Limit to one use to ensure we don't increase instruction count.
3967 unsigned Num = C.getLimitedValue(BitWidth);
3968 if (Num != BitWidth && II->hasOneUse()) {
3969 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3970 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3971 : APInt::getHighBitsSet(BitWidth, Num + 1);
3972 APInt Mask2 = IsTrailing
3975 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3976 ConstantInt::get(Ty, Mask2));
3977 }
3978 break;
3979 }
3980
3981 case Intrinsic::ctpop: {
3982 // popcount(A) == 0 -> A == 0 and likewise for !=
3983 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3984 bool IsZero = C.isZero();
3985 if (IsZero || C == BitWidth)
3986 return new ICmpInst(Pred, II->getArgOperand(0),
3987 IsZero ? Constant::getNullValue(Ty)
3989
3990 break;
3991 }
3992
3993 case Intrinsic::fshl:
3994 case Intrinsic::fshr:
3995 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3996 const APInt *RotAmtC;
3997 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3998 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3999 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
4000 return new ICmpInst(Pred, II->getArgOperand(0),
4001 II->getIntrinsicID() == Intrinsic::fshl
4002 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
4003 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
4004 }
4005 break;
4006
4007 case Intrinsic::umax:
4008 case Intrinsic::uadd_sat: {
4009 // uadd.sat(a, b) == 0 -> (a | b) == 0
4010 // umax(a, b) == 0 -> (a | b) == 0
4011 if (C.isZero() && II->hasOneUse()) {
4012 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4013 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4014 }
4015 break;
4016 }
4017
4018 case Intrinsic::ssub_sat:
4019 // ssub.sat(a, b) == 0 -> a == b
4020 //
4021 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4022 // (because 1 saturates to 0). Just skip the optimization for i1.
4023 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4024 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4025 break;
4026 case Intrinsic::usub_sat: {
4027 // usub.sat(a, b) == 0 -> a <= b
4028 if (C.isZero()) {
4029 ICmpInst::Predicate NewPred =
4031 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4032 }
4033 break;
4034 }
4035 default:
4036 break;
4037 }
4038
4039 return nullptr;
4040}
4041
4042/// Fold an icmp with LLVM intrinsics
4043static Instruction *
4045 InstCombiner::BuilderTy &Builder) {
4046 assert(Cmp.isEquality());
4047
4048 ICmpInst::Predicate Pred = Cmp.getPredicate();
4049 Value *Op0 = Cmp.getOperand(0);
4050 Value *Op1 = Cmp.getOperand(1);
4051 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4052 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4053 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4054 return nullptr;
4055
4056 switch (IIOp0->getIntrinsicID()) {
4057 case Intrinsic::bswap:
4058 case Intrinsic::bitreverse:
4059 // If both operands are byte-swapped or bit-reversed, just compare the
4060 // original values.
4061 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4062 case Intrinsic::fshl:
4063 case Intrinsic::fshr: {
4064 // If both operands are rotated by same amount, just compare the
4065 // original values.
4066 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4067 break;
4068 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4069 break;
4070 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4071 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4072
4073 // rotate(X, AmtX) == rotate(Y, AmtY)
4074 // -> rotate(X, AmtX - AmtY) == Y
4075 // Do this if either both rotates have one use or if only one has one use
4076 // and AmtX/AmtY are constants.
4077 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4078 if (OneUses == 2 ||
4079 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4080 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4081 Value *SubAmt =
4082 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4083 Value *CombinedRotate = Builder.CreateIntrinsic(
4084 Op0->getType(), IIOp0->getIntrinsicID(),
4085 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4086 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4087 }
4088 } break;
4089 default:
4090 break;
4091 }
4092
4093 return nullptr;
4094}
4095
4096/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4097/// where X is some kind of instruction and C is AllowPoison.
4098/// TODO: Move more folds which allow poison to this function.
4101 const APInt &C) {
4102 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4103 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4104 switch (II->getIntrinsicID()) {
4105 default:
4106 break;
4107 case Intrinsic::fshl:
4108 case Intrinsic::fshr:
4109 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4110 // (rot X, ?) == 0/-1 --> X == 0/-1
4111 if (C.isZero() || C.isAllOnes())
4112 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4113 }
4114 break;
4115 }
4116 }
4117
4118 return nullptr;
4119}
4120
4121/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4123 BinaryOperator *BO,
4124 const APInt &C) {
4125 switch (BO->getOpcode()) {
4126 case Instruction::Xor:
4127 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4128 return I;
4129 break;
4130 case Instruction::And:
4131 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4132 return I;
4133 break;
4134 case Instruction::Or:
4135 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4136 return I;
4137 break;
4138 case Instruction::Mul:
4139 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4140 return I;
4141 break;
4142 case Instruction::Shl:
4143 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4144 return I;
4145 break;
4146 case Instruction::LShr:
4147 case Instruction::AShr:
4148 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4149 return I;
4150 break;
4151 case Instruction::SRem:
4152 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4153 return I;
4154 break;
4155 case Instruction::UDiv:
4156 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4157 return I;
4158 [[fallthrough]];
4159 case Instruction::SDiv:
4160 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4161 return I;
4162 break;
4163 case Instruction::Sub:
4164 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4165 return I;
4166 break;
4167 case Instruction::Add:
4168 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4169 return I;
4170 break;
4171 default:
4172 break;
4173 }
4174
4175 // TODO: These folds could be refactored to be part of the above calls.
4177 return I;
4178
4179 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4180 // : C4), C5` pattern, by computing a truth table of the four constant
4181 // variants.
4183}
4184
4185static Instruction *
4187 const APInt &C,
4188 InstCombiner::BuilderTy &Builder) {
4189 // This transform may end up producing more than one instruction for the
4190 // intrinsic, so limit it to one user of the intrinsic.
4191 if (!II->hasOneUse())
4192 return nullptr;
4193
4194 // Let Y = [add/sub]_sat(X, C) pred C2
4195 // SatVal = The saturating value for the operation
4196 // WillWrap = Whether or not the operation will underflow / overflow
4197 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4198 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4199 //
4200 // When (SatVal pred C2) is true, then
4201 // Y = WillWrap ? true : ((X binop C) pred C2)
4202 // => Y = WillWrap || ((X binop C) pred C2)
4203 // else
4204 // Y = WillWrap ? false : ((X binop C) pred C2)
4205 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4206 // => Y = !WillWrap && ((X binop C) pred C2)
4207 Value *Op0 = II->getOperand(0);
4208 Value *Op1 = II->getOperand(1);
4209
4210 const APInt *COp1;
4211 // This transform only works when the intrinsic has an integral constant or
4212 // splat vector as the second operand.
4213 if (!match(Op1, m_APInt(COp1)))
4214 return nullptr;
4215
4216 APInt SatVal;
4217 switch (II->getIntrinsicID()) {
4218 default:
4220 "This function only works with usub_sat and uadd_sat for now!");
4221 case Intrinsic::uadd_sat:
4222 SatVal = APInt::getAllOnes(C.getBitWidth());
4223 break;
4224 case Intrinsic::usub_sat:
4225 SatVal = APInt::getZero(C.getBitWidth());
4226 break;
4227 }
4228
4229 // Check (SatVal pred C2)
4230 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4231
4232 // !WillWrap.
4234 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4235
4236 // WillWrap.
4237 if (SatValCheck)
4238 C1 = C1.inverse();
4239
4241 if (II->getBinaryOp() == Instruction::Add)
4242 C2 = C2.sub(*COp1);
4243 else
4244 C2 = C2.add(*COp1);
4245
4246 Instruction::BinaryOps CombiningOp =
4247 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4248
4249 std::optional<ConstantRange> Combination;
4250 if (CombiningOp == Instruction::BinaryOps::Or)
4251 Combination = C1.exactUnionWith(C2);
4252 else /* CombiningOp == Instruction::BinaryOps::And */
4253 Combination = C1.exactIntersectWith(C2);
4254
4255 if (!Combination)
4256 return nullptr;
4257
4258 CmpInst::Predicate EquivPred;
4259 APInt EquivInt;
4260 APInt EquivOffset;
4261
4262 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4263
4264 return new ICmpInst(
4265 EquivPred,
4266 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4267 ConstantInt::get(Op1->getType(), EquivInt));
4268}
4269
4270static Instruction *
4272 const APInt &C,
4273 InstCombiner::BuilderTy &Builder) {
4274 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4275 switch (Pred) {
4276 case ICmpInst::ICMP_EQ:
4277 case ICmpInst::ICMP_NE:
4278 if (C.isZero())
4279 NewPredicate = Pred;
4280 else if (C.isOne())
4281 NewPredicate =
4283 else if (C.isAllOnes())
4284 NewPredicate =
4286 break;
4287
4288 case ICmpInst::ICMP_SGT:
4289 if (C.isAllOnes())
4290 NewPredicate = ICmpInst::ICMP_UGE;
4291 else if (C.isZero())
4292 NewPredicate = ICmpInst::ICMP_UGT;
4293 break;
4294
4295 case ICmpInst::ICMP_SLT:
4296 if (C.isZero())
4297 NewPredicate = ICmpInst::ICMP_ULT;
4298 else if (C.isOne())
4299 NewPredicate = ICmpInst::ICMP_ULE;
4300 break;
4301
4302 case ICmpInst::ICMP_ULT:
4303 if (C.ugt(1))
4304 NewPredicate = ICmpInst::ICMP_UGE;
4305 break;
4306
4307 case ICmpInst::ICMP_UGT:
4308 if (!C.isZero() && !C.isAllOnes())
4309 NewPredicate = ICmpInst::ICMP_ULT;
4310 break;
4311
4312 default:
4313 break;
4314 }
4315
4316 if (!NewPredicate)
4317 return nullptr;
4318
4319 if (I->getIntrinsicID() == Intrinsic::scmp)
4320 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4321 Value *LHS = I->getOperand(0);
4322 Value *RHS = I->getOperand(1);
4323 return new ICmpInst(*NewPredicate, LHS, RHS);
4324}
4325
4326/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4329 const APInt &C) {
4330 ICmpInst::Predicate Pred = Cmp.getPredicate();
4331
4332 // Handle folds that apply for any kind of icmp.
4333 switch (II->getIntrinsicID()) {
4334 default:
4335 break;
4336 case Intrinsic::uadd_sat:
4337 case Intrinsic::usub_sat:
4338 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4339 Pred, cast<SaturatingInst>(II), C, Builder))
4340 return Folded;
4341 break;
4342 case Intrinsic::ctpop: {
4343 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4344 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4345 return R;
4346 } break;
4347 case Intrinsic::scmp:
4348 case Intrinsic::ucmp:
4349 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4350 return Folded;
4351 break;
4352 }
4353
4354 if (Cmp.isEquality())
4355 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4356
4357 Type *Ty = II->getType();
4358 unsigned BitWidth = C.getBitWidth();
4359 switch (II->getIntrinsicID()) {
4360 case Intrinsic::ctpop: {
4361 // (ctpop X > BitWidth - 1) --> X == -1
4362 Value *X = II->getArgOperand(0);
4363 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4364 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4366 // (ctpop X < BitWidth) --> X != -1
4367 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4368 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4370 break;
4371 }
4372 case Intrinsic::ctlz: {
4373 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4374 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4375 unsigned Num = C.getLimitedValue();
4376 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4377 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4378 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4379 }
4380
4381 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4382 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4383 unsigned Num = C.getLimitedValue();
4385 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4386 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4387 }
4388 break;
4389 }
4390 case Intrinsic::cttz: {
4391 // Limit to one use to ensure we don't increase instruction count.
4392 if (!II->hasOneUse())
4393 return nullptr;
4394
4395 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4396 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4397 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4398 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4399 Builder.CreateAnd(II->getArgOperand(0), Mask),
4401 }
4402
4403 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4404 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4405 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4406 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4407 Builder.CreateAnd(II->getArgOperand(0), Mask),
4409 }
4410 break;
4411 }
4412 case Intrinsic::ssub_sat:
4413 // ssub.sat(a, b) spred 0 -> a spred b
4414 //
4415 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4416 // (because 1 saturates to 0). Just skip the optimization for i1.
4417 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4418 if (C.isZero())
4419 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4420 // X s<= 0 is cannonicalized to X s< 1
4421 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4422 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4423 II->getArgOperand(1));
4424 // X s>= 0 is cannonicalized to X s> -1
4425 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4426 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4427 II->getArgOperand(1));
4428 }
4429 break;
4430 case Intrinsic::abs: {
4431 if (!II->hasOneUse())
4432 return nullptr;
4433
4434 Value *X = II->getArgOperand(0);
4435
4436 // If C >= 0:
4437 // abs(X) u> C --> X + C u> 2 * C
4438 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4439 return new ICmpInst(ICmpInst::ICMP_UGT,
4440 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4441 ConstantInt::get(Ty, 2 * C));
4442 }
4443
4444 // If C >= 1:
4445 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4446 if (Pred == CmpInst::ICMP_ULT && C.sge(1))
4447 return new ICmpInst(ICmpInst::ICMP_ULE,
4448 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4449 ConstantInt::get(Ty, 2 * (C - 1)));
4450
4451 break;
4452 }
4453 default:
4454 break;
4455 }
4456
4457 return nullptr;
4458}
4459
4460/// Handle icmp with constant (but not simple integer constant) RHS.
4462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4463 Constant *RHSC = dyn_cast<Constant>(Op1);
4465 if (!RHSC || !LHSI)
4466 return nullptr;
4467
4468 switch (LHSI->getOpcode()) {
4469 case Instruction::IntToPtr:
4470 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4471 if (isa<ConstantPointerNull>(RHSC)) {
4472 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4473 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4474 APInt NullPtrValue =
4475 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4476 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4477 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4478 }
4479 }
4480 break;
4481
4482 case Instruction::Load:
4483 // Try to optimize things like "A[i] > 4" to index computations.
4484 if (GetElementPtrInst *GEP =
4486 if (Instruction *Res =
4488 return Res;
4489 break;
4490 }
4491
4492 return nullptr;
4493}
4494
4496 Value *RHS, const ICmpInst &I) {
4497 // Try to fold the comparison into the select arms, which will cause the
4498 // select to be converted into a logical and/or.
4499 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4500 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4501 return Res;
4502 if (std::optional<bool> Impl = isImpliedCondition(
4503 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4504 return ConstantInt::get(I.getType(), *Impl);
4505 return nullptr;
4506 };
4507
4508 ConstantInt *CI = nullptr;
4509 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4510 if (Op1)
4511 CI = dyn_cast<ConstantInt>(Op1);
4512
4513 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4514 if (Op2)
4515 CI = dyn_cast<ConstantInt>(Op2);
4516
4517 auto Simplifies = [&](Value *Op, unsigned Idx) {
4518 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4519 const APInt *Dummy;
4520 return Op ||
4521 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4522 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4523 };
4524
4525 // We only want to perform this transformation if it will not lead to
4526 // additional code. This is true if either both sides of the select
4527 // fold to a constant (in which case the icmp is replaced with a select
4528 // which will usually simplify) or this is the only user of the
4529 // select (in which case we are trading a select+icmp for a simpler
4530 // select+icmp) or all uses of the select can be replaced based on
4531 // dominance information ("Global cases").
4532 bool Transform = false;
4533 if (Op1 && Op2)
4534 Transform = true;
4535 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4536 // Local case
4537 if (SI->hasOneUse())
4538 Transform = true;
4539 // Global cases
4540 else if (CI && !CI->isZero())
4541 // When Op1 is constant try replacing select with second operand.
4542 // Otherwise Op2 is constant and try replacing select with first
4543 // operand.
4544 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4545 }
4546 if (Transform) {
4547 if (!Op1)
4548 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4549 if (!Op2)
4550 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4551 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr,
4552 ProfcheckDisableMetadataFixes ? nullptr : SI);
4553 }
4554
4555 return nullptr;
4556}
4557
4558// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4559static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4560 unsigned Depth = 0) {
4561 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4562 return true;
4563 if (V->getType()->getScalarSizeInBits() == 1)
4564 return true;
4566 return false;
4567 Value *X;
4569 if (!I)
4570 return false;
4571 switch (I->getOpcode()) {
4572 case Instruction::ZExt:
4573 // ZExt(Mask) is a Mask.
4574 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4575 case Instruction::SExt:
4576 // SExt(Mask) is a Mask.
4577 // SExt(~Mask) is a ~Mask.
4578 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4579 case Instruction::And:
4580 case Instruction::Or:
4581 // Mask0 | Mask1 is a Mask.
4582 // Mask0 & Mask1 is a Mask.
4583 // ~Mask0 | ~Mask1 is a ~Mask.
4584 // ~Mask0 & ~Mask1 is a ~Mask.
4585 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4586 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4587 case Instruction::Xor:
4588 if (match(V, m_Not(m_Value(X))))
4589 return isMaskOrZero(X, !Not, Q, Depth);
4590
4591 // (X ^ -X) is a ~Mask
4592 if (Not)
4593 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4594 // (X ^ (X - 1)) is a Mask
4595 else
4596 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4597 case Instruction::Select:
4598 // c ? Mask0 : Mask1 is a Mask.
4599 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4600 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4601 case Instruction::Shl:
4602 // (~Mask) << X is a ~Mask.
4603 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4604 case Instruction::LShr:
4605 // Mask >> X is a Mask.
4606 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4607 case Instruction::AShr:
4608 // Mask s>> X is a Mask.
4609 // ~Mask s>> X is a ~Mask.
4610 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4611 case Instruction::Add:
4612 // Pow2 - 1 is a Mask.
4613 if (!Not && match(I->getOperand(1), m_AllOnes()))
4614 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4615 Q.AC, Q.CxtI, Q.DT, Depth);
4616 break;
4617 case Instruction::Sub:
4618 // -Pow2 is a ~Mask.
4619 if (Not && match(I->getOperand(0), m_Zero()))
4620 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4621 Q.AC, Q.CxtI, Q.DT, Depth);
4622 break;
4623 case Instruction::Call: {
4624 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4625 switch (II->getIntrinsicID()) {
4626 // min/max(Mask0, Mask1) is a Mask.
4627 // min/max(~Mask0, ~Mask1) is a ~Mask.
4628 case Intrinsic::umax:
4629 case Intrinsic::smax:
4630 case Intrinsic::umin:
4631 case Intrinsic::smin:
4632 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4633 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4634
4635 // In the context of masks, bitreverse(Mask) == ~Mask
4636 case Intrinsic::bitreverse:
4637 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4638 default:
4639 break;
4640 }
4641 }
4642 break;
4643 }
4644 default:
4645 break;
4646 }
4647 return false;
4648}
4649
4650/// Some comparisons can be simplified.
4651/// In this case, we are looking for comparisons that look like
4652/// a check for a lossy truncation.
4653/// Folds:
4654/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4655/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4656/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4657/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4658/// Where Mask is some pattern that produces all-ones in low bits:
4659/// (-1 >> y)
4660/// ((-1 << y) >> y) <- non-canonical, has extra uses
4661/// ~(-1 << y)
4662/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4663/// The Mask can be a constant, too.
4664/// For some predicates, the operands are commutative.
4665/// For others, x can only be on a specific side.
4667 Value *Op1, const SimplifyQuery &Q,
4668 InstCombiner &IC) {
4669
4670 ICmpInst::Predicate DstPred;
4671 switch (Pred) {
4673 // x & Mask == x
4674 // x & ~Mask == 0
4675 // ~x | Mask == -1
4676 // -> x u<= Mask
4677 // x & ~Mask == ~Mask
4678 // -> ~Mask u<= x
4680 break;
4682 // x & Mask != x
4683 // x & ~Mask != 0
4684 // ~x | Mask != -1
4685 // -> x u> Mask
4686 // x & ~Mask != ~Mask
4687 // -> ~Mask u> x
4689 break;
4691 // x & Mask u< x
4692 // -> x u> Mask
4693 // x & ~Mask u< ~Mask
4694 // -> ~Mask u> x
4696 break;
4698 // x & Mask u>= x
4699 // -> x u<= Mask
4700 // x & ~Mask u>= ~Mask
4701 // -> ~Mask u<= x
4703 break;
4705 // x & Mask s< x [iff Mask s>= 0]
4706 // -> x s> Mask
4707 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4708 // -> ~Mask s> x
4710 break;
4712 // x & Mask s>= x [iff Mask s>= 0]
4713 // -> x s<= Mask
4714 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4715 // -> ~Mask s<= x
4717 break;
4718 default:
4719 // We don't support sgt,sle
4720 // ult/ugt are simplified to true/false respectively.
4721 return nullptr;
4722 }
4723
4724 Value *X, *M;
4725 // Put search code in lambda for early positive returns.
4726 auto IsLowBitMask = [&]() {
4727 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4728 X = Op1;
4729 // Look for: x & Mask pred x
4730 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4731 return !ICmpInst::isSigned(Pred) ||
4732 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4733 }
4734
4735 // Look for: x & ~Mask pred ~Mask
4736 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4737 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4738 }
4739 return false;
4740 }
4741 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4742 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4743
4744 auto Check = [&]() {
4745 // Look for: ~x | Mask == -1
4746 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4747 if (Value *NotX =
4748 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4749 X = NotX;
4750 return true;
4751 }
4752 }
4753 return false;
4754 };
4755 if (Check())
4756 return true;
4757 std::swap(X, M);
4758 return Check();
4759 }
4760 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4761 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4762 auto Check = [&]() {
4763 // Look for: x & ~Mask == 0
4764 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4765 if (Value *NotM =
4766 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4767 M = NotM;
4768 return true;
4769 }
4770 }
4771 return false;
4772 };
4773 if (Check())
4774 return true;
4775 std::swap(X, M);
4776 return Check();
4777 }
4778 return false;
4779 };
4780
4781 if (!IsLowBitMask())
4782 return nullptr;
4783
4784 return IC.Builder.CreateICmp(DstPred, X, M);
4785}
4786
4787/// Some comparisons can be simplified.
4788/// In this case, we are looking for comparisons that look like
4789/// a check for a lossy signed truncation.
4790/// Folds: (MaskedBits is a constant.)
4791/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4792/// Into:
4793/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4794/// Where KeptBits = bitwidth(%x) - MaskedBits
4795static Value *
4797 InstCombiner::BuilderTy &Builder) {
4798 CmpPredicate SrcPred;
4799 Value *X;
4800 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4801 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4802 if (!match(&I, m_c_ICmp(SrcPred,
4804 m_APInt(C1))),
4805 m_Deferred(X))))
4806 return nullptr;
4807
4808 // Potential handling of non-splats: for each element:
4809 // * if both are undef, replace with constant 0.
4810 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4811 // * if both are not undef, and are different, bailout.
4812 // * else, only one is undef, then pick the non-undef one.
4813
4814 // The shift amount must be equal.
4815 if (*C0 != *C1)
4816 return nullptr;
4817 const APInt &MaskedBits = *C0;
4818 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4819
4820 ICmpInst::Predicate DstPred;
4821 switch (SrcPred) {
4823 // ((%x << MaskedBits) a>> MaskedBits) == %x
4824 // =>
4825 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4827 break;
4829 // ((%x << MaskedBits) a>> MaskedBits) != %x
4830 // =>
4831 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4833 break;
4834 // FIXME: are more folds possible?
4835 default:
4836 return nullptr;
4837 }
4838
4839 auto *XType = X->getType();
4840 const unsigned XBitWidth = XType->getScalarSizeInBits();
4841 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4842 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4843
4844 // KeptBits = bitwidth(%x) - MaskedBits
4845 const APInt KeptBits = BitWidth - MaskedBits;
4846 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4847 // ICmpCst = (1 << KeptBits)
4848 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4849 assert(ICmpCst.isPowerOf2());
4850 // AddCst = (1 << (KeptBits-1))
4851 const APInt AddCst = ICmpCst.lshr(1);
4852 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4853
4854 // T0 = add %x, AddCst
4855 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4856 // T1 = T0 DstPred ICmpCst
4857 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4858
4859 return T1;
4860}
4861
4862// Given pattern:
4863// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4864// we should move shifts to the same hand of 'and', i.e. rewrite as
4865// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4866// We are only interested in opposite logical shifts here.
4867// One of the shifts can be truncated.
4868// If we can, we want to end up creating 'lshr' shift.
4869static Value *
4871 InstCombiner::BuilderTy &Builder) {
4872 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4873 !I.getOperand(0)->hasOneUse())
4874 return nullptr;
4875
4876 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4877
4878 // Look for an 'and' of two logical shifts, one of which may be truncated.
4879 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4880 Instruction *XShift, *MaybeTruncation, *YShift;
4881 if (!match(
4882 I.getOperand(0),
4883 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4885 m_AnyLogicalShift, m_Instruction(YShift))),
4886 m_Instruction(MaybeTruncation)))))
4887 return nullptr;
4888
4889 // We potentially looked past 'trunc', but only when matching YShift,
4890 // therefore YShift must have the widest type.
4891 Instruction *WidestShift = YShift;
4892 // Therefore XShift must have the shallowest type.
4893 // Or they both have identical types if there was no truncation.
4894 Instruction *NarrowestShift = XShift;
4895
4896 Type *WidestTy = WidestShift->getType();
4897 Type *NarrowestTy = NarrowestShift->getType();
4898 assert(NarrowestTy == I.getOperand(0)->getType() &&
4899 "We did not look past any shifts while matching XShift though.");
4900 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4901
4902 // If YShift is a 'lshr', swap the shifts around.
4903 if (match(YShift, m_LShr(m_Value(), m_Value())))
4904 std::swap(XShift, YShift);
4905
4906 // The shifts must be in opposite directions.
4907 auto XShiftOpcode = XShift->getOpcode();
4908 if (XShiftOpcode == YShift->getOpcode())
4909 return nullptr; // Do not care about same-direction shifts here.
4910
4911 Value *X, *XShAmt, *Y, *YShAmt;
4912 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4913 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4914
4915 // If one of the values being shifted is a constant, then we will end with
4916 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4917 // however, we will need to ensure that we won't increase instruction count.
4918 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4919 // At least one of the hands of the 'and' should be one-use shift.
4920 if (!match(I.getOperand(0),
4921 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4922 return nullptr;
4923 if (HadTrunc) {
4924 // Due to the 'trunc', we will need to widen X. For that either the old
4925 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4926 if (!MaybeTruncation->hasOneUse() &&
4927 !NarrowestShift->getOperand(1)->hasOneUse())
4928 return nullptr;
4929 }
4930 }
4931
4932 // We have two shift amounts from two different shifts. The types of those
4933 // shift amounts may not match. If that's the case let's bailout now.
4934 if (XShAmt->getType() != YShAmt->getType())
4935 return nullptr;
4936
4937 // As input, we have the following pattern:
4938 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4939 // We want to rewrite that as:
4940 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4941 // While we know that originally (Q+K) would not overflow
4942 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4943 // shift amounts. so it may now overflow in smaller bitwidth.
4944 // To ensure that does not happen, we need to ensure that the total maximal
4945 // shift amount is still representable in that smaller bit width.
4946 unsigned MaximalPossibleTotalShiftAmount =
4947 (WidestTy->getScalarSizeInBits() - 1) +
4948 (NarrowestTy->getScalarSizeInBits() - 1);
4949 APInt MaximalRepresentableShiftAmount =
4951 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4952 return nullptr;
4953
4954 // Can we fold (XShAmt+YShAmt) ?
4955 auto *NewShAmt = dyn_cast_or_null<Constant>(
4956 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4957 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4958 if (!NewShAmt)
4959 return nullptr;
4960 if (NewShAmt->getType() != WidestTy) {
4961 NewShAmt =
4962 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4963 if (!NewShAmt)
4964 return nullptr;
4965 }
4966 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4967
4968 // Is the new shift amount smaller than the bit width?
4969 // FIXME: could also rely on ConstantRange.
4970 if (!match(NewShAmt,
4972 APInt(WidestBitWidth, WidestBitWidth))))
4973 return nullptr;
4974
4975 // An extra legality check is needed if we had trunc-of-lshr.
4976 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
4977 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
4978 WidestShift]() {
4979 // It isn't obvious whether it's worth it to analyze non-constants here.
4980 // Also, let's basically give up on non-splat cases, pessimizing vectors.
4981 // If *any* of these preconditions matches we can perform the fold.
4982 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
4983 ? NewShAmt->getSplatValue()
4984 : NewShAmt;
4985 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
4986 if (NewShAmtSplat &&
4987 (NewShAmtSplat->isNullValue() ||
4988 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
4989 return true;
4990 // We consider *min* leading zeros so a single outlier
4991 // blocks the transform as opposed to allowing it.
4992 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
4994 unsigned MinLeadZero = Known.countMinLeadingZeros();
4995 // If the value being shifted has at most lowest bit set we can fold.
4996 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
4997 if (MaxActiveBits <= 1)
4998 return true;
4999 // Precondition: NewShAmt u<= countLeadingZeros(C)
5000 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5001 return true;
5002 }
5003 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5005 unsigned MinLeadZero = Known.countMinLeadingZeros();
5006 // If the value being shifted has at most lowest bit set we can fold.
5007 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5008 if (MaxActiveBits <= 1)
5009 return true;
5010 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5011 if (NewShAmtSplat) {
5012 APInt AdjNewShAmt =
5013 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5014 if (AdjNewShAmt.ule(MinLeadZero))
5015 return true;
5016 }
5017 }
5018 return false; // Can't tell if it's ok.
5019 };
5020 if (!CanFold())
5021 return nullptr;
5022 }
5023
5024 // All good, we can do this fold.
5025 X = Builder.CreateZExt(X, WidestTy);
5026 Y = Builder.CreateZExt(Y, WidestTy);
5027 // The shift is the same that was for X.
5028 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5029 ? Builder.CreateLShr(X, NewShAmt)
5030 : Builder.CreateShl(X, NewShAmt);
5031 Value *T1 = Builder.CreateAnd(T0, Y);
5032 return Builder.CreateICmp(I.getPredicate(), T1,
5033 Constant::getNullValue(WidestTy));
5034}
5035
5036/// Fold
5037/// (-1 u/ x) u< y
5038/// ((x * y) ?/ x) != y
5039/// to
5040/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5041/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5042/// will mean that we are looking for the opposite answer.
5044 CmpPredicate Pred;
5045 Value *X, *Y;
5047 Instruction *Div;
5048 bool NeedNegation;
5049 // Look for: (-1 u/ x) u</u>= y
5050 if (!I.isEquality() &&
5051 match(&I, m_c_ICmp(Pred,
5053 m_Instruction(Div)),
5054 m_Value(Y)))) {
5055 Mul = nullptr;
5056
5057 // Are we checking that overflow does not happen, or does happen?
5058 switch (Pred) {
5060 NeedNegation = false;
5061 break; // OK
5063 NeedNegation = true;
5064 break; // OK
5065 default:
5066 return nullptr; // Wrong predicate.
5067 }
5068 } else // Look for: ((x * y) / x) !=/== y
5069 if (I.isEquality() &&
5070 match(&I, m_c_ICmp(Pred, m_Value(Y),
5073 m_Value(X)),
5075 m_Deferred(X))),
5076 m_Instruction(Div))))) {
5077 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5078 } else
5079 return nullptr;
5080
5082 // If the pattern included (x * y), we'll want to insert new instructions
5083 // right before that original multiplication so that we can replace it.
5084 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5085 if (MulHadOtherUses)
5086 Builder.SetInsertPoint(Mul);
5087
5088 Value *Call = Builder.CreateIntrinsic(
5089 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5090 : Intrinsic::smul_with_overflow,
5091 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5092
5093 // If the multiplication was used elsewhere, to ensure that we don't leave
5094 // "duplicate" instructions, replace uses of that original multiplication
5095 // with the multiplication result from the with.overflow intrinsic.
5096 if (MulHadOtherUses)
5097 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5098
5099 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5100 if (NeedNegation) // This technically increases instruction count.
5101 Res = Builder.CreateNot(Res, "mul.not.ov");
5102
5103 // If we replaced the mul, erase it. Do this after all uses of Builder,
5104 // as the mul is used as insertion point.
5105 if (MulHadOtherUses)
5107
5108 return Res;
5109}
5110
5112 InstCombiner::BuilderTy &Builder) {
5113 CmpPredicate Pred;
5114 Value *X;
5115 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5116
5117 if (ICmpInst::isSigned(Pred))
5118 Pred = ICmpInst::getSwappedPredicate(Pred);
5119 else if (ICmpInst::isUnsigned(Pred))
5120 Pred = ICmpInst::getSignedPredicate(Pred);
5121 // else for equality-comparisons just keep the predicate.
5122
5123 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5124 Constant::getNullValue(X->getType()), I.getName());
5125 }
5126
5127 // A value is not equal to its negation unless that value is 0 or
5128 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5129 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5130 ICmpInst::isEquality(Pred)) {
5131 Type *Ty = X->getType();
5132 uint32_t BitWidth = Ty->getScalarSizeInBits();
5133 Constant *MaxSignedVal =
5134 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5135 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5136 Constant *Zero = Constant::getNullValue(Ty);
5137 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5138 }
5139
5140 return nullptr;
5141}
5142
5144 InstCombinerImpl &IC) {
5145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5146 // Normalize and operand as operand 0.
5147 CmpInst::Predicate Pred = I.getPredicate();
5148 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5149 std::swap(Op0, Op1);
5150 Pred = ICmpInst::getSwappedPredicate(Pred);
5151 }
5152
5153 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5154 return nullptr;
5155
5156 // (icmp (X & Y) u< X --> (X & Y) != X
5157 if (Pred == ICmpInst::ICMP_ULT)
5158 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5159
5160 // (icmp (X & Y) u>= X --> (X & Y) == X
5161 if (Pred == ICmpInst::ICMP_UGE)
5162 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5163
5164 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5165 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5166 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5167 // so don't do this fold.
5168 if (!match(Op1, m_ImmConstant()))
5169 if (auto *NotOp1 =
5170 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5171 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5172 Constant::getAllOnesValue(Op1->getType()));
5173 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5174 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5175 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5176 Constant::getNullValue(Op1->getType()));
5177 }
5178
5179 if (!ICmpInst::isSigned(Pred))
5180 return nullptr;
5181
5182 KnownBits KnownY = IC.computeKnownBits(A, &I);
5183 // (X & NegY) spred X --> (X & NegY) upred X
5184 if (KnownY.isNegative())
5185 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5186
5187 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5188 return nullptr;
5189
5190 if (KnownY.isNonNegative())
5191 // (X & PosY) s<= X --> X s>= 0
5192 // (X & PosY) s> X --> X s< 0
5193 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5194 Constant::getNullValue(Op1->getType()));
5195
5197 // (NegX & Y) s<= NegX --> Y s< 0
5198 // (NegX & Y) s> NegX --> Y s>= 0
5200 Constant::getNullValue(A->getType()));
5201
5202 return nullptr;
5203}
5204
5206 InstCombinerImpl &IC) {
5207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5208
5209 // Normalize or operand as operand 0.
5210 CmpInst::Predicate Pred = I.getPredicate();
5211 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5212 std::swap(Op0, Op1);
5213 Pred = ICmpInst::getSwappedPredicate(Pred);
5214 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5215 return nullptr;
5216 }
5217
5218 // icmp (X | Y) u<= X --> (X | Y) == X
5219 if (Pred == ICmpInst::ICMP_ULE)
5220 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5221
5222 // icmp (X | Y) u> X --> (X | Y) != X
5223 if (Pred == ICmpInst::ICMP_UGT)
5224 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5225
5226 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5227 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5228 if (Value *NotOp1 = IC.getFreelyInverted(
5229 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5230 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5231 Constant::getNullValue(Op1->getType()));
5232 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5233 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5234 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5235 Constant::getAllOnesValue(Op1->getType()));
5236 }
5237 return nullptr;
5238}
5239
5241 InstCombinerImpl &IC) {
5242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5243 // Normalize xor operand as operand 0.
5244 CmpInst::Predicate Pred = I.getPredicate();
5245 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5246 std::swap(Op0, Op1);
5247 Pred = ICmpInst::getSwappedPredicate(Pred);
5248 }
5249 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5250 return nullptr;
5251
5252 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5253 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5254 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5255 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5257 if (PredOut != Pred && isKnownNonZero(A, Q))
5258 return new ICmpInst(PredOut, Op0, Op1);
5259
5260 // These transform work when A is negative.
5261 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5262 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5263 if (match(A, m_Negative())) {
5264 CmpInst::Predicate NewPred;
5265 switch (ICmpInst::getStrictPredicate(Pred)) {
5266 default:
5267 return nullptr;
5268 case ICmpInst::ICMP_SLT:
5269 case ICmpInst::ICMP_UGT:
5270 NewPred = ICmpInst::ICMP_SLT;
5271 break;
5272 case ICmpInst::ICMP_SGT:
5273 case ICmpInst::ICMP_ULT:
5274 NewPred = ICmpInst::ICMP_SGE;
5275 break;
5276 }
5277 Constant *Const = Constant::getNullValue(Op0->getType());
5278 return new ICmpInst(NewPred, Op0, Const);
5279 }
5280
5281 return nullptr;
5282}
5283
5284/// Return true if X is a multiple of C.
5285/// TODO: Handle non-power-of-2 factors.
5286static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5287 if (C.isOne())
5288 return true;
5289
5290 if (!C.isPowerOf2())
5291 return false;
5292
5293 return MaskedValueIsZero(X, C - 1, Q);
5294}
5295
5296/// Try to fold icmp (binop), X or icmp X, (binop).
5297/// TODO: A large part of this logic is duplicated in InstSimplify's
5298/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5299/// duplication.
5301 const SimplifyQuery &SQ) {
5302 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5303 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5304
5305 // Special logic for binary operators.
5308 if (!BO0 && !BO1)
5309 return nullptr;
5310
5311 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5312 return NewICmp;
5313
5314 const CmpInst::Predicate Pred = I.getPredicate();
5315 Value *X;
5316
5317 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5318 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5319 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5320 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5321 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5322 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5323 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5324 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5325 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5326
5327 {
5328 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5329 Constant *C;
5330 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5331 m_ImmConstant(C)))) &&
5332 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5334 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5335 }
5336 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5337 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5338 m_ImmConstant(C)))) &&
5339 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5341 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5342 }
5343 }
5344
5345 // (icmp eq/ne (X, -P2), INT_MIN)
5346 // -> (icmp slt/sge X, INT_MIN + P2)
5347 if (ICmpInst::isEquality(Pred) && BO0 &&
5348 match(I.getOperand(1), m_SignMask()) &&
5350 // Will Constant fold.
5351 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5352 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5354 BO0->getOperand(0), NewC);
5355 }
5356
5357 {
5358 // Similar to above: an unsigned overflow comparison may use offset + mask:
5359 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5360 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5361 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5362 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5363 BinaryOperator *BO;
5364 const APInt *C;
5365 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5366 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5368 CmpInst::Predicate NewPred =
5370 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5371 return new ICmpInst(NewPred, Op1, Zero);
5372 }
5373
5374 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5375 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5377 CmpInst::Predicate NewPred =
5379 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5380 return new ICmpInst(NewPred, Op0, Zero);
5381 }
5382 }
5383
5384 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5385 bool Op0HasNUW = false, Op1HasNUW = false;
5386 bool Op0HasNSW = false, Op1HasNSW = false;
5387 // Analyze the case when either Op0 or Op1 is an add instruction.
5388 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5389 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5390 bool &HasNSW, bool &HasNUW) -> bool {
5392 HasNUW = BO.hasNoUnsignedWrap();
5393 HasNSW = BO.hasNoSignedWrap();
5394 return ICmpInst::isEquality(Pred) ||
5395 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5396 (CmpInst::isSigned(Pred) && HasNSW);
5397 } else if (BO.getOpcode() == Instruction::Or) {
5398 HasNUW = true;
5399 HasNSW = true;
5400 return true;
5401 } else {
5402 return false;
5403 }
5404 };
5405 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5406
5407 if (BO0) {
5408 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5409 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5410 }
5411 if (BO1) {
5412 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5413 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5414 }
5415
5416 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5417 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5418 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5419 return new ICmpInst(Pred, A == Op1 ? B : A,
5420 Constant::getNullValue(Op1->getType()));
5421
5422 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5423 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5424 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5425 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5426 C == Op0 ? D : C);
5427
5428 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5429 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5430 NoOp1WrapProblem) {
5431 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5432 Value *Y, *Z;
5433 if (A == C) {
5434 // C + B == C + D -> B == D
5435 Y = B;
5436 Z = D;
5437 } else if (A == D) {
5438 // D + B == C + D -> B == C
5439 Y = B;
5440 Z = C;
5441 } else if (B == C) {
5442 // A + C == C + D -> A == D
5443 Y = A;
5444 Z = D;
5445 } else {
5446 assert(B == D);
5447 // A + D == C + D -> A == C
5448 Y = A;
5449 Z = C;
5450 }
5451 return new ICmpInst(Pred, Y, Z);
5452 }
5453
5454 if (ICmpInst::isRelational(Pred)) {
5455 // Return if both X and Y is divisible by Z/-Z.
5456 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5457 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5458 bool IsNegative) -> bool {
5459 const APInt *OffsetC;
5460 if (!match(Z, m_APInt(OffsetC)))
5461 return false;
5462
5463 // Fast path for Z == 1/-1.
5464 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5465 return true;
5466
5467 APInt C = *OffsetC;
5468 if (IsNegative)
5469 C.negate();
5470 // Note: -INT_MIN is also negative.
5471 if (!C.isStrictlyPositive())
5472 return false;
5473
5474 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5475 };
5476
5477 // TODO: The subtraction-related identities shown below also hold, but
5478 // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
5479 // wouldn't happen even if they were implemented.
5480 //
5481 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5482 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5483 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5484 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5485
5486 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5487 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5488 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5489 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5490 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5491 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5492 if (A && NoOp0WrapProblem &&
5493 ShareCommonDivisor(A, Op1, B,
5494 ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred)))
5496 Op1);
5497
5498 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5499 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5500 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5501 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5502 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5503 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5504 if (C && NoOp1WrapProblem &&
5505 ShareCommonDivisor(Op0, C, D,
5506 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5508 C);
5509 }
5510
5511 // if C1 has greater magnitude than C2:
5512 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5513 // s.t. C3 = C1 - C2
5514 //
5515 // if C2 has greater magnitude than C1:
5516 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5517 // s.t. C3 = C2 - C1
5518 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5519 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5520 const APInt *AP1, *AP2;
5521 // TODO: Support non-uniform vectors.
5522 // TODO: Allow poison passthrough if B or D's element is poison.
5523 if (match(B, m_APIntAllowPoison(AP1)) &&
5524 match(D, m_APIntAllowPoison(AP2)) &&
5525 AP1->isNegative() == AP2->isNegative()) {
5526 APInt AP1Abs = AP1->abs();
5527 APInt AP2Abs = AP2->abs();
5528 if (AP1Abs.uge(AP2Abs)) {
5529 APInt Diff = *AP1 - *AP2;
5530 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5531 Value *NewAdd = Builder.CreateAdd(
5532 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5533 return new ICmpInst(Pred, NewAdd, C);
5534 } else {
5535 APInt Diff = *AP2 - *AP1;
5536 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5537 Value *NewAdd = Builder.CreateAdd(
5538 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5539 return new ICmpInst(Pred, A, NewAdd);
5540 }
5541 }
5542 Constant *Cst1, *Cst2;
5543 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5544 ICmpInst::isEquality(Pred)) {
5545 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5546 Value *NewAdd = Builder.CreateAdd(C, Diff);
5547 return new ICmpInst(Pred, A, NewAdd);
5548 }
5549 }
5550
5551 // Analyze the case when either Op0 or Op1 is a sub instruction.
5552 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5553 A = nullptr;
5554 B = nullptr;
5555 C = nullptr;
5556 D = nullptr;
5557 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5558 A = BO0->getOperand(0);
5559 B = BO0->getOperand(1);
5560 }
5561 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5562 C = BO1->getOperand(0);
5563 D = BO1->getOperand(1);
5564 }
5565
5566 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5567 if (A == Op1 && NoOp0WrapProblem)
5568 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5569 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5570 if (C == Op0 && NoOp1WrapProblem)
5571 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5572
5573 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5574 // (A - B) u>/u<= A --> B u>/u<= A
5575 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5576 return new ICmpInst(Pred, B, A);
5577 // C u</u>= (C - D) --> C u</u>= D
5578 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5579 return new ICmpInst(Pred, C, D);
5580 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5581 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5582 isKnownNonZero(B, Q))
5584 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5585 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5586 isKnownNonZero(D, Q))
5588
5589 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5590 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5591 return new ICmpInst(Pred, A, C);
5592
5593 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5594 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5595 return new ICmpInst(Pred, D, B);
5596
5597 // icmp (0-X) < cst --> x > -cst
5598 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5599 Value *X;
5600 if (match(BO0, m_Neg(m_Value(X))))
5601 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5602 if (RHSC->isNotMinSignedValue())
5603 return new ICmpInst(I.getSwappedPredicate(), X,
5604 ConstantExpr::getNeg(RHSC));
5605 }
5606
5607 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5608 return R;
5609 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5610 return R;
5611
5612 {
5613 // Try to remove shared multiplier from comparison:
5614 // X * Z pred Y * Z
5615 Value *X, *Y, *Z;
5616 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5617 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5618 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5619 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5620 if (ICmpInst::isSigned(Pred)) {
5621 if (Op0HasNSW && Op1HasNSW) {
5622 KnownBits ZKnown = computeKnownBits(Z, &I);
5623 if (ZKnown.isStrictlyPositive())
5624 return new ICmpInst(Pred, X, Y);
5625 if (ZKnown.isNegative())
5626 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5628 SQ.getWithInstruction(&I));
5629 if (LessThan && match(LessThan, m_One()))
5630 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5631 Constant::getNullValue(Z->getType()));
5632 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5633 SQ.getWithInstruction(&I));
5634 if (GreaterThan && match(GreaterThan, m_One()))
5635 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5636 }
5637 } else {
5638 bool NonZero;
5639 if (ICmpInst::isEquality(Pred)) {
5640 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5641 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5642 isKnownNonEqual(X, Y, SQ))
5643 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5644
5645 KnownBits ZKnown = computeKnownBits(Z, &I);
5646 // if Z % 2 != 0
5647 // X * Z eq/ne Y * Z -> X eq/ne Y
5648 if (ZKnown.countMaxTrailingZeros() == 0)
5649 return new ICmpInst(Pred, X, Y);
5650 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5651 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5652 // X * Z eq/ne Y * Z -> X eq/ne Y
5653 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5654 return new ICmpInst(Pred, X, Y);
5655 } else
5656 NonZero = isKnownNonZero(Z, Q);
5657
5658 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5659 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5660 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5661 return new ICmpInst(Pred, X, Y);
5662 }
5663 }
5664 }
5665
5666 BinaryOperator *SRem = nullptr;
5667 // icmp (srem X, Y), Y
5668 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5669 SRem = BO0;
5670 // icmp Y, (srem X, Y)
5671 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5672 Op0 == BO1->getOperand(1))
5673 SRem = BO1;
5674 if (SRem) {
5675 // We don't check hasOneUse to avoid increasing register pressure because
5676 // the value we use is the same value this instruction was already using.
5677 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5678 default:
5679 break;
5680 case ICmpInst::ICMP_EQ:
5681 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5682 case ICmpInst::ICMP_NE:
5683 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5684 case ICmpInst::ICMP_SGT:
5685 case ICmpInst::ICMP_SGE:
5686 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5688 case ICmpInst::ICMP_SLT:
5689 case ICmpInst::ICMP_SLE:
5690 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5692 }
5693 }
5694
5695 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5696 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5697 BO0->getOperand(1) == BO1->getOperand(1)) {
5698 switch (BO0->getOpcode()) {
5699 default:
5700 break;
5701 case Instruction::Add:
5702 case Instruction::Sub:
5703 case Instruction::Xor: {
5704 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5705 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5706
5707 const APInt *C;
5708 if (match(BO0->getOperand(1), m_APInt(C))) {
5709 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5710 if (C->isSignMask()) {
5711 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5712 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5713 }
5714
5715 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5716 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5717 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5718 NewPred = I.getSwappedPredicate(NewPred);
5719 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5720 }
5721 }
5722 break;
5723 }
5724 case Instruction::Mul: {
5725 if (!I.isEquality())
5726 break;
5727
5728 const APInt *C;
5729 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5730 !C->isOne()) {
5731 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5732 // Mask = -1 >> count-trailing-zeros(C).
5733 if (unsigned TZs = C->countr_zero()) {
5734 Constant *Mask = ConstantInt::get(
5735 BO0->getType(),
5736 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5737 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5738 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5739 return new ICmpInst(Pred, And1, And2);
5740 }
5741 }
5742 break;
5743 }
5744 case Instruction::UDiv:
5745 case Instruction::LShr:
5746 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5747 break;
5748 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5749
5750 case Instruction::SDiv:
5751 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5752 !BO0->isExact() || !BO1->isExact())
5753 break;
5754 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5755
5756 case Instruction::AShr:
5757 if (!BO0->isExact() || !BO1->isExact())
5758 break;
5759 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5760
5761 case Instruction::Shl: {
5762 bool NUW = Op0HasNUW && Op1HasNUW;
5763 bool NSW = Op0HasNSW && Op1HasNSW;
5764 if (!NUW && !NSW)
5765 break;
5766 if (!NSW && I.isSigned())
5767 break;
5768 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5769 }
5770 }
5771 }
5772
5773 if (BO0) {
5774 // Transform A & (L - 1) `ult` L --> L != 0
5775 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5776 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5777
5778 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5779 auto *Zero = Constant::getNullValue(BO0->getType());
5780 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5781 }
5782 }
5783
5784 // For unsigned predicates / eq / ne:
5785 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5786 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5787 if (!ICmpInst::isSigned(Pred)) {
5788 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5789 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5790 Constant::getNullValue(Op1->getType()));
5791 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5792 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5793 Constant::getNullValue(Op0->getType()), Op0);
5794 }
5795
5797 return replaceInstUsesWith(I, V);
5798
5799 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5800 return R;
5801
5803 return replaceInstUsesWith(I, V);
5804
5806 return replaceInstUsesWith(I, V);
5807
5808 return nullptr;
5809}
5810
5811/// Fold icmp Pred min|max(X, Y), Z.
5814 Value *Z, CmpPredicate Pred) {
5815 Value *X = MinMax->getLHS();
5816 Value *Y = MinMax->getRHS();
5817 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5818 return nullptr;
5819 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5820 // Revert the transform signed pred -> unsigned pred
5821 // TODO: We can flip the signedness of predicate if both operands of icmp
5822 // are negative.
5823 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5824 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5826 } else
5827 return nullptr;
5828 }
5829 SimplifyQuery Q = SQ.getWithInstruction(&I);
5830 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5831 if (!Val)
5832 return std::nullopt;
5833 if (match(Val, m_One()))
5834 return true;
5835 if (match(Val, m_Zero()))
5836 return false;
5837 return std::nullopt;
5838 };
5839 // Remove samesign here since it is illegal to keep it when we speculatively
5840 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5841 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5842 // -46, -32)`. `X` is allowed to be non-negative here.
5843 Pred = Pred.dropSameSign();
5844 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5845 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5846 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5847 return nullptr;
5848 if (!CmpXZ.has_value()) {
5849 std::swap(X, Y);
5850 std::swap(CmpXZ, CmpYZ);
5851 }
5852
5853 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5854 if (CmpYZ.has_value())
5855 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5856 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5857 };
5858
5859 switch (Pred) {
5860 case ICmpInst::ICMP_EQ:
5861 case ICmpInst::ICMP_NE: {
5862 // If X == Z:
5863 // Expr Result
5864 // min(X, Y) == Z X <= Y
5865 // max(X, Y) == Z X >= Y
5866 // min(X, Y) != Z X > Y
5867 // max(X, Y) != Z X < Y
5868 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5869 ICmpInst::Predicate NewPred =
5870 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5871 if (Pred == ICmpInst::ICMP_NE)
5872 NewPred = ICmpInst::getInversePredicate(NewPred);
5873 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5874 }
5875 // Otherwise (X != Z):
5876 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5877 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5878 if (!MinMaxCmpXZ.has_value()) {
5879 std::swap(X, Y);
5880 std::swap(CmpXZ, CmpYZ);
5881 // Re-check pre-condition X != Z
5882 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5883 break;
5884 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5885 }
5886 if (!MinMaxCmpXZ.has_value())
5887 break;
5888 if (*MinMaxCmpXZ) {
5889 // Expr Fact Result
5890 // min(X, Y) == Z X < Z false
5891 // max(X, Y) == Z X > Z false
5892 // min(X, Y) != Z X < Z true
5893 // max(X, Y) != Z X > Z true
5894 return replaceInstUsesWith(
5895 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5896 } else {
5897 // Expr Fact Result
5898 // min(X, Y) == Z X > Z Y == Z
5899 // max(X, Y) == Z X < Z Y == Z
5900 // min(X, Y) != Z X > Z Y != Z
5901 // max(X, Y) != Z X < Z Y != Z
5902 return FoldIntoCmpYZ();
5903 }
5904 break;
5905 }
5906 case ICmpInst::ICMP_SLT:
5907 case ICmpInst::ICMP_ULT:
5908 case ICmpInst::ICMP_SLE:
5909 case ICmpInst::ICMP_ULE:
5910 case ICmpInst::ICMP_SGT:
5911 case ICmpInst::ICMP_UGT:
5912 case ICmpInst::ICMP_SGE:
5913 case ICmpInst::ICMP_UGE: {
5914 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5915 if (*CmpXZ) {
5916 if (IsSame) {
5917 // Expr Fact Result
5918 // min(X, Y) < Z X < Z true
5919 // min(X, Y) <= Z X <= Z true
5920 // max(X, Y) > Z X > Z true
5921 // max(X, Y) >= Z X >= Z true
5922 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5923 } else {
5924 // Expr Fact Result
5925 // max(X, Y) < Z X < Z Y < Z
5926 // max(X, Y) <= Z X <= Z Y <= Z
5927 // min(X, Y) > Z X > Z Y > Z
5928 // min(X, Y) >= Z X >= Z Y >= Z
5929 return FoldIntoCmpYZ();
5930 }
5931 } else {
5932 if (IsSame) {
5933 // Expr Fact Result
5934 // min(X, Y) < Z X >= Z Y < Z
5935 // min(X, Y) <= Z X > Z Y <= Z
5936 // max(X, Y) > Z X <= Z Y > Z
5937 // max(X, Y) >= Z X < Z Y >= Z
5938 return FoldIntoCmpYZ();
5939 } else {
5940 // Expr Fact Result
5941 // max(X, Y) < Z X >= Z false
5942 // max(X, Y) <= Z X > Z false
5943 // min(X, Y) > Z X <= Z false
5944 // min(X, Y) >= Z X < Z false
5945 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5946 }
5947 }
5948 break;
5949 }
5950 default:
5951 break;
5952 }
5953
5954 return nullptr;
5955}
5956
5957/// Match and fold patterns like:
5958/// icmp eq/ne X, min(max(X, Lo), Hi)
5959/// which represents a range check and can be represented as a ConstantRange.
5960///
5961/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5962/// (X - Lo) u< (Hi + 1 - Lo)
5963/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5964/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5966 MinMaxIntrinsic *Min) {
5967 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5968 return nullptr;
5969
5970 const APInt *Lo = nullptr, *Hi = nullptr;
5971 if (Min->isSigned()) {
5972 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
5973 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
5974 return nullptr;
5975 } else {
5976 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
5977 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
5978 return nullptr;
5979 }
5980
5983 APInt C, Offset;
5984 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5985 CR.getEquivalentICmp(Pred, C, Offset);
5986 else
5987 CR.inverse().getEquivalentICmp(Pred, C, Offset);
5988
5989 if (!Offset.isZero())
5990 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
5991
5992 return replaceInstUsesWith(
5993 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
5994}
5995
5996// Canonicalize checking for a power-of-2-or-zero value:
5998 InstCombiner::BuilderTy &Builder) {
5999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6000 const CmpInst::Predicate Pred = I.getPredicate();
6001 Value *A = nullptr;
6002 bool CheckIs;
6003 if (I.isEquality()) {
6004 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6005 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6006 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6007 m_Deferred(A)))) ||
6008 !match(Op1, m_ZeroInt()))
6009 A = nullptr;
6010
6011 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6012 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6013 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6014 A = Op1;
6015 else if (match(Op1,
6017 A = Op0;
6018
6019 CheckIs = Pred == ICmpInst::ICMP_EQ;
6020 } else if (ICmpInst::isUnsigned(Pred)) {
6021 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6022 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6023
6024 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6026 m_Specific(Op1))))) {
6027 A = Op1;
6028 CheckIs = Pred == ICmpInst::ICMP_UGE;
6029 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6031 m_Specific(Op0))))) {
6032 A = Op0;
6033 CheckIs = Pred == ICmpInst::ICMP_ULE;
6034 }
6035 }
6036
6037 if (A) {
6038 Type *Ty = A->getType();
6039 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6040 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6041 ConstantInt::get(Ty, 2))
6042 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6043 ConstantInt::get(Ty, 1));
6044 }
6045
6046 return nullptr;
6047}
6048
6049/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6050using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6052 bool AllowRecursion) {
6054 if (!Inst || !Inst->hasOneUse())
6055 return;
6056
6057 switch (Inst->getOpcode()) {
6058 case Instruction::Add:
6059 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6060 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6061 break;
6062 case Instruction::Sub:
6063 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6064 break;
6065 case Instruction::Xor:
6066 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6067 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6068 break;
6069 case Instruction::Shl:
6070 if (Inst->hasNoSignedWrap())
6071 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6072 if (Inst->hasNoUnsignedWrap())
6073 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6074 break;
6075 case Instruction::Select:
6076 if (AllowRecursion) {
6077 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6078 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6079 }
6080 break;
6081 default:
6082 break;
6083 }
6084}
6085
6087
6092
6094 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6095 }
6097 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6098 }
6099 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6101 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6102 }
6103 bool isValid() const { return Kind != OffsetKind::Invalid; }
6105 switch (Kind) {
6107 llvm_unreachable("Invalid offset result");
6108 case OffsetKind::Value:
6109 return V0;
6110 case OffsetKind::Select:
6111 return Builder.CreateSelect(
6112 V0, V1, V2, "", ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
6113 }
6114 llvm_unreachable("Unknown OffsetKind enum");
6115 }
6116};
6117
6118/// Offset both sides of an equality icmp to see if we can save some
6119/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6120/// Note: This operation should not introduce poison.
6122 InstCombiner::BuilderTy &Builder,
6123 const SimplifyQuery &SQ) {
6124 assert(I.isEquality() && "Expected an equality icmp");
6125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6126 if (!Op0->getType()->isIntOrIntVectorTy())
6127 return nullptr;
6128
6129 SmallVector<OffsetOp, 4> OffsetOps;
6130 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6131 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6132
6133 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6134 switch (BinOpc) {
6135 // V = shl nsw X, RHS => X = ashr V, RHS
6136 case Instruction::AShr: {
6137 const APInt *CV, *CRHS;
6138 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6139 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6141 return nullptr;
6142 break;
6143 }
6144 // V = shl nuw X, RHS => X = lshr V, RHS
6145 case Instruction::LShr: {
6146 const APInt *CV, *CRHS;
6147 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6148 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6150 return nullptr;
6151 break;
6152 }
6153 default:
6154 break;
6155 }
6156
6157 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6158 if (!Simplified)
6159 return nullptr;
6160 // Reject constant expressions as they don't simplify things.
6161 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6162 return nullptr;
6163 // Check if the transformation introduces poison.
6164 return impliesPoison(RHS, V) ? Simplified : nullptr;
6165 };
6166
6167 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6168 Value *RHS) -> OffsetResult {
6169 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6170 if (!Sel->hasOneUse())
6171 return OffsetResult::invalid();
6172 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6173 if (!TrueVal)
6174 return OffsetResult::invalid();
6175 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6176 if (!FalseVal)
6177 return OffsetResult::invalid();
6178 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6179 }
6180 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6181 return OffsetResult::value(Simplified);
6182 return OffsetResult::invalid();
6183 };
6184
6185 for (auto [BinOp, RHS] : OffsetOps) {
6186 auto BinOpc = static_cast<unsigned>(BinOp);
6187
6188 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6189 if (!Op0Result.isValid())
6190 continue;
6191 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6192 if (!Op1Result.isValid())
6193 continue;
6194
6195 Value *NewLHS = Op0Result.materialize(Builder);
6196 Value *NewRHS = Op1Result.materialize(Builder);
6197 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6198 }
6199
6200 return nullptr;
6201}
6202
6204 if (!I.isEquality())
6205 return nullptr;
6206
6207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6208 const CmpInst::Predicate Pred = I.getPredicate();
6209 Value *A, *B, *C, *D;
6210 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6211 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6212 Value *OtherVal = A == Op1 ? B : A;
6213 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6214 }
6215
6216 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6217 // A^c1 == C^c2 --> A == C^(c1^c2)
6218 ConstantInt *C1, *C2;
6219 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6220 Op1->hasOneUse()) {
6221 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6222 Value *Xor = Builder.CreateXor(C, NC);
6223 return new ICmpInst(Pred, A, Xor);
6224 }
6225
6226 // A^B == A^D -> B == D
6227 if (A == C)
6228 return new ICmpInst(Pred, B, D);
6229 if (A == D)
6230 return new ICmpInst(Pred, B, C);
6231 if (B == C)
6232 return new ICmpInst(Pred, A, D);
6233 if (B == D)
6234 return new ICmpInst(Pred, A, C);
6235 }
6236 }
6237
6238 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6239 // A == (A^B) -> B == 0
6240 Value *OtherVal = A == Op0 ? B : A;
6241 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6242 }
6243
6244 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6245 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6246 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6247 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6248
6249 if (A == C) {
6250 X = B;
6251 Y = D;
6252 Z = A;
6253 } else if (A == D) {
6254 X = B;
6255 Y = C;
6256 Z = A;
6257 } else if (B == C) {
6258 X = A;
6259 Y = D;
6260 Z = B;
6261 } else if (B == D) {
6262 X = A;
6263 Y = C;
6264 Z = B;
6265 }
6266
6267 if (X) {
6268 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6269 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6270 // instructions.
6271 const APInt *C0, *C1;
6272 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6273 (*C0 ^ *C1).isNegatedPowerOf2();
6274
6275 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6276 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6277 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6278 int UseCnt =
6279 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6280 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6281 if (XorIsNegP2 || UseCnt >= 2) {
6282 // Build (X^Y) & Z
6283 Op1 = Builder.CreateXor(X, Y);
6284 Op1 = Builder.CreateAnd(Op1, Z);
6285 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6286 }
6287 }
6288 }
6289
6290 {
6291 // Similar to above, but specialized for constant because invert is needed:
6292 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6293 Value *X, *Y;
6294 Constant *C;
6295 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6296 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6297 Value *Xor = Builder.CreateXor(X, Y);
6298 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6299 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6300 }
6301 }
6302
6303 if (match(Op1, m_ZExt(m_Value(A))) &&
6304 (Op0->hasOneUse() || Op1->hasOneUse())) {
6305 // (B & (Pow2C-1)) == zext A --> A == trunc B
6306 // (B & (Pow2C-1)) != zext A --> A != trunc B
6307 const APInt *MaskC;
6308 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6309 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6310 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6311 }
6312
6313 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6314 // For lshr and ashr pairs.
6315 const APInt *AP1, *AP2;
6316 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6317 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6318 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6319 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6320 if (*AP1 != *AP2)
6321 return nullptr;
6322 unsigned TypeBits = AP1->getBitWidth();
6323 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6324 if (ShAmt < TypeBits && ShAmt != 0) {
6325 ICmpInst::Predicate NewPred =
6327 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6328 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6329 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6330 }
6331 }
6332
6333 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6334 ConstantInt *Cst1;
6335 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6336 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6337 unsigned TypeBits = Cst1->getBitWidth();
6338 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6339 if (ShAmt < TypeBits && ShAmt != 0) {
6340 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6341 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6342 Value *And =
6343 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6344 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6345 }
6346 }
6347
6348 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6349 // "icmp (and X, mask), cst"
6350 uint64_t ShAmt = 0;
6351 if (Op0->hasOneUse() &&
6352 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6353 match(Op1, m_ConstantInt(Cst1)) &&
6354 // Only do this when A has multiple uses. This is most important to do
6355 // when it exposes other optimizations.
6356 !A->hasOneUse()) {
6357 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6358
6359 if (ShAmt < ASize) {
6360 APInt MaskV =
6362 MaskV <<= ShAmt;
6363
6364 APInt CmpV = Cst1->getValue().zext(ASize);
6365 CmpV <<= ShAmt;
6366
6367 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6368 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6369 }
6370 }
6371
6373 return ICmp;
6374
6375 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6376 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6377 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6378 // few steps of instcombine.
6379 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6380 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6382 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6383 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6385 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6386 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6388 Add, ConstantInt::get(A->getType(), C.shl(1)));
6389 }
6390
6391 // Canonicalize:
6392 // Assume B_Pow2 != 0
6393 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6394 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6395 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6396 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6397 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6399
6400 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6401 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6402 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6403 ConstantInt::getNullValue(Op1->getType()));
6404
6405 // Canonicalize:
6406 // icmp eq/ne X, OneUse(rotate-right(X))
6407 // -> icmp eq/ne X, rotate-left(X)
6408 // We generally try to convert rotate-right -> rotate-left, this just
6409 // canonicalizes another case.
6410 if (match(&I, m_c_ICmp(m_Value(A),
6412 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6413 return new ICmpInst(
6414 Pred, A,
6415 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6416
6417 // Canonicalize:
6418 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6419 Constant *Cst;
6422 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6423
6424 {
6425 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6426 auto m_Matcher =
6429 m_Sub(m_Value(B), m_Deferred(A)));
6430 std::optional<bool> IsZero = std::nullopt;
6431 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6432 m_Deferred(A))))
6433 IsZero = false;
6434 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6435 else if (match(&I,
6436 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6437 IsZero = true;
6438
6439 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6440 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6441 // -> (icmp eq/ne (and X, P2), 0)
6442 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6443 // -> (icmp eq/ne (and X, P2), P2)
6444 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6445 *IsZero ? A
6446 : ConstantInt::getNullValue(A->getType()));
6447 }
6448
6449 if (auto *Res = foldICmpEqualityWithOffset(
6450 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6451 return Res;
6452
6453 return nullptr;
6454}
6455
6457 ICmpInst::Predicate Pred = ICmp.getPredicate();
6458 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6459
6460 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6461 // The trunc masks high bits while the compare may effectively mask low bits.
6462 Value *X;
6463 const APInt *C;
6464 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6465 return nullptr;
6466
6467 // This matches patterns corresponding to tests of the signbit as well as:
6468 // (trunc X) pred C2 --> (X & Mask) == C
6469 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6470 /*AllowNonZeroC=*/true)) {
6471 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6472 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6473 return new ICmpInst(Res->Pred, And, C);
6474 }
6475
6476 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6477 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6478 if (II->getIntrinsicID() == Intrinsic::cttz ||
6479 II->getIntrinsicID() == Intrinsic::ctlz) {
6480 unsigned MaxRet = SrcBits;
6481 // If the "is_zero_poison" argument is set, then we know at least
6482 // one bit is set in the input, so the result is always at least one
6483 // less than the full bitwidth of that input.
6484 if (match(II->getArgOperand(1), m_One()))
6485 MaxRet--;
6486
6487 // Make sure the destination is wide enough to hold the largest output of
6488 // the intrinsic.
6489 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6490 if (Instruction *I =
6491 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6492 return I;
6493 }
6494 }
6495
6496 return nullptr;
6497}
6498
6500 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6501 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6502 Value *X;
6503 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6504 return nullptr;
6505
6506 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6507 bool IsSignedCmp = ICmp.isSigned();
6508
6509 // icmp Pred (ext X), (ext Y)
6510 Value *Y;
6511 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6512 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6513 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6514
6515 if (IsZext0 != IsZext1) {
6516 // If X and Y and both i1
6517 // (icmp eq/ne (zext X) (sext Y))
6518 // eq -> (icmp eq (or X, Y), 0)
6519 // ne -> (icmp ne (or X, Y), 0)
6520 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6521 Y->getType()->isIntOrIntVectorTy(1))
6522 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6523 Constant::getNullValue(X->getType()));
6524
6525 // If we have mismatched casts and zext has the nneg flag, we can
6526 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6527
6528 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6529 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6530
6531 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6532 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6533
6534 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6535 IsSignedExt = true;
6536 else
6537 return nullptr;
6538 }
6539
6540 // Not an extension from the same type?
6541 Type *XTy = X->getType(), *YTy = Y->getType();
6542 if (XTy != YTy) {
6543 // One of the casts must have one use because we are creating a new cast.
6544 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6545 return nullptr;
6546 // Extend the narrower operand to the type of the wider operand.
6547 CastInst::CastOps CastOpcode =
6548 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6549 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6550 X = Builder.CreateCast(CastOpcode, X, YTy);
6551 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6552 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6553 else
6554 return nullptr;
6555 }
6556
6557 // (zext X) == (zext Y) --> X == Y
6558 // (sext X) == (sext Y) --> X == Y
6559 if (ICmp.isEquality())
6560 return new ICmpInst(ICmp.getPredicate(), X, Y);
6561
6562 // A signed comparison of sign extended values simplifies into a
6563 // signed comparison.
6564 if (IsSignedCmp && IsSignedExt)
6565 return new ICmpInst(ICmp.getPredicate(), X, Y);
6566
6567 // The other three cases all fold into an unsigned comparison.
6568 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6569 }
6570
6571 // Below here, we are only folding a compare with constant.
6572 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6573 if (!C)
6574 return nullptr;
6575
6576 // If a lossless truncate is possible...
6577 Type *SrcTy = CastOp0->getSrcTy();
6578 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6579 if (Res) {
6580 if (ICmp.isEquality())
6581 return new ICmpInst(ICmp.getPredicate(), X, Res);
6582
6583 // A signed comparison of sign extended values simplifies into a
6584 // signed comparison.
6585 if (IsSignedExt && IsSignedCmp)
6586 return new ICmpInst(ICmp.getPredicate(), X, Res);
6587
6588 // The other three cases all fold into an unsigned comparison.
6589 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6590 }
6591
6592 // The re-extended constant changed, partly changed (in the case of a vector),
6593 // or could not be determined to be equal (in the case of a constant
6594 // expression), so the constant cannot be represented in the shorter type.
6595 // All the cases that fold to true or false will have already been handled
6596 // by simplifyICmpInst, so only deal with the tricky case.
6597 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6598 return nullptr;
6599
6600 // Is source op positive?
6601 // icmp ult (sext X), C --> icmp sgt X, -1
6602 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6604
6605 // Is source op negative?
6606 // icmp ugt (sext X), C --> icmp slt X, 0
6607 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6609}
6610
6611/// Handle icmp (cast x), (cast or constant).
6613 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6614 // icmp compares only pointer's value.
6615 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6616 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6617 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6618 if (SimplifiedOp0 || SimplifiedOp1)
6619 return new ICmpInst(ICmp.getPredicate(),
6620 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6621 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6622
6623 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6624 Value *Op1 = ICmp.getOperand(1);
6625 if (!CastOp0)
6626 return nullptr;
6627 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6628 return nullptr;
6629
6630 Value *Op0Src = CastOp0->getOperand(0);
6631 Type *SrcTy = CastOp0->getSrcTy();
6632 Type *DestTy = CastOp0->getDestTy();
6633
6634 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6635 // integer type is the same size as the pointer type.
6636 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6637 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6638 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6639 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6640 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6641 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6642 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6643 };
6644 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6645 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6646 Value *NewOp1 = nullptr;
6647 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6648 NewOp1 = PtrToIntOp1->getOperand(0);
6649 HasPtrToInt = true;
6650 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6651 NewOp1 = PtrToAddrOp1->getOperand(0);
6652 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6653 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6654 }
6655
6656 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6657 // check PtrWidth.
6658 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6659 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6660 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6661 }
6662
6663 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6664 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6665 CompatibleSizes(DestTy, SrcTy)) {
6666 Value *NewOp1 = nullptr;
6667 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6668 Value *IntSrc = IntToPtrOp1->getOperand(0);
6669 if (IntSrc->getType() == Op0Src->getType())
6670 NewOp1 = IntToPtrOp1->getOperand(0);
6671 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6672 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6673 }
6674
6675 if (NewOp1)
6676 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6677 }
6678
6679 if (Instruction *R = foldICmpWithTrunc(ICmp))
6680 return R;
6681
6682 return foldICmpWithZextOrSext(ICmp);
6683}
6684
6686 bool IsSigned) {
6687 switch (BinaryOp) {
6688 default:
6689 llvm_unreachable("Unsupported binary op");
6690 case Instruction::Add:
6691 case Instruction::Sub:
6692 return match(RHS, m_Zero());
6693 case Instruction::Mul:
6694 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6695 match(RHS, m_One());
6696 }
6697}
6698
6701 bool IsSigned, Value *LHS, Value *RHS,
6702 Instruction *CxtI) const {
6703 switch (BinaryOp) {
6704 default:
6705 llvm_unreachable("Unsupported binary op");
6706 case Instruction::Add:
6707 if (IsSigned)
6708 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6709 else
6710 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6711 case Instruction::Sub:
6712 if (IsSigned)
6713 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6714 else
6715 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6716 case Instruction::Mul:
6717 if (IsSigned)
6718 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6719 else
6720 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6721 }
6722}
6723
6724bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6725 bool IsSigned, Value *LHS,
6726 Value *RHS, Instruction &OrigI,
6727 Value *&Result,
6728 Constant *&Overflow) {
6729 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6730 std::swap(LHS, RHS);
6731
6732 // If the overflow check was an add followed by a compare, the insertion point
6733 // may be pointing to the compare. We want to insert the new instructions
6734 // before the add in case there are uses of the add between the add and the
6735 // compare.
6736 Builder.SetInsertPoint(&OrigI);
6737
6738 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6739 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6740 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6741
6742 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6743 Result = LHS;
6744 Overflow = ConstantInt::getFalse(OverflowTy);
6745 return true;
6746 }
6747
6748 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6750 return false;
6753 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6754 Result->takeName(&OrigI);
6755 Overflow = ConstantInt::getTrue(OverflowTy);
6756 return true;
6758 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6759 Result->takeName(&OrigI);
6760 Overflow = ConstantInt::getFalse(OverflowTy);
6761 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6762 if (IsSigned)
6763 Inst->setHasNoSignedWrap();
6764 else
6765 Inst->setHasNoUnsignedWrap();
6766 }
6767 return true;
6768 }
6769
6770 llvm_unreachable("Unexpected overflow result");
6771}
6772
6773/// Recognize and process idiom involving test for multiplication
6774/// overflow.
6775///
6776/// The caller has matched a pattern of the form:
6777/// I = cmp u (mul(zext A, zext B), V
6778/// The function checks if this is a test for overflow and if so replaces
6779/// multiplication with call to 'mul.with.overflow' intrinsic.
6780///
6781/// \param I Compare instruction.
6782/// \param MulVal Result of 'mult' instruction. It is one of the arguments of
6783/// the compare instruction. Must be of integer type.
6784/// \param OtherVal The other argument of compare instruction.
6785/// \returns Instruction which must replace the compare instruction, NULL if no
6786/// replacement required.
6788 const APInt *OtherVal,
6789 InstCombinerImpl &IC) {
6790 // Don't bother doing this transformation for pointers, don't do it for
6791 // vectors.
6792 if (!isa<IntegerType>(MulVal->getType()))
6793 return nullptr;
6794
6795 auto *MulInstr = dyn_cast<Instruction>(MulVal);
6796 if (!MulInstr)
6797 return nullptr;
6798 assert(MulInstr->getOpcode() == Instruction::Mul);
6799
6800 auto *LHS = cast<ZExtInst>(MulInstr->getOperand(0)),
6801 *RHS = cast<ZExtInst>(MulInstr->getOperand(1));
6802 assert(LHS->getOpcode() == Instruction::ZExt);
6803 assert(RHS->getOpcode() == Instruction::ZExt);
6804 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6805
6806 // Calculate type and width of the result produced by mul.with.overflow.
6807 Type *TyA = A->getType(), *TyB = B->getType();
6808 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6809 WidthB = TyB->getPrimitiveSizeInBits();
6810 unsigned MulWidth;
6811 Type *MulType;
6812 if (WidthB > WidthA) {
6813 MulWidth = WidthB;
6814 MulType = TyB;
6815 } else {
6816 MulWidth = WidthA;
6817 MulType = TyA;
6818 }
6819
6820 // In order to replace the original mul with a narrower mul.with.overflow,
6821 // all uses must ignore upper bits of the product. The number of used low
6822 // bits must be not greater than the width of mul.with.overflow.
6823 if (MulVal->hasNUsesOrMore(2))
6824 for (User *U : MulVal->users()) {
6825 if (U == &I)
6826 continue;
6827 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6828 // Check if truncation ignores bits above MulWidth.
6829 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6830 if (TruncWidth > MulWidth)
6831 return nullptr;
6832 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6833 // Check if AND ignores bits above MulWidth.
6834 if (BO->getOpcode() != Instruction::And)
6835 return nullptr;
6836 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6837 const APInt &CVal = CI->getValue();
6838 if (CVal.getBitWidth() - CVal.countl_zero() > MulWidth)
6839 return nullptr;
6840 } else {
6841 // In this case we could have the operand of the binary operation
6842 // being defined in another block, and performing the replacement
6843 // could break the dominance relation.
6844 return nullptr;
6845 }
6846 } else {
6847 // Other uses prohibit this transformation.
6848 return nullptr;
6849 }
6850 }
6851
6852 // Recognize patterns
6853 switch (I.getPredicate()) {
6854 case ICmpInst::ICMP_UGT: {
6855 // Recognize pattern:
6856 // mulval = mul(zext A, zext B)
6857 // cmp ugt mulval, max
6858 APInt MaxVal = APInt::getMaxValue(MulWidth);
6859 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6860 if (MaxVal.eq(*OtherVal))
6861 break; // Recognized
6862 return nullptr;
6863 }
6864
6865 case ICmpInst::ICMP_ULT: {
6866 // Recognize pattern:
6867 // mulval = mul(zext A, zext B)
6868 // cmp ule mulval, max + 1
6869 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), MulWidth);
6870 if (MaxVal.eq(*OtherVal))
6871 break; // Recognized
6872 return nullptr;
6873 }
6874
6875 default:
6876 return nullptr;
6877 }
6878
6879 InstCombiner::BuilderTy &Builder = IC.Builder;
6880 Builder.SetInsertPoint(MulInstr);
6881
6882 // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
6883 Value *MulA = A, *MulB = B;
6884 if (WidthA < MulWidth)
6885 MulA = Builder.CreateZExt(A, MulType);
6886 if (WidthB < MulWidth)
6887 MulB = Builder.CreateZExt(B, MulType);
6888 Value *Call =
6889 Builder.CreateIntrinsic(Intrinsic::umul_with_overflow, MulType,
6890 {MulA, MulB}, /*FMFSource=*/nullptr, "umul");
6891 IC.addToWorklist(MulInstr);
6892
6893 // If there are uses of mul result other than the comparison, we know that
6894 // they are truncation or binary AND. Change them to use result of
6895 // mul.with.overflow and adjust properly mask/size.
6896 if (MulVal->hasNUsesOrMore(2)) {
6897 Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
6898 for (User *U : make_early_inc_range(MulVal->users())) {
6899 if (U == &I)
6900 continue;
6901 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6902 if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
6903 IC.replaceInstUsesWith(*TI, Mul);
6904 else
6905 TI->setOperand(0, Mul);
6906 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6907 assert(BO->getOpcode() == Instruction::And);
6908 // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
6909 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6910 APInt ShortMask = CI->getValue().trunc(MulWidth);
6911 Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
6912 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6913 IC.replaceInstUsesWith(*BO, Zext);
6914 } else {
6915 llvm_unreachable("Unexpected Binary operation");
6916 }
6918 }
6919 }
6920
6921 // The original icmp gets replaced with the overflow value, maybe inverted
6922 // depending on predicate.
6923 if (I.getPredicate() == ICmpInst::ICMP_ULT) {
6924 Value *Res = Builder.CreateExtractValue(Call, 1);
6925 return BinaryOperator::CreateNot(Res);
6926 }
6927
6928 return ExtractValueInst::Create(Call, 1);
6929}
6930
6931/// When performing a comparison against a constant, it is possible that not all
6932/// the bits in the LHS are demanded. This helper method computes the mask that
6933/// IS demanded.
6935 const APInt *RHS;
6936 if (!match(I.getOperand(1), m_APInt(RHS)))
6938
6939 // If this is a normal comparison, it demands all bits. If it is a sign bit
6940 // comparison, it only demands the sign bit.
6941 bool UnusedBit;
6942 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
6944
6945 switch (I.getPredicate()) {
6946 // For a UGT comparison, we don't care about any bits that
6947 // correspond to the trailing ones of the comparand. The value of these
6948 // bits doesn't impact the outcome of the comparison, because any value
6949 // greater than the RHS must differ in a bit higher than these due to carry.
6950 case ICmpInst::ICMP_UGT:
6951 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
6952
6953 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6954 // Any value less than the RHS must differ in a higher bit because of carries.
6955 case ICmpInst::ICMP_ULT:
6956 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
6957
6958 default:
6960 }
6961}
6962
6963/// Check that one use is in the same block as the definition and all
6964/// other uses are in blocks dominated by a given block.
6965///
6966/// \param DI Definition
6967/// \param UI Use
6968/// \param DB Block that must dominate all uses of \p DI outside
6969/// the parent block
6970/// \return true when \p UI is the only use of \p DI in the parent block
6971/// and all other uses of \p DI are in blocks dominated by \p DB.
6972///
6974 const Instruction *UI,
6975 const BasicBlock *DB) const {
6976 assert(DI && UI && "Instruction not defined\n");
6977 // Ignore incomplete definitions.
6978 if (!DI->getParent())
6979 return false;
6980 // DI and UI must be in the same block.
6981 if (DI->getParent() != UI->getParent())
6982 return false;
6983 // Protect from self-referencing blocks.
6984 if (DI->getParent() == DB)
6985 return false;
6986 for (const User *U : DI->users()) {
6987 auto *Usr = cast<Instruction>(U);
6988 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
6989 return false;
6990 }
6991 return true;
6992}
6993
6994/// Return true when the instruction sequence within a block is select-cmp-br.
6996 const BasicBlock *BB = SI->getParent();
6997 if (!BB)
6998 return false;
7000 if (!BI)
7001 return false;
7002 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7003 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7004 return false;
7005 return true;
7006}
7007
7008/// True when a select result is replaced by one of its operands
7009/// in select-icmp sequence. This will eventually result in the elimination
7010/// of the select.
7011///
7012/// \param SI Select instruction
7013/// \param Icmp Compare instruction
7014/// \param SIOpd Operand that replaces the select
7015///
7016/// Notes:
7017/// - The replacement is global and requires dominator information
7018/// - The caller is responsible for the actual replacement
7019///
7020/// Example:
7021///
7022/// entry:
7023/// %4 = select i1 %3, %C* %0, %C* null
7024/// %5 = icmp eq %C* %4, null
7025/// br i1 %5, label %9, label %7
7026/// ...
7027/// ; <label>:7 ; preds = %entry
7028/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7029/// ...
7030///
7031/// can be transformed to
7032///
7033/// %5 = icmp eq %C* %0, null
7034/// %6 = select i1 %3, i1 %5, i1 true
7035/// br i1 %6, label %9, label %7
7036/// ...
7037/// ; <label>:7 ; preds = %entry
7038/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7039///
7040/// Similar when the first operand of the select is a constant or/and
7041/// the compare is for not equal rather than equal.
7042///
7043/// NOTE: The function is only called when the select and compare constants
7044/// are equal, the optimization can work only for EQ predicates. This is not a
7045/// major restriction since a NE compare should be 'normalized' to an equal
7046/// compare, which usually happens in the combiner and test case
7047/// select-cmp-br.ll checks for it.
7049 const ICmpInst *Icmp,
7050 const unsigned SIOpd) {
7051 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7053 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7054 // The check for the single predecessor is not the best that can be
7055 // done. But it protects efficiently against cases like when SI's
7056 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7057 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7058 // replaced can be reached on either path. So the uniqueness check
7059 // guarantees that the path all uses of SI (outside SI's parent) are on
7060 // is disjoint from all other paths out of SI. But that information
7061 // is more expensive to compute, and the trade-off here is in favor
7062 // of compile-time. It should also be noticed that we check for a single
7063 // predecessor and not only uniqueness. This to handle the situation when
7064 // Succ and Succ1 points to the same basic block.
7065 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7066 NumSel++;
7067 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7068 return true;
7069 }
7070 }
7071 return false;
7072}
7073
7074/// Try to fold the comparison based on range information we can get by checking
7075/// whether bits are known to be zero or one in the inputs.
7077 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7078 Type *Ty = Op0->getType();
7079 ICmpInst::Predicate Pred = I.getPredicate();
7080
7081 // Get scalar or pointer size.
7082 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7083 ? Ty->getScalarSizeInBits()
7084 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7085
7086 if (!BitWidth)
7087 return nullptr;
7088
7089 KnownBits Op0Known(BitWidth);
7090 KnownBits Op1Known(BitWidth);
7091
7092 {
7093 // Don't use dominating conditions when folding icmp using known bits. This
7094 // may convert signed into unsigned predicates in ways that other passes
7095 // (especially IndVarSimplify) may not be able to reliably undo.
7096 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7098 Op0Known, Q))
7099 return &I;
7100
7101 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7102 return &I;
7103 }
7104
7105 // If an unsigned samesign comparison is not poison, both operands have the
7106 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7107 // values so the existing range folds can use that constraint.
7108 if (I.hasSameSign() && I.isUnsigned()) {
7109 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7110 if (To.isNegative() || To.isNonNegative())
7111 return;
7112 if (From.isNegative())
7113 To.makeNegative();
7114 else if (From.isNonNegative())
7115 To.makeNonNegative();
7116 };
7117 PropagateSignBit(Op0Known, Op1Known);
7118 PropagateSignBit(Op1Known, Op0Known);
7119 }
7120
7121 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7122 return new ICmpInst(
7123 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7124 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7125 return new ICmpInst(
7126 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7127
7128 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7129 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7130
7131 // Given the known and unknown bits, compute a range that the LHS could be
7132 // in. Compute the Min, Max and RHS values based on the known bits. For the
7133 // EQ and NE we use unsigned values.
7134 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7135 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7136 if (I.isSigned()) {
7137 Op0Min = Op0Known.getSignedMinValue();
7138 Op0Max = Op0Known.getSignedMaxValue();
7139 Op1Min = Op1Known.getSignedMinValue();
7140 Op1Max = Op1Known.getSignedMaxValue();
7141 } else {
7142 Op0Min = Op0Known.getMinValue();
7143 Op0Max = Op0Known.getMaxValue();
7144 Op1Min = Op1Known.getMinValue();
7145 Op1Max = Op1Known.getMaxValue();
7146 }
7147
7148 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7149 // min/max canonical compare with some other compare. That could lead to
7150 // conflict with select canonicalization and infinite looping.
7151 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7152 auto isMinMaxCmp = [&](Instruction &Cmp) {
7153 if (!Cmp.hasOneUse())
7154 return false;
7155 Value *A, *B;
7156 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7158 return false;
7159 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7160 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7161 };
7162 if (!isMinMaxCmp(I)) {
7163 switch (Pred) {
7164 default:
7165 break;
7166 case ICmpInst::ICMP_ULT: {
7167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7168 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7169 const APInt *CmpC;
7170 if (match(Op1, m_APInt(CmpC))) {
7171 // A <u C -> A == C-1 if min(A)+1 == C
7172 if (*CmpC == Op0Min + 1)
7173 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7174 ConstantInt::get(Op1->getType(), *CmpC - 1));
7175 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7176 // exceeds the log2 of C.
7177 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7178 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7179 Constant::getNullValue(Op1->getType()));
7180 }
7181 break;
7182 }
7183 case ICmpInst::ICMP_UGT: {
7184 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7185 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7186 const APInt *CmpC;
7187 if (match(Op1, m_APInt(CmpC))) {
7188 // A >u C -> A == C+1 if max(a)-1 == C
7189 if (*CmpC == Op0Max - 1)
7190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7191 ConstantInt::get(Op1->getType(), *CmpC + 1));
7192 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7193 // exceeds the log2 of C.
7194 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7195 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7196 Constant::getNullValue(Op1->getType()));
7197 }
7198 break;
7199 }
7200 case ICmpInst::ICMP_SLT: {
7201 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7202 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7203 const APInt *CmpC;
7204 if (match(Op1, m_APInt(CmpC))) {
7205 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7206 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7207 ConstantInt::get(Op1->getType(), *CmpC - 1));
7208 }
7209 break;
7210 }
7211 case ICmpInst::ICMP_SGT: {
7212 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7213 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7214 const APInt *CmpC;
7215 if (match(Op1, m_APInt(CmpC))) {
7216 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7217 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7218 ConstantInt::get(Op1->getType(), *CmpC + 1));
7219 }
7220 break;
7221 }
7222 }
7223 }
7224
7225 // Based on the range information we know about the LHS, see if we can
7226 // simplify this comparison. For example, (x&4) < 8 is always true.
7227 switch (Pred) {
7228 default:
7229 break;
7230 case ICmpInst::ICMP_EQ:
7231 case ICmpInst::ICMP_NE: {
7232 // If all bits are known zero except for one, then we know at most one bit
7233 // is set. If the comparison is against zero, then this is a check to see if
7234 // *that* bit is set.
7235 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7236 if (Op1Known.isZero()) {
7237 // If the LHS is an AND with the same constant, look through it.
7238 Value *LHS = nullptr;
7239 const APInt *LHSC;
7240 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7241 *LHSC != Op0KnownZeroInverted)
7242 LHS = Op0;
7243
7244 Value *X;
7245 const APInt *C1;
7246 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7247 Type *XTy = X->getType();
7248 unsigned Log2C1 = C1->countr_zero();
7249 APInt C2 = Op0KnownZeroInverted;
7250 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7251 if (C2Pow2.isPowerOf2()) {
7252 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7253 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7254 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7255 unsigned Log2C2 = C2Pow2.countr_zero();
7256 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7257 auto NewPred =
7259 return new ICmpInst(NewPred, X, CmpC);
7260 }
7261 }
7262 }
7263
7264 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7265 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7266 (Op0Known & Op1Known) == Op0Known)
7267 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7268 ConstantInt::getNullValue(Op1->getType()));
7269 break;
7270 }
7271 case ICmpInst::ICMP_SGE:
7272 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7273 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7274 break;
7275 case ICmpInst::ICMP_SLE:
7276 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7277 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7278 break;
7279 case ICmpInst::ICMP_UGE:
7280 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7281 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7282 break;
7283 case ICmpInst::ICMP_ULE:
7284 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7285 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7286 break;
7287 }
7288
7289 // Turn a signed comparison into an unsigned one if both operands are known to
7290 // have the same sign. Set samesign if possible (except for equality
7291 // predicates).
7292 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7293 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7294 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7295 I.setPredicate(I.getUnsignedPredicate());
7296 I.setSameSign();
7297 return &I;
7298 }
7299
7300 return nullptr;
7301}
7302
7303/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7304/// then try to reduce patterns based on that limit.
7306 Value *X, *Y;
7307 CmpPredicate Pred;
7308
7309 // X must be 0 and bool must be true for "ULT":
7310 // X <u (zext i1 Y) --> (X == 0) & Y
7311 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7312 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7313 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7314
7315 // X must be 0 or bool must be true for "ULE":
7316 // X <=u (sext i1 Y) --> (X == 0) | Y
7317 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7318 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7319 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7320
7321 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7322 CmpPredicate Pred1, Pred2;
7323 const APInt *C;
7324 Instruction *ExtI;
7325 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7328 m_APInt(C)))))) &&
7329 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7330 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7331 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7332 auto CreateRangeCheck = [&] {
7333 Value *CmpV1 =
7334 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7335 Value *CmpV2 = Builder.CreateICmp(
7336 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7338 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7339 CmpV1, CmpV2);
7340 };
7341 if (C->isZero()) {
7342 if (Pred2 == ICmpInst::ICMP_EQ) {
7343 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7344 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7345 return replaceInstUsesWith(
7346 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7347 } else if (!IsSExt || HasOneUse) {
7348 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7349 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7350 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7351 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7352 return CreateRangeCheck();
7353 }
7354 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7355 if (Pred2 == ICmpInst::ICMP_NE) {
7356 // icmp eq X, (zext (icmp ne X, 1)) --> false
7357 // icmp ne X, (zext (icmp ne X, 1)) --> true
7358 // icmp eq X, (sext (icmp ne X, -1)) --> false
7359 // icmp ne X, (sext (icmp ne X, -1)) --> true
7360 return replaceInstUsesWith(
7361 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7362 } else if (!IsSExt || HasOneUse) {
7363 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7364 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7365 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7366 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7367 return CreateRangeCheck();
7368 }
7369 } else {
7370 // when C != 0 && C != 1:
7371 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7372 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7373 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7374 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7375 // when C != 0 && C != -1:
7376 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7377 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7378 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7379 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7380 return ICmpInst::Create(
7381 Instruction::ICmp, Pred1, X,
7382 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7383 ? (IsSExt ? -1 : 1)
7384 : 0));
7385 }
7386 }
7387
7388 return nullptr;
7389}
7390
7391/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7392/// it into the appropriate icmp lt or icmp gt instruction. This transform
7393/// allows them to be folded in visitICmpInst.
7395 CmpPredicate Pred = I.getCmpPredicate();
7396 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7398 return nullptr;
7399
7400 Value *Op0 = I.getOperand(0);
7401 Value *Op1 = I.getOperand(1);
7402 auto *Op1C = dyn_cast<Constant>(Op1);
7403 if (!Op1C)
7404 return nullptr;
7405
7406 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7407 if (!FlippedStrictness)
7408 return nullptr;
7409
7410 auto *NewCmp =
7411 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7412 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7413 return NewCmp;
7414}
7415
7416/// If we have a comparison with a non-canonical predicate, if we can update
7417/// all the users, invert the predicate and adjust all the users.
7419 // Is the predicate already canonical?
7420 CmpInst::Predicate Pred = I.getPredicate();
7422 return nullptr;
7423
7424 // Can all users be adjusted to predicate inversion?
7425 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7426 return nullptr;
7427
7428 // Ok, we can canonicalize comparison!
7429 // Let's first invert the comparison's predicate.
7430 I.setPredicate(CmpInst::getInversePredicate(Pred));
7431 I.setName(I.getName() + ".not");
7432
7433 // And, adapt users.
7435
7436 return &I;
7437}
7438
7439/// Integer compare with boolean values can always be turned into bitwise ops.
7441 InstCombiner::BuilderTy &Builder) {
7442 Value *A = I.getOperand(0), *B = I.getOperand(1);
7443 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7444
7445 // A boolean compared to true/false can be simplified to Op0/true/false in
7446 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7447 // Cases not handled by InstSimplify are always 'not' of Op0.
7448 if (match(B, m_Zero())) {
7449 switch (I.getPredicate()) {
7450 case CmpInst::ICMP_EQ: // A == 0 -> !A
7451 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7452 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7454 default:
7455 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7456 }
7457 } else if (match(B, m_One())) {
7458 switch (I.getPredicate()) {
7459 case CmpInst::ICMP_NE: // A != 1 -> !A
7460 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7461 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7463 default:
7464 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7465 }
7466 }
7467
7468 switch (I.getPredicate()) {
7469 default:
7470 llvm_unreachable("Invalid icmp instruction!");
7471 case ICmpInst::ICMP_EQ:
7472 // icmp eq i1 A, B -> ~(A ^ B)
7473 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7474
7475 case ICmpInst::ICMP_NE:
7476 // icmp ne i1 A, B -> A ^ B
7477 return BinaryOperator::CreateXor(A, B);
7478
7479 case ICmpInst::ICMP_UGT:
7480 // icmp ugt -> icmp ult
7481 std::swap(A, B);
7482 [[fallthrough]];
7483 case ICmpInst::ICMP_ULT:
7484 // icmp ult i1 A, B -> ~A & B
7485 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7486
7487 case ICmpInst::ICMP_SGT:
7488 // icmp sgt -> icmp slt
7489 std::swap(A, B);
7490 [[fallthrough]];
7491 case ICmpInst::ICMP_SLT:
7492 // icmp slt i1 A, B -> A & ~B
7493 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7494
7495 case ICmpInst::ICMP_UGE:
7496 // icmp uge -> icmp ule
7497 std::swap(A, B);
7498 [[fallthrough]];
7499 case ICmpInst::ICMP_ULE:
7500 // icmp ule i1 A, B -> ~A | B
7501 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7502
7503 case ICmpInst::ICMP_SGE:
7504 // icmp sge -> icmp sle
7505 std::swap(A, B);
7506 [[fallthrough]];
7507 case ICmpInst::ICMP_SLE:
7508 // icmp sle i1 A, B -> A | ~B
7509 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7510 }
7511}
7512
7513// Transform pattern like:
7514// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7515// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7516// Into:
7517// (X l>> Y) != 0
7518// (X l>> Y) == 0
7520 InstCombiner::BuilderTy &Builder) {
7521 CmpPredicate Pred, NewPred;
7522 Value *X, *Y;
7523 if (match(&Cmp,
7524 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7525 switch (Pred) {
7526 case ICmpInst::ICMP_ULE:
7527 NewPred = ICmpInst::ICMP_NE;
7528 break;
7529 case ICmpInst::ICMP_UGT:
7530 NewPred = ICmpInst::ICMP_EQ;
7531 break;
7532 default:
7533 return nullptr;
7534 }
7535 } else if (match(&Cmp, m_c_ICmp(Pred,
7538 m_Add(m_Shl(m_One(), m_Value(Y)),
7539 m_AllOnes()))),
7540 m_Value(X)))) {
7541 // The variant with 'add' is not canonical, (the variant with 'not' is)
7542 // we only get it because it has extra uses, and can't be canonicalized,
7543
7544 switch (Pred) {
7545 case ICmpInst::ICMP_ULT:
7546 NewPred = ICmpInst::ICMP_NE;
7547 break;
7548 case ICmpInst::ICMP_UGE:
7549 NewPred = ICmpInst::ICMP_EQ;
7550 break;
7551 default:
7552 return nullptr;
7553 }
7554 } else
7555 return nullptr;
7556
7557 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7558 Constant *Zero = Constant::getNullValue(NewX->getType());
7559 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7560}
7561
7563 InstCombiner::BuilderTy &Builder) {
7564 const CmpInst::Predicate Pred = Cmp.getPredicate();
7565 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7566 Value *V1, *V2;
7567
7568 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7569 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7570 if (auto *I = dyn_cast<Instruction>(V))
7571 I->copyIRFlags(&Cmp);
7572 Module *M = Cmp.getModule();
7574 M, Intrinsic::vector_reverse, V->getType());
7575 return CallInst::Create(F, V);
7576 };
7577
7578 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7579 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7580 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7581 (LHS->hasOneUse() || RHS->hasOneUse()))
7582 return createCmpReverse(Pred, V1, V2);
7583
7584 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7585 if (LHS->hasOneUse() && isSplatValue(RHS))
7586 return createCmpReverse(Pred, V1, RHS);
7587 }
7588 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7589 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7590 return createCmpReverse(Pred, LHS, V2);
7591
7592 ArrayRef<int> M;
7593 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7594 return nullptr;
7595
7596 // If both arguments of the cmp are shuffles that use the same mask and
7597 // shuffle within a single vector, move the shuffle after the cmp:
7598 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7599 Type *V1Ty = V1->getType();
7600 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7601 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7602 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7603 return new ShuffleVectorInst(NewCmp, M);
7604 }
7605
7606 // Try to canonicalize compare with splatted operand and splat constant.
7607 // TODO: We could generalize this for more than splats. See/use the code in
7608 // InstCombiner::foldVectorBinop().
7609 Constant *C;
7610 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7611 return nullptr;
7612
7613 // Length-changing splats are ok, so adjust the constants as needed:
7614 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7615 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7616 int MaskSplatIndex;
7617 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7618 // We allow poison in matching, but this transform removes it for safety.
7619 // Demanded elements analysis should be able to recover some/all of that.
7620 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7621 ScalarC);
7622 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7623 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7624 return new ShuffleVectorInst(NewCmp, NewM);
7625 }
7626
7627 return nullptr;
7628}
7629
7630// extract(uadd.with.overflow(A, B), 0) ult A
7631// -> extract(uadd.with.overflow(A, B), 1)
7633 CmpInst::Predicate Pred = I.getPredicate();
7634 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7635
7636 Value *UAddOv;
7637 Value *A, *B;
7638 auto UAddOvResultPat = m_ExtractValue<0>(
7640 if (match(Op0, UAddOvResultPat) &&
7641 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7642 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7643 (match(A, m_One()) || match(B, m_One()))) ||
7644 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7645 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7646 // extract(uadd.with.overflow(A, B), 0) < A
7647 // extract(uadd.with.overflow(A, 1), 0) == 0
7648 // extract(uadd.with.overflow(A, -1), 0) != -1
7649 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7650 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7651 (Op0 == A || Op0 == B))
7652 // A > extract(uadd.with.overflow(A, B), 0)
7653 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7654 else
7655 return nullptr;
7656
7657 return ExtractValueInst::Create(UAddOv, 1);
7658}
7659
7661 if (!I.getOperand(0)->getType()->isPointerTy() ||
7663 I.getParent()->getParent(),
7664 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7665 return nullptr;
7666 }
7667 Instruction *Op;
7668 if (match(I.getOperand(0), m_Instruction(Op)) &&
7669 match(I.getOperand(1), m_Zero()) &&
7670 Op->isLaunderOrStripInvariantGroup()) {
7671 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
7672 Op->getOperand(0), I.getOperand(1));
7673 }
7674 return nullptr;
7675}
7676
7678 IRBuilderBase &Builder) {
7679 if (!ICmpInst::isEquality(I.getPredicate()))
7680 return nullptr;
7681
7682 // The caller puts constants after non-constants.
7683 Value *Op = I.getOperand(0);
7684 Value *Const = I.getOperand(1);
7685
7686 // For Cond an equality condition, fold
7687 //
7688 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7689 // icmp (eq|ne) Op, (Zero|AllOnes)
7690 //
7691 // with a bitcast.
7692 Value *Vec;
7693 if ((match(Const, m_ZeroInt()) &&
7695 m_Value(Vec))))) ||
7696 (match(Const, m_AllOnes()) &&
7698 m_Value(Vec)))))) {
7699 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7700 if (!VecTy)
7701 return nullptr;
7702 Type *VecEltTy = VecTy->getElementType();
7703 unsigned ScalarBW =
7704 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7705 if (!DL.fitsInLegalInteger(ScalarBW))
7706 return nullptr;
7707 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7708 Value *NewConst = match(Const, m_ZeroInt())
7709 ? ConstantInt::get(ScalarTy, 0)
7710 : ConstantInt::getAllOnesValue(ScalarTy);
7711 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7712 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7713 }
7714 return nullptr;
7715}
7716
7717/// This function folds patterns produced by lowering of reduce idioms, such as
7718/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7719/// attempts to generate fewer number of scalar comparisons instead of vector
7720/// comparisons when possible.
7722 InstCombiner::BuilderTy &Builder,
7723 const DataLayout &DL) {
7724 if (I.getType()->isVectorTy())
7725 return nullptr;
7726 CmpPredicate OuterPred, InnerPred;
7727 Value *LHS, *RHS;
7728
7729 // Match lowering of @llvm.vector.reduce.and. Turn
7730 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7731 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7732 /// %res = icmp <pred> i8 %scalar_ne, 0
7733 ///
7734 /// into
7735 ///
7736 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7737 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7738 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7739 ///
7740 /// for <pred> in {ne, eq}.
7741 if (!match(&I, m_ICmp(OuterPred,
7743 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7744 m_Zero())))
7745 return nullptr;
7746 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7747 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7748 return nullptr;
7749 unsigned NumBits =
7750 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7751 // TODO: Relax this to "not wider than max legal integer type"?
7752 if (!DL.isLegalInteger(NumBits))
7753 return nullptr;
7754
7755 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7756 auto *ScalarTy = Builder.getIntNTy(NumBits);
7757 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7758 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7759 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7760 I.getName());
7761 }
7762
7763 return nullptr;
7764}
7765
7766// This helper will be called with icmp operands in both orders.
7768 Value *Op0, Value *Op1,
7769 ICmpInst &CxtI) {
7770 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7771 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7772 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
7773 return NI;
7774
7775 if (auto *SI = dyn_cast<SelectInst>(Op0))
7776 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
7777 return NI;
7778
7779 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7780 if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
7781 return Res;
7782
7783 if (Instruction *Res = foldICmpWithClamp(CxtI, Op1, MinMax))
7784 return Res;
7785 }
7786
7787 {
7788 Value *X;
7789 const APInt *C;
7790 // icmp X+Cst, X
7791 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7792 return foldICmpAddOpConst(X, *C, Pred);
7793 }
7794
7795 // abs(X) >= X --> true
7796 // abs(X) u<= X --> true
7797 // abs(X) < X --> false
7798 // abs(X) u> X --> false
7799 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7800 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7801 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7802 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7803 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7804 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7805 {
7806 Value *X;
7807 Constant *C;
7809 match(Op1, m_Specific(X))) {
7810 Value *NullValue = Constant::getNullValue(X->getType());
7811 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7812 const APInt SMin =
7813 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7814 bool IsIntMinPosion = C->isAllOnesValue();
7815 switch (Pred) {
7816 case CmpInst::ICMP_ULE:
7817 case CmpInst::ICMP_SGE:
7818 return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
7819 case CmpInst::ICMP_UGT:
7820 case CmpInst::ICMP_SLT:
7822 case CmpInst::ICMP_UGE:
7823 case CmpInst::ICMP_SLE:
7824 case CmpInst::ICMP_EQ: {
7825 return replaceInstUsesWith(
7826 CxtI, IsIntMinPosion
7827 ? Builder.CreateICmpSGT(X, AllOnesValue)
7828 : Builder.CreateICmpULT(
7829 X, ConstantInt::get(X->getType(), SMin + 1)));
7830 }
7831 case CmpInst::ICMP_ULT:
7832 case CmpInst::ICMP_SGT:
7833 case CmpInst::ICMP_NE: {
7834 return replaceInstUsesWith(
7835 CxtI, IsIntMinPosion
7836 ? Builder.CreateICmpSLT(X, NullValue)
7837 : Builder.CreateICmpUGT(
7838 X, ConstantInt::get(X->getType(), SMin)));
7839 }
7840 default:
7841 llvm_unreachable("Invalid predicate!");
7842 }
7843 }
7844 }
7845
7846 const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);
7847 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7848 return replaceInstUsesWith(CxtI, V);
7849
7850 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7851 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7852 {
7853 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7854 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7856 }
7857
7858 if (!ICmpInst::isUnsigned(Pred) &&
7859 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7860 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7862 }
7863 }
7864
7865 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7866 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7867 {
7868 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7869 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7871 }
7872
7873 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7874 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7875 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7877 }
7878 }
7879
7880 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7881 // -> icmp X, (add nsw/nuw Y, K >> L)
7882 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7883 Value *X;
7884 uint64_t ShAmt;
7885 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7886 !CxtI.isSigned()) {
7887 if (ShAmt >= X->getType()->getScalarSizeInBits())
7888 return nullptr;
7889 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7890 ShiftSemantics::Unsigned, &CxtI)) {
7891 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7893 return new ICmpInst(Pred, X, NewOp1);
7894 }
7895 }
7896
7897 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7898 !CxtI.isUnsigned()) {
7899 if (ShAmt >= X->getType()->getScalarSizeInBits())
7900 return nullptr;
7901 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7902 ShiftSemantics::Signed, &CxtI)) {
7903 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7905 return new ICmpInst(Pred, X, NewOp1);
7906 }
7907 }
7908 return nullptr;
7909}
7910
7912 bool Changed = false;
7913 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7915 unsigned Op0Cplxity = getComplexity(Op0);
7916 unsigned Op1Cplxity = getComplexity(Op1);
7917
7918 /// Orders the operands of the compare so that they are listed from most
7919 /// complex to least complex. This puts constants before unary operators,
7920 /// before binary operators.
7921 if (Op0Cplxity < Op1Cplxity) {
7922 I.swapOperands();
7923 std::swap(Op0, Op1);
7924 Changed = true;
7925 }
7926
7927 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7928 return replaceInstUsesWith(I, V);
7929
7930 // Comparing -val or val with non-zero is the same as just comparing val
7931 // ie, abs(val) != 0 -> val != 0
7932 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
7933 Value *Cond, *SelectTrue, *SelectFalse;
7934 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
7935 m_Value(SelectFalse)))) {
7936 if (Value *V = dyn_castNegVal(SelectTrue)) {
7937 if (V == SelectFalse)
7938 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7939 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
7940 if (V == SelectTrue)
7941 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7942 }
7943 }
7944 }
7945
7947 return Res;
7948
7949 if (Op0->getType()->isIntOrIntVectorTy(1))
7951 return Res;
7952
7954 return Res;
7955
7957 return Res;
7958
7960 return Res;
7961
7963 return Res;
7964
7966 return Res;
7967
7969 return Res;
7970
7972 return Res;
7973
7974 // Test if the ICmpInst instruction is used exclusively by a select as
7975 // part of a minimum or maximum operation. If so, refrain from doing
7976 // any other folding. This helps out other analyses which understand
7977 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7978 // and CodeGen. And in this case, at least one of the comparison
7979 // operands has at least one user besides the compare (the select),
7980 // which would often largely negate the benefit of folding anyway.
7981 //
7982 // Do the same for the other patterns recognized by matchSelectPattern.
7983 if (I.hasOneUse())
7984 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
7985 Value *A, *B;
7987 if (SPR.Flavor != SPF_UNKNOWN)
7988 return nullptr;
7989 }
7990
7991 // Do this after checking for min/max to prevent infinite looping.
7992 if (Instruction *Res = foldICmpWithZero(I))
7993 return Res;
7994
7995 Value *X;
7996 const APInt *C;
7997 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
7998 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
7999 match(Op1, m_Not(m_Specific(X)))) {
8000 if (C->isNonNegative())
8001 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8002 Constant::getNullValue(X->getType()));
8003 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8004 ConstantInt::get(X->getType(), ~*C));
8005 }
8006
8007 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8008 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8009 match(Op1, m_Not(m_Specific(X)))) {
8010 if (C->isNonNegative())
8011 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8012 Constant::getAllOnesValue(X->getType()));
8013 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8014 ConstantInt::get(X->getType(), ~*C));
8015 }
8016
8017 // FIXME: We only do this after checking for min/max to prevent infinite
8018 // looping caused by a reverse canonicalization of these patterns for min/max.
8019 // FIXME: The organization of folds is a mess. These would naturally go into
8020 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8021 // down here after the min/max restriction.
8022 ICmpInst::Predicate Pred = I.getPredicate();
8023 if (match(Op1, m_APInt(C))) {
8024 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8025 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8026 Constant *Zero = Constant::getNullValue(Op0->getType());
8027 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8028 }
8029
8030 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8031 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8033 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8034 }
8035 }
8036
8037 // The folds in here may rely on wrapping flags and special constants, so
8038 // they can break up min/max idioms in some cases but not seemingly similar
8039 // patterns.
8040 // FIXME: It may be possible to enhance select folding to make this
8041 // unnecessary. It may also be moot if we canonicalize to min/max
8042 // intrinsics.
8043 if (Instruction *Res = foldICmpBinOp(I, Q))
8044 return Res;
8045
8047 return Res;
8048
8049 // Try to match comparison as a sign bit test. Intentionally do this after
8050 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8051 if (Instruction *New = foldSignBitTest(I))
8052 return New;
8053
8054 if (auto *PN = dyn_cast<PHINode>(Op0))
8055 if (Instruction *NV = foldOpIntoPhi(I, PN))
8056 return NV;
8057 if (auto *PN = dyn_cast<PHINode>(Op1))
8058 if (Instruction *NV = foldOpIntoPhi(I, PN))
8059 return NV;
8060
8062 return Res;
8063
8064 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8065 return Res;
8066 if (Instruction *Res =
8067 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8068 return Res;
8069
8070 if (I.isCommutative()) {
8071 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8072 replaceOperand(I, 0, Pair->first);
8073 replaceOperand(I, 1, Pair->second);
8074 return &I;
8075 }
8076 }
8077
8078 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8079 // when all select arms are constants, via truth table.
8081 return R;
8082
8083 // In case of a comparison with two select instructions having the same
8084 // condition, check whether one of the resulting branches can be simplified.
8085 // If so, just compare the other branch and select the appropriate result.
8086 // For example:
8087 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8088 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8089 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8090 // The icmp will result false for the false value of selects and the result
8091 // will depend upon the comparison of true values of selects if %cmp is
8092 // true. Thus, transform this into:
8093 // %cmp = icmp slt i32 %y, %z
8094 // %sel = select i1 %cond, i1 %cmp, i1 false
8095 // This handles similar cases to transform.
8096 {
8097 Value *Cond, *A, *B, *C, *D;
8098 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8100 (Op0->hasOneUse() || Op1->hasOneUse())) {
8101 // Check whether comparison of TrueValues can be simplified
8102 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8103 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8104 return SelectInst::Create(
8105 Cond, Res, NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8107 }
8108 // Check whether comparison of FalseValues can be simplified
8109 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8110 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8111 return SelectInst::Create(
8112 Cond, NewICMP, Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8114 }
8115 }
8116 }
8117
8118 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8119 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8120 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8121 {
8122 Value *A, *B;
8123 CmpPredicate CmpPred;
8124 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8126 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8127 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8128 bool I0NUW = I0->hasNoUnsignedWrap();
8129 bool I1NUW = I1->hasNoUnsignedWrap();
8130 bool I0NSW = I0->hasNoSignedWrap();
8131 bool I1NSW = I1->hasNoSignedWrap();
8132 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8133 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8134 (ICmpInst::isEquality(Pred) &&
8135 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8136 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8137 ConstantInt::get(Op0->getType(), 0));
8138 }
8139 }
8140 }
8141
8142 // Try to optimize equality comparisons against alloca-based pointers.
8143 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8144 assert(Op1->getType()->isPointerTy() &&
8145 "Comparing pointer with non-pointer?");
8146 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8147 if (foldAllocaCmp(Alloca))
8148 return nullptr;
8149 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8150 if (foldAllocaCmp(Alloca))
8151 return nullptr;
8152 }
8153
8154 if (Instruction *Res = foldICmpBitCast(I))
8155 return Res;
8156
8157 // TODO: Hoist this above the min/max bailout.
8159 return R;
8160
8161 {
8162 Value *X, *Y;
8163 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8164 // and (X & ~Y) != 0 --> (X & Y) == 0
8165 // if A is a power of 2.
8166 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8167 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8168 I.isEquality())
8169 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8170 Op1);
8171
8172 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8173 if (Op0->getType()->isIntOrIntVectorTy()) {
8174 bool ConsumesOp0, ConsumesOp1;
8175 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8176 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8177 (ConsumesOp0 || ConsumesOp1)) {
8178 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8179 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8180 assert(InvOp0 && InvOp1 &&
8181 "Mismatch between isFreeToInvert and getFreelyInverted");
8182 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8183 }
8184 }
8185
8186 Instruction *AddI = nullptr;
8188 m_Instruction(AddI))) &&
8189 isa<IntegerType>(X->getType())) {
8190 Value *Result;
8191 Constant *Overflow;
8192 // m_UAddWithOverflow can match patterns that do not include an explicit
8193 // "add" instruction, so check the opcode of the matched op.
8194 if (AddI->getOpcode() == Instruction::Add &&
8195 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8196 Result, Overflow)) {
8197 replaceInstUsesWith(*AddI, Result);
8198 eraseInstFromFunction(*AddI);
8199 return replaceInstUsesWith(I, Overflow);
8200 }
8201 }
8202
8203 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8204 if (match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) &&
8205 match(Op1, m_APInt(C))) {
8206 if (Instruction *R = processUMulZExtIdiom(I, Op0, C, *this))
8207 return R;
8208 }
8209
8210 // Signbit test folds
8211 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8212 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8213 Instruction *ExtI;
8214 if ((I.isUnsigned() || I.isEquality()) &&
8215 match(Op1,
8217 Y->getType()->getScalarSizeInBits() == 1 &&
8218 (Op0->hasOneUse() || Op1->hasOneUse())) {
8219 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8220 Instruction *ShiftI;
8221 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8223 OpWidth - 1))))) {
8224 unsigned ExtOpc = ExtI->getOpcode();
8225 unsigned ShiftOpc = ShiftI->getOpcode();
8226 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8227 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8228 Value *SLTZero =
8229 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8230 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8231 return replaceInstUsesWith(I, Cmp);
8232 }
8233 }
8234 }
8235 }
8236
8237 if (Instruction *Res = foldICmpEquality(I))
8238 return Res;
8239
8241 return Res;
8242
8243 if (Instruction *Res = foldICmpOfUAddOv(I))
8244 return Res;
8245
8247 return Res;
8248
8249 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8250 // an i1 which indicates whether or not we successfully did the swap.
8251 //
8252 // Replace comparisons between the old value and the expected value with the
8253 // indicator that 'cmpxchg' returns.
8254 //
8255 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8256 // spuriously fail. In those cases, the old value may equal the expected
8257 // value but it is possible for the swap to not occur.
8258 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8259 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8260 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8261 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8262 !ACXI->isWeak())
8263 return ExtractValueInst::Create(ACXI, 1);
8264
8266 return Res;
8267
8268 if (I.getType()->isVectorTy())
8269 if (Instruction *Res = foldVectorCmp(I, Builder))
8270 return Res;
8271
8273 return Res;
8274
8276 return Res;
8277
8278 {
8279 Value *A;
8280 const APInt *C1, *C2;
8281 ICmpInst::Predicate Pred = I.getPredicate();
8282 if (ICmpInst::isEquality(Pred)) {
8283 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8284 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8285 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8286 match(Op1, m_APInt(C2))) {
8287 Type *InputTy = A->getType();
8288 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8289 // c2 must be non-negative at the bitwidth of a.
8290 if (C2->getActiveBits() < InputBitWidth) {
8291 APInt TruncC1 = C1->trunc(InputBitWidth);
8292 // Check if there are 1s in C1 high bits of size InputBitWidth.
8293 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8294 TruncC1.setBit(InputBitWidth - 1);
8295 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8296 return new ICmpInst(
8297 Pred, AndInst,
8298 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8299 }
8300 }
8301 }
8302 }
8303
8304 return Changed ? &I : nullptr;
8305}
8306
8307/// Fold fcmp ([us]itofp x, cst) if possible.
8309 Instruction *LHSI,
8310 Constant *RHSC) {
8311 const APFloat *RHS;
8312 if (!match(RHSC, m_APFloat(RHS)))
8313 return nullptr;
8314
8315 // Get the width of the mantissa. We don't want to hack on conversions that
8316 // might lose information from the integer, e.g. "i64 -> float"
8317 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8318 if (MantissaWidth == -1)
8319 return nullptr; // Unknown.
8320
8321 Type *IntTy = LHSI->getOperand(0)->getType();
8322 unsigned IntWidth = IntTy->getScalarSizeInBits();
8323 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8324
8325 if (I.isEquality()) {
8326 FCmpInst::Predicate P = I.getPredicate();
8327 bool IsExact = false;
8328 APSInt RHSCvt(IntWidth, LHSUnsigned);
8329 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8330
8331 // If the floating point constant isn't an integer value, we know if we will
8332 // ever compare equal / not equal to it.
8333 if (!IsExact) {
8334 // TODO: Can never be -0.0 and other non-representable values
8335 APFloat RHSRoundInt(*RHS);
8337 if (*RHS != RHSRoundInt) {
8339 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8340
8342 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8343 }
8344 }
8345
8346 // TODO: If the constant is exactly representable, is it always OK to do
8347 // equality compares as integer?
8348 }
8349
8350 // Check to see that the input is converted from an integer type that is small
8351 // enough that preserves all bits. TODO: check here for "known" sign bits.
8352 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8353
8354 // Following test does NOT adjust IntWidth downwards for signed inputs,
8355 // because the most negative value still requires all the mantissa bits
8356 // to distinguish it from one less than that value.
8357 if ((int)IntWidth > MantissaWidth) {
8358 // Conversion would lose accuracy. Check if loss can impact comparison.
8359 int Exp = ilogb(*RHS);
8360 if (Exp == APFloat::IEK_Inf) {
8361 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8362 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8363 // Conversion could create infinity.
8364 return nullptr;
8365 } else {
8366 // Note that if RHS is zero or NaN, then Exp is negative
8367 // and first condition is trivially false.
8368 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8369 // Conversion could affect comparison.
8370 return nullptr;
8371 }
8372 }
8373
8374 // Otherwise, we can potentially simplify the comparison. We know that it
8375 // will always come through as an integer value and we know the constant is
8376 // not a NAN (it would have been previously simplified).
8377 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8378
8380 switch (I.getPredicate()) {
8381 default:
8382 llvm_unreachable("Unexpected predicate!");
8383 case FCmpInst::FCMP_UEQ:
8384 case FCmpInst::FCMP_OEQ:
8385 Pred = ICmpInst::ICMP_EQ;
8386 break;
8387 case FCmpInst::FCMP_UGT:
8388 case FCmpInst::FCMP_OGT:
8389 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8390 break;
8391 case FCmpInst::FCMP_UGE:
8392 case FCmpInst::FCMP_OGE:
8393 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8394 break;
8395 case FCmpInst::FCMP_ULT:
8396 case FCmpInst::FCMP_OLT:
8397 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8398 break;
8399 case FCmpInst::FCMP_ULE:
8400 case FCmpInst::FCMP_OLE:
8401 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8402 break;
8403 case FCmpInst::FCMP_UNE:
8404 case FCmpInst::FCMP_ONE:
8405 Pred = ICmpInst::ICMP_NE;
8406 break;
8407 case FCmpInst::FCMP_ORD:
8408 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8409 case FCmpInst::FCMP_UNO:
8410 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8411 }
8412
8413 // Now we know that the APFloat is a normal number, zero or inf.
8414
8415 // See if the FP constant is too large for the integer. For example,
8416 // comparing an i8 to 300.0.
8417 if (!LHSUnsigned) {
8418 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8419 // and large values.
8420 APFloat SMax(RHS->getSemantics());
8421 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8423 if (SMax < *RHS) { // smax < 13123.0
8424 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8425 Pred == ICmpInst::ICMP_SLE)
8426 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8427 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8428 }
8429 } else {
8430 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8431 // +INF and large values.
8432 APFloat UMax(RHS->getSemantics());
8433 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8435 if (UMax < *RHS) { // umax < 13123.0
8436 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8437 Pred == ICmpInst::ICMP_ULE)
8438 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8439 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8440 }
8441 }
8442
8443 if (!LHSUnsigned) {
8444 // See if the RHS value is < SignedMin.
8445 APFloat SMin(RHS->getSemantics());
8446 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8448 if (SMin > *RHS) { // smin > 12312.0
8449 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8450 Pred == ICmpInst::ICMP_SGE)
8451 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8452 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8453 }
8454 } else {
8455 // See if the RHS value is < UnsignedMin.
8456 APFloat UMin(RHS->getSemantics());
8457 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8459 if (UMin > *RHS) { // umin > 12312.0
8460 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8461 Pred == ICmpInst::ICMP_UGE)
8462 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8463 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8464 }
8465 }
8466
8467 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8468 // [0, UMAX], but it may still be fractional. Check whether this is the case
8469 // using the IsExact flag.
8470 // Don't do this for zero, because -0.0 is not fractional.
8471 APSInt RHSInt(IntWidth, LHSUnsigned);
8472 bool IsExact;
8473 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8474 if (!RHS->isZero()) {
8475 if (!IsExact) {
8476 // If we had a comparison against a fractional value, we have to adjust
8477 // the compare predicate and sometimes the value. RHSC is rounded towards
8478 // zero at this point.
8479 switch (Pred) {
8480 default:
8481 llvm_unreachable("Unexpected integer comparison!");
8482 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8483 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8484 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8485 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8486 case ICmpInst::ICMP_ULE:
8487 // (float)int <= 4.4 --> int <= 4
8488 // (float)int <= -4.4 --> false
8489 if (RHS->isNegative())
8490 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8491 break;
8492 case ICmpInst::ICMP_SLE:
8493 // (float)int <= 4.4 --> int <= 4
8494 // (float)int <= -4.4 --> int < -4
8495 if (RHS->isNegative())
8496 Pred = ICmpInst::ICMP_SLT;
8497 break;
8498 case ICmpInst::ICMP_ULT:
8499 // (float)int < -4.4 --> false
8500 // (float)int < 4.4 --> int <= 4
8501 if (RHS->isNegative())
8502 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8503 Pred = ICmpInst::ICMP_ULE;
8504 break;
8505 case ICmpInst::ICMP_SLT:
8506 // (float)int < -4.4 --> int < -4
8507 // (float)int < 4.4 --> int <= 4
8508 if (!RHS->isNegative())
8509 Pred = ICmpInst::ICMP_SLE;
8510 break;
8511 case ICmpInst::ICMP_UGT:
8512 // (float)int > 4.4 --> int > 4
8513 // (float)int > -4.4 --> true
8514 if (RHS->isNegative())