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 // The invariant here is that we are handling m_AddLike instructions,
5399 // which can only be a or disjoint, which is equivalent to an add nuw nsw.
5400 HasNUW = true;
5401 HasNSW = true;
5402 return true;
5403 } else {
5404 return false;
5405 }
5406 };
5407 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5408
5409 if (BO0) {
5410 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5411 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5412 }
5413 if (BO1) {
5414 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5415 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5416 }
5417
5418 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5419 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5420 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5421 return new ICmpInst(Pred, A == Op1 ? B : A,
5422 Constant::getNullValue(Op1->getType()));
5423
5424 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5425 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5426 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5427 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5428 C == Op0 ? D : C);
5429
5430 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5431 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5432 NoOp1WrapProblem) {
5433 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5434 Value *Y, *Z;
5435 if (A == C) {
5436 // C + B == C + D -> B == D
5437 Y = B;
5438 Z = D;
5439 } else if (A == D) {
5440 // D + B == C + D -> B == C
5441 Y = B;
5442 Z = C;
5443 } else if (B == C) {
5444 // A + C == C + D -> A == D
5445 Y = A;
5446 Z = D;
5447 } else {
5448 assert(B == D);
5449 // A + D == C + D -> A == C
5450 Y = A;
5451 Z = C;
5452 }
5453 return new ICmpInst(Pred, Y, Z);
5454 }
5455
5456 if (ICmpInst::isRelational(Pred)) {
5457 // Return if both X and Y is divisible by Z/-Z.
5458 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5459 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5460 bool IsNegative) -> bool {
5461 const APInt *OffsetC;
5462 if (!match(Z, m_APInt(OffsetC)))
5463 return false;
5464
5465 // Fast path for Z == 1/-1.
5466 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5467 return true;
5468
5469 APInt C = *OffsetC;
5470 if (IsNegative)
5471 C.negate();
5472 // Note: -INT_MIN is also negative.
5473 if (!C.isStrictlyPositive())
5474 return false;
5475
5476 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5477 };
5478
5479 // The subtraction-related identities (A -nuw B) shown below require that
5480 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5481 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5482 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5483 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5484 // requires proving A <u B, for which the nowrap precondition can never be
5485 // satisfied. These are therefore skipped.
5486 //
5487 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5488 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5489 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5490 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5491
5492 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5493 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5494 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5495 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5496 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5497 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5498 bool IsNegative = ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred);
5499 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5500 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5501 ShareCommonDivisor(A, Op1, B, IsNegative))
5503 Op1);
5504
5505 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5506 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5507 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5508 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5509 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5510 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5511 if (C && NoOp1WrapProblem &&
5512 ShareCommonDivisor(Op0, C, D,
5513 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5515 C);
5516 }
5517
5518 // if C1 has greater magnitude than C2:
5519 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5520 // s.t. C3 = C1 - C2
5521 //
5522 // if C2 has greater magnitude than C1:
5523 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5524 // s.t. C3 = C2 - C1
5525 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5526 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5527 const APInt *AP1, *AP2;
5528 // TODO: Support non-uniform vectors.
5529 // TODO: Allow poison passthrough if B or D's element is poison.
5530 if (match(B, m_APIntAllowPoison(AP1)) &&
5531 match(D, m_APIntAllowPoison(AP2)) &&
5532 AP1->isNegative() == AP2->isNegative()) {
5533 APInt AP1Abs = AP1->abs();
5534 APInt AP2Abs = AP2->abs();
5535 if (AP1Abs.uge(AP2Abs)) {
5536 APInt Diff = *AP1 - *AP2;
5537 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5538 Value *NewAdd = Builder.CreateAdd(
5539 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5540 return new ICmpInst(Pred, NewAdd, C);
5541 } else {
5542 APInt Diff = *AP2 - *AP1;
5543 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5544 Value *NewAdd = Builder.CreateAdd(
5545 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5546 return new ICmpInst(Pred, A, NewAdd);
5547 }
5548 }
5549 Constant *Cst1, *Cst2;
5550 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5551 ICmpInst::isEquality(Pred)) {
5552 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5553 Value *NewAdd = Builder.CreateAdd(C, Diff);
5554 return new ICmpInst(Pred, A, NewAdd);
5555 }
5556 }
5557
5558 // Analyze the case when either Op0 or Op1 is a sub instruction.
5559 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5560 A = nullptr;
5561 B = nullptr;
5562 C = nullptr;
5563 D = nullptr;
5564 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5565 A = BO0->getOperand(0);
5566 B = BO0->getOperand(1);
5567 }
5568 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5569 C = BO1->getOperand(0);
5570 D = BO1->getOperand(1);
5571 }
5572
5573 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5574 if (A == Op1 && NoOp0WrapProblem)
5575 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5576 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5577 if (C == Op0 && NoOp1WrapProblem)
5578 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5579
5580 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5581 // (A - B) u>/u<= A --> B u>/u<= A
5582 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5583 return new ICmpInst(Pred, B, A);
5584 // C u</u>= (C - D) --> C u</u>= D
5585 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5586 return new ICmpInst(Pred, C, D);
5587 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5588 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5589 isKnownNonZero(B, Q))
5591 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5592 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5593 isKnownNonZero(D, Q))
5595
5596 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5597 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5598 return new ICmpInst(Pred, A, C);
5599
5600 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5601 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5602 return new ICmpInst(Pred, D, B);
5603
5604 // icmp (0-X) < cst --> x > -cst
5605 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5606 Value *X;
5607 if (match(BO0, m_Neg(m_Value(X))))
5608 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5609 if (RHSC->isNotMinSignedValue())
5610 return new ICmpInst(I.getSwappedPredicate(), X,
5611 ConstantExpr::getNeg(RHSC));
5612 }
5613
5614 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5615 return R;
5616 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5617 return R;
5618
5619 {
5620 // Try to remove shared multiplier from comparison:
5621 // X * Z pred Y * Z
5622 Value *X, *Y, *Z;
5623 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5624 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5625 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5626 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5627 if (ICmpInst::isSigned(Pred)) {
5628 if (Op0HasNSW && Op1HasNSW) {
5629 KnownBits ZKnown = computeKnownBits(Z, &I);
5630 if (ZKnown.isStrictlyPositive())
5631 return new ICmpInst(Pred, X, Y);
5632 if (ZKnown.isNegative())
5633 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5635 SQ.getWithInstruction(&I));
5636 if (LessThan && match(LessThan, m_One()))
5637 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5638 Constant::getNullValue(Z->getType()));
5639 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5640 SQ.getWithInstruction(&I));
5641 if (GreaterThan && match(GreaterThan, m_One()))
5642 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5643 }
5644 } else {
5645 bool NonZero;
5646 if (ICmpInst::isEquality(Pred)) {
5647 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5648 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5649 isKnownNonEqual(X, Y, SQ))
5650 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5651
5652 KnownBits ZKnown = computeKnownBits(Z, &I);
5653 // if Z % 2 != 0
5654 // X * Z eq/ne Y * Z -> X eq/ne Y
5655 if (ZKnown.countMaxTrailingZeros() == 0)
5656 return new ICmpInst(Pred, X, Y);
5657 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5658 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5659 // X * Z eq/ne Y * Z -> X eq/ne Y
5660 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5661 return new ICmpInst(Pred, X, Y);
5662 } else
5663 NonZero = isKnownNonZero(Z, Q);
5664
5665 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5666 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5667 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5668 return new ICmpInst(Pred, X, Y);
5669 }
5670 }
5671 }
5672
5673 BinaryOperator *SRem = nullptr;
5674 // icmp (srem X, Y), Y
5675 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5676 SRem = BO0;
5677 // icmp Y, (srem X, Y)
5678 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5679 Op0 == BO1->getOperand(1))
5680 SRem = BO1;
5681 if (SRem) {
5682 // We don't check hasOneUse to avoid increasing register pressure because
5683 // the value we use is the same value this instruction was already using.
5684 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5685 default:
5686 break;
5687 case ICmpInst::ICMP_EQ:
5688 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5689 case ICmpInst::ICMP_NE:
5690 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5691 case ICmpInst::ICMP_SGT:
5692 case ICmpInst::ICMP_SGE:
5693 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5695 case ICmpInst::ICMP_SLT:
5696 case ICmpInst::ICMP_SLE:
5697 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5699 }
5700 }
5701
5702 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5703 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5704 BO0->getOperand(1) == BO1->getOperand(1)) {
5705 switch (BO0->getOpcode()) {
5706 default:
5707 break;
5708 case Instruction::Add:
5709 case Instruction::Sub:
5710 case Instruction::Xor: {
5711 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5712 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5713
5714 const APInt *C;
5715 if (match(BO0->getOperand(1), m_APInt(C))) {
5716 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5717 if (C->isSignMask()) {
5718 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5719 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5720 }
5721
5722 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5723 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5724 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5725 NewPred = I.getSwappedPredicate(NewPred);
5726 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5727 }
5728 }
5729 break;
5730 }
5731 case Instruction::Mul: {
5732 if (!I.isEquality())
5733 break;
5734
5735 const APInt *C;
5736 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5737 !C->isOne()) {
5738 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5739 // Mask = -1 >> count-trailing-zeros(C).
5740 if (unsigned TZs = C->countr_zero()) {
5741 Constant *Mask = ConstantInt::get(
5742 BO0->getType(),
5743 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5744 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5745 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5746 return new ICmpInst(Pred, And1, And2);
5747 }
5748 }
5749 break;
5750 }
5751 case Instruction::UDiv:
5752 case Instruction::LShr:
5753 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5754 break;
5755 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5756
5757 case Instruction::SDiv:
5758 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5759 !BO0->isExact() || !BO1->isExact())
5760 break;
5761 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5762
5763 case Instruction::AShr:
5764 if (!BO0->isExact() || !BO1->isExact())
5765 break;
5766 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5767
5768 case Instruction::Shl: {
5769 bool NUW = Op0HasNUW && Op1HasNUW;
5770 bool NSW = Op0HasNSW && Op1HasNSW;
5771 if (!NUW && !NSW)
5772 break;
5773 if (!NSW && I.isSigned())
5774 break;
5775 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5776 }
5777 }
5778 }
5779
5780 if (BO0) {
5781 // Transform A & (L - 1) `ult` L --> L != 0
5782 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5783 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5784
5785 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5786 auto *Zero = Constant::getNullValue(BO0->getType());
5787 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5788 }
5789 }
5790
5791 // For unsigned predicates / eq / ne:
5792 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5793 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5794 if (!ICmpInst::isSigned(Pred)) {
5795 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5796 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5797 Constant::getNullValue(Op1->getType()));
5798 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5799 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5800 Constant::getNullValue(Op0->getType()), Op0);
5801 }
5802
5804 return replaceInstUsesWith(I, V);
5805
5806 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5807 return R;
5808
5810 return replaceInstUsesWith(I, V);
5811
5813 return replaceInstUsesWith(I, V);
5814
5815 return nullptr;
5816}
5817
5818/// Fold icmp Pred min|max(X, Y), Z.
5821 Value *Z, CmpPredicate Pred) {
5822 Value *X = MinMax->getLHS();
5823 Value *Y = MinMax->getRHS();
5824 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5825 return nullptr;
5826 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5827 // Revert the transform signed pred -> unsigned pred
5828 // TODO: We can flip the signedness of predicate if both operands of icmp
5829 // are negative.
5830 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5831 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5833 } else
5834 return nullptr;
5835 }
5836 SimplifyQuery Q = SQ.getWithInstruction(&I);
5837 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5838 if (!Val)
5839 return std::nullopt;
5840 if (match(Val, m_One()))
5841 return true;
5842 if (match(Val, m_Zero()))
5843 return false;
5844 return std::nullopt;
5845 };
5846 // Remove samesign here since it is illegal to keep it when we speculatively
5847 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5848 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5849 // -46, -32)`. `X` is allowed to be non-negative here.
5850 Pred = Pred.dropSameSign();
5851 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5852 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5853 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5854 return nullptr;
5855 if (!CmpXZ.has_value()) {
5856 std::swap(X, Y);
5857 std::swap(CmpXZ, CmpYZ);
5858 }
5859
5860 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5861 if (CmpYZ.has_value())
5862 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5863 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5864 };
5865
5866 switch (Pred) {
5867 case ICmpInst::ICMP_EQ:
5868 case ICmpInst::ICMP_NE: {
5869 // If X == Z:
5870 // Expr Result
5871 // min(X, Y) == Z X <= Y
5872 // max(X, Y) == Z X >= Y
5873 // min(X, Y) != Z X > Y
5874 // max(X, Y) != Z X < Y
5875 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5876 ICmpInst::Predicate NewPred =
5877 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5878 if (Pred == ICmpInst::ICMP_NE)
5879 NewPred = ICmpInst::getInversePredicate(NewPred);
5880 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5881 }
5882 // Otherwise (X != Z):
5883 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5884 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5885 if (!MinMaxCmpXZ.has_value()) {
5886 std::swap(X, Y);
5887 std::swap(CmpXZ, CmpYZ);
5888 // Re-check pre-condition X != Z
5889 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5890 break;
5891 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5892 }
5893 if (!MinMaxCmpXZ.has_value())
5894 break;
5895 if (*MinMaxCmpXZ) {
5896 // Expr Fact Result
5897 // min(X, Y) == Z X < Z false
5898 // max(X, Y) == Z X > Z false
5899 // min(X, Y) != Z X < Z true
5900 // max(X, Y) != Z X > Z true
5901 return replaceInstUsesWith(
5902 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5903 } else {
5904 // Expr Fact Result
5905 // min(X, Y) == Z X > Z Y == Z
5906 // max(X, Y) == Z X < Z Y == Z
5907 // min(X, Y) != Z X > Z Y != Z
5908 // max(X, Y) != Z X < Z Y != Z
5909 return FoldIntoCmpYZ();
5910 }
5911 break;
5912 }
5913 case ICmpInst::ICMP_SLT:
5914 case ICmpInst::ICMP_ULT:
5915 case ICmpInst::ICMP_SLE:
5916 case ICmpInst::ICMP_ULE:
5917 case ICmpInst::ICMP_SGT:
5918 case ICmpInst::ICMP_UGT:
5919 case ICmpInst::ICMP_SGE:
5920 case ICmpInst::ICMP_UGE: {
5921 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5922 if (*CmpXZ) {
5923 if (IsSame) {
5924 // Expr Fact Result
5925 // min(X, Y) < Z X < Z true
5926 // min(X, Y) <= Z X <= Z true
5927 // max(X, Y) > Z X > Z true
5928 // max(X, Y) >= Z X >= Z true
5929 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5930 } else {
5931 // Expr Fact Result
5932 // max(X, Y) < Z X < Z Y < Z
5933 // max(X, Y) <= Z X <= Z Y <= Z
5934 // min(X, Y) > Z X > Z Y > Z
5935 // min(X, Y) >= Z X >= Z Y >= Z
5936 return FoldIntoCmpYZ();
5937 }
5938 } else {
5939 if (IsSame) {
5940 // Expr Fact Result
5941 // min(X, Y) < Z X >= Z Y < Z
5942 // min(X, Y) <= Z X > Z Y <= Z
5943 // max(X, Y) > Z X <= Z Y > Z
5944 // max(X, Y) >= Z X < Z Y >= Z
5945 return FoldIntoCmpYZ();
5946 } else {
5947 // Expr Fact Result
5948 // max(X, Y) < Z X >= Z false
5949 // max(X, Y) <= Z X > Z false
5950 // min(X, Y) > Z X <= Z false
5951 // min(X, Y) >= Z X < Z false
5952 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5953 }
5954 }
5955 break;
5956 }
5957 default:
5958 break;
5959 }
5960
5961 return nullptr;
5962}
5963
5964/// Match and fold patterns like:
5965/// icmp eq/ne X, min(max(X, Lo), Hi)
5966/// which represents a range check and can be represented as a ConstantRange.
5967///
5968/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
5969/// (X - Lo) u< (Hi + 1 - Lo)
5970/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
5971/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
5973 MinMaxIntrinsic *Min) {
5974 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
5975 return nullptr;
5976
5977 const APInt *Lo = nullptr, *Hi = nullptr;
5978 if (Min->isSigned()) {
5979 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
5980 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
5981 return nullptr;
5982 } else {
5983 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
5984 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
5985 return nullptr;
5986 }
5987
5990 APInt C, Offset;
5991 if (I.getPredicate() == ICmpInst::ICMP_EQ)
5992 CR.getEquivalentICmp(Pred, C, Offset);
5993 else
5994 CR.inverse().getEquivalentICmp(Pred, C, Offset);
5995
5996 if (!Offset.isZero())
5997 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
5998
5999 return replaceInstUsesWith(
6000 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
6001}
6002
6003// Canonicalize checking for a power-of-2-or-zero value:
6005 InstCombiner::BuilderTy &Builder) {
6006 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6007 const CmpInst::Predicate Pred = I.getPredicate();
6008 Value *A = nullptr;
6009 bool CheckIs;
6010 if (I.isEquality()) {
6011 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6012 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6013 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6014 m_Deferred(A)))) ||
6015 !match(Op1, m_ZeroInt()))
6016 A = nullptr;
6017
6018 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6019 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6020 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6021 A = Op1;
6022 else if (match(Op1,
6024 A = Op0;
6025
6026 CheckIs = Pred == ICmpInst::ICMP_EQ;
6027 } else if (ICmpInst::isUnsigned(Pred)) {
6028 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6029 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6030
6031 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6033 m_Specific(Op1))))) {
6034 A = Op1;
6035 CheckIs = Pred == ICmpInst::ICMP_UGE;
6036 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6038 m_Specific(Op0))))) {
6039 A = Op0;
6040 CheckIs = Pred == ICmpInst::ICMP_ULE;
6041 }
6042 }
6043
6044 if (A) {
6045 Type *Ty = A->getType();
6046 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6047 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6048 ConstantInt::get(Ty, 2))
6049 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6050 ConstantInt::get(Ty, 1));
6051 }
6052
6053 return nullptr;
6054}
6055
6056/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6057using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6059 bool AllowRecursion) {
6061 if (!Inst || !Inst->hasOneUse())
6062 return;
6063
6064 switch (Inst->getOpcode()) {
6065 case Instruction::Add:
6066 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6067 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6068 break;
6069 case Instruction::Sub:
6070 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6071 break;
6072 case Instruction::Xor:
6073 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6074 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6075 break;
6076 case Instruction::Shl:
6077 if (Inst->hasNoSignedWrap())
6078 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6079 if (Inst->hasNoUnsignedWrap())
6080 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6081 break;
6082 case Instruction::Select:
6083 if (AllowRecursion) {
6084 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6085 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6086 }
6087 break;
6088 default:
6089 break;
6090 }
6091}
6092
6094
6099
6101 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6102 }
6104 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6105 }
6106 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6108 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6109 }
6110 bool isValid() const { return Kind != OffsetKind::Invalid; }
6112 switch (Kind) {
6114 llvm_unreachable("Invalid offset result");
6115 case OffsetKind::Value:
6116 return V0;
6117 case OffsetKind::Select:
6118 return Builder.CreateSelect(
6119 V0, V1, V2, "", ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
6120 }
6121 llvm_unreachable("Unknown OffsetKind enum");
6122 }
6123};
6124
6125/// Offset both sides of an equality icmp to see if we can save some
6126/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6127/// Note: This operation should not introduce poison.
6129 InstCombiner::BuilderTy &Builder,
6130 const SimplifyQuery &SQ) {
6131 assert(I.isEquality() && "Expected an equality icmp");
6132 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6133 if (!Op0->getType()->isIntOrIntVectorTy())
6134 return nullptr;
6135
6136 SmallVector<OffsetOp, 4> OffsetOps;
6137 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6138 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6139
6140 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6141 switch (BinOpc) {
6142 // V = shl nsw X, RHS => X = ashr V, RHS
6143 case Instruction::AShr: {
6144 const APInt *CV, *CRHS;
6145 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6146 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6148 return nullptr;
6149 break;
6150 }
6151 // V = shl nuw X, RHS => X = lshr V, RHS
6152 case Instruction::LShr: {
6153 const APInt *CV, *CRHS;
6154 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6155 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6157 return nullptr;
6158 break;
6159 }
6160 default:
6161 break;
6162 }
6163
6164 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6165 if (!Simplified)
6166 return nullptr;
6167 // Reject constant expressions as they don't simplify things.
6168 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6169 return nullptr;
6170 // Check if the transformation introduces poison.
6171 return impliesPoison(RHS, V) ? Simplified : nullptr;
6172 };
6173
6174 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6175 Value *RHS) -> OffsetResult {
6176 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6177 if (!Sel->hasOneUse())
6178 return OffsetResult::invalid();
6179 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6180 if (!TrueVal)
6181 return OffsetResult::invalid();
6182 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6183 if (!FalseVal)
6184 return OffsetResult::invalid();
6185 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6186 }
6187 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6188 return OffsetResult::value(Simplified);
6189 return OffsetResult::invalid();
6190 };
6191
6192 for (auto [BinOp, RHS] : OffsetOps) {
6193 auto BinOpc = static_cast<unsigned>(BinOp);
6194
6195 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6196 if (!Op0Result.isValid())
6197 continue;
6198 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6199 if (!Op1Result.isValid())
6200 continue;
6201
6202 Value *NewLHS = Op0Result.materialize(Builder);
6203 Value *NewRHS = Op1Result.materialize(Builder);
6204 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6205 }
6206
6207 return nullptr;
6208}
6209
6211 if (!I.isEquality())
6212 return nullptr;
6213
6214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6215 const CmpInst::Predicate Pred = I.getPredicate();
6216 Value *A, *B, *C, *D;
6217 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6218 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6219 Value *OtherVal = A == Op1 ? B : A;
6220 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6221 }
6222
6223 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6224 // A^c1 == C^c2 --> A == C^(c1^c2)
6225 ConstantInt *C1, *C2;
6226 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6227 Op1->hasOneUse()) {
6228 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6229 Value *Xor = Builder.CreateXor(C, NC);
6230 return new ICmpInst(Pred, A, Xor);
6231 }
6232
6233 // A^B == A^D -> B == D
6234 if (A == C)
6235 return new ICmpInst(Pred, B, D);
6236 if (A == D)
6237 return new ICmpInst(Pred, B, C);
6238 if (B == C)
6239 return new ICmpInst(Pred, A, D);
6240 if (B == D)
6241 return new ICmpInst(Pred, A, C);
6242 }
6243 }
6244
6245 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6246 // A == (A^B) -> B == 0
6247 Value *OtherVal = A == Op0 ? B : A;
6248 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6249 }
6250
6251 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6252 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6253 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6254 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6255
6256 if (A == C) {
6257 X = B;
6258 Y = D;
6259 Z = A;
6260 } else if (A == D) {
6261 X = B;
6262 Y = C;
6263 Z = A;
6264 } else if (B == C) {
6265 X = A;
6266 Y = D;
6267 Z = B;
6268 } else if (B == D) {
6269 X = A;
6270 Y = C;
6271 Z = B;
6272 }
6273
6274 if (X) {
6275 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6276 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6277 // instructions.
6278 const APInt *C0, *C1;
6279 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6280 (*C0 ^ *C1).isNegatedPowerOf2();
6281
6282 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6283 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6284 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6285 int UseCnt =
6286 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6287 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6288 if (XorIsNegP2 || UseCnt >= 2) {
6289 // Build (X^Y) & Z
6290 Op1 = Builder.CreateXor(X, Y);
6291 Op1 = Builder.CreateAnd(Op1, Z);
6292 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6293 }
6294 }
6295 }
6296
6297 {
6298 // Similar to above, but specialized for constant because invert is needed:
6299 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6300 Value *X, *Y;
6301 Constant *C;
6302 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6303 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6304 Value *Xor = Builder.CreateXor(X, Y);
6305 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6306 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6307 }
6308 }
6309
6310 if (match(Op1, m_ZExt(m_Value(A))) &&
6311 (Op0->hasOneUse() || Op1->hasOneUse())) {
6312 // (B & (Pow2C-1)) == zext A --> A == trunc B
6313 // (B & (Pow2C-1)) != zext A --> A != trunc B
6314 const APInt *MaskC;
6315 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6316 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6317 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6318 }
6319
6320 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6321 // For lshr and ashr pairs.
6322 const APInt *AP1, *AP2;
6323 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6324 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6325 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6326 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6327 if (*AP1 != *AP2)
6328 return nullptr;
6329 unsigned TypeBits = AP1->getBitWidth();
6330 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6331 if (ShAmt < TypeBits && ShAmt != 0) {
6332 ICmpInst::Predicate NewPred =
6334 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6335 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6336 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6337 }
6338 }
6339
6340 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6341 ConstantInt *Cst1;
6342 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6343 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6344 unsigned TypeBits = Cst1->getBitWidth();
6345 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6346 if (ShAmt < TypeBits && ShAmt != 0) {
6347 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6348 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6349 Value *And =
6350 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6351 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6352 }
6353 }
6354
6355 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6356 // "icmp (and X, mask), cst"
6357 uint64_t ShAmt = 0;
6358 if (Op0->hasOneUse() &&
6359 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6360 match(Op1, m_ConstantInt(Cst1)) &&
6361 // Only do this when A has multiple uses. This is most important to do
6362 // when it exposes other optimizations.
6363 !A->hasOneUse()) {
6364 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6365
6366 if (ShAmt < ASize) {
6367 APInt MaskV =
6369 MaskV <<= ShAmt;
6370
6371 APInt CmpV = Cst1->getValue().zext(ASize);
6372 CmpV <<= ShAmt;
6373
6374 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6375 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6376 }
6377 }
6378
6380 return ICmp;
6381
6382 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6383 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6384 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6385 // few steps of instcombine.
6386 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6387 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6389 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6390 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6392 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6393 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6395 Add, ConstantInt::get(A->getType(), C.shl(1)));
6396 }
6397
6398 // Canonicalize:
6399 // Assume B_Pow2 != 0
6400 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6401 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6402 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6403 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6404 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6406
6407 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6408 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6409 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6410 ConstantInt::getNullValue(Op1->getType()));
6411
6412 // Canonicalize:
6413 // icmp eq/ne X, OneUse(rotate-right(X))
6414 // -> icmp eq/ne X, rotate-left(X)
6415 // We generally try to convert rotate-right -> rotate-left, this just
6416 // canonicalizes another case.
6417 if (match(&I, m_c_ICmp(m_Value(A),
6419 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6420 return new ICmpInst(
6421 Pred, A,
6422 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6423
6424 // Canonicalize:
6425 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6426 Constant *Cst;
6429 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6430
6431 {
6432 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6433 auto m_Matcher =
6436 m_Sub(m_Value(B), m_Deferred(A)));
6437 std::optional<bool> IsZero = std::nullopt;
6438 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6439 m_Deferred(A))))
6440 IsZero = false;
6441 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6442 else if (match(&I,
6443 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6444 IsZero = true;
6445
6446 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6447 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6448 // -> (icmp eq/ne (and X, P2), 0)
6449 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6450 // -> (icmp eq/ne (and X, P2), P2)
6451 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6452 *IsZero ? A
6453 : ConstantInt::getNullValue(A->getType()));
6454 }
6455
6456 if (auto *Res = foldICmpEqualityWithOffset(
6457 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6458 return Res;
6459
6460 return nullptr;
6461}
6462
6464 ICmpInst::Predicate Pred = ICmp.getPredicate();
6465 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6466
6467 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6468 // The trunc masks high bits while the compare may effectively mask low bits.
6469 Value *X;
6470 const APInt *C;
6471 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6472 return nullptr;
6473
6474 // This matches patterns corresponding to tests of the signbit as well as:
6475 // (trunc X) pred C2 --> (X & Mask) == C
6476 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6477 /*AllowNonZeroC=*/true)) {
6478 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6479 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6480 return new ICmpInst(Res->Pred, And, C);
6481 }
6482
6483 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6484 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6485 if (II->getIntrinsicID() == Intrinsic::cttz ||
6486 II->getIntrinsicID() == Intrinsic::ctlz) {
6487 unsigned MaxRet = SrcBits;
6488 // If the "is_zero_poison" argument is set, then we know at least
6489 // one bit is set in the input, so the result is always at least one
6490 // less than the full bitwidth of that input.
6491 if (match(II->getArgOperand(1), m_One()))
6492 MaxRet--;
6493
6494 // Make sure the destination is wide enough to hold the largest output of
6495 // the intrinsic.
6496 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6497 if (Instruction *I =
6498 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6499 return I;
6500 }
6501 }
6502
6503 return nullptr;
6504}
6505
6507 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6508 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6509 Value *X;
6510 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6511 return nullptr;
6512
6513 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6514 bool IsSignedCmp = ICmp.isSigned();
6515
6516 // icmp Pred (ext X), (ext Y)
6517 Value *Y;
6518 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6519 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6520 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6521
6522 if (IsZext0 != IsZext1) {
6523 // If X and Y and both i1
6524 // (icmp eq/ne (zext X) (sext Y))
6525 // eq -> (icmp eq (or X, Y), 0)
6526 // ne -> (icmp ne (or X, Y), 0)
6527 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6528 Y->getType()->isIntOrIntVectorTy(1))
6529 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6530 Constant::getNullValue(X->getType()));
6531
6532 // If we have mismatched casts and zext has the nneg flag, we can
6533 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6534
6535 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6536 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6537
6538 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6539 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6540
6541 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6542 IsSignedExt = true;
6543 else
6544 return nullptr;
6545 }
6546
6547 // Not an extension from the same type?
6548 Type *XTy = X->getType(), *YTy = Y->getType();
6549 if (XTy != YTy) {
6550 // One of the casts must have one use because we are creating a new cast.
6551 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6552 return nullptr;
6553 // Extend the narrower operand to the type of the wider operand.
6554 CastInst::CastOps CastOpcode =
6555 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6556 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6557 X = Builder.CreateCast(CastOpcode, X, YTy);
6558 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6559 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6560 else
6561 return nullptr;
6562 }
6563
6564 // (zext X) == (zext Y) --> X == Y
6565 // (sext X) == (sext Y) --> X == Y
6566 if (ICmp.isEquality())
6567 return new ICmpInst(ICmp.getPredicate(), X, Y);
6568
6569 // A signed comparison of sign extended values simplifies into a
6570 // signed comparison.
6571 if (IsSignedCmp && IsSignedExt)
6572 return new ICmpInst(ICmp.getPredicate(), X, Y);
6573
6574 // The other three cases all fold into an unsigned comparison.
6575 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6576 }
6577
6578 // Below here, we are only folding a compare with constant.
6579 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6580 if (!C)
6581 return nullptr;
6582
6583 // If a lossless truncate is possible...
6584 Type *SrcTy = CastOp0->getSrcTy();
6585 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6586 if (Res) {
6587 if (ICmp.isEquality())
6588 return new ICmpInst(ICmp.getPredicate(), X, Res);
6589
6590 // A signed comparison of sign extended values simplifies into a
6591 // signed comparison.
6592 if (IsSignedExt && IsSignedCmp)
6593 return new ICmpInst(ICmp.getPredicate(), X, Res);
6594
6595 // The other three cases all fold into an unsigned comparison.
6596 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6597 }
6598
6599 // The re-extended constant changed, partly changed (in the case of a vector),
6600 // or could not be determined to be equal (in the case of a constant
6601 // expression), so the constant cannot be represented in the shorter type.
6602 // All the cases that fold to true or false will have already been handled
6603 // by simplifyICmpInst, so only deal with the tricky case.
6604 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6605 return nullptr;
6606
6607 // Is source op positive?
6608 // icmp ult (sext X), C --> icmp sgt X, -1
6609 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6611
6612 // Is source op negative?
6613 // icmp ugt (sext X), C --> icmp slt X, 0
6614 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6616}
6617
6618/// Handle icmp (cast x), (cast or constant).
6620 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6621 // icmp compares only pointer's value.
6622 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6623 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6624 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6625 if (SimplifiedOp0 || SimplifiedOp1)
6626 return new ICmpInst(ICmp.getPredicate(),
6627 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6628 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6629
6630 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6631 Value *Op1 = ICmp.getOperand(1);
6632 if (!CastOp0)
6633 return nullptr;
6634 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6635 return nullptr;
6636
6637 Value *Op0Src = CastOp0->getOperand(0);
6638 Type *SrcTy = CastOp0->getSrcTy();
6639 Type *DestTy = CastOp0->getDestTy();
6640
6641 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6642 // integer type is the same size as the pointer type.
6643 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6644 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6645 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6646 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6647 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6648 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6649 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6650 };
6651 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6652 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6653 Value *NewOp1 = nullptr;
6654 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6655 NewOp1 = PtrToIntOp1->getOperand(0);
6656 HasPtrToInt = true;
6657 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6658 NewOp1 = PtrToAddrOp1->getOperand(0);
6659 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6660 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6661 }
6662
6663 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6664 // check PtrWidth.
6665 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6666 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6667 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6668 }
6669
6670 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6671 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6672 CompatibleSizes(DestTy, SrcTy)) {
6673 Value *NewOp1 = nullptr;
6674 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6675 Value *IntSrc = IntToPtrOp1->getOperand(0);
6676 if (IntSrc->getType() == Op0Src->getType())
6677 NewOp1 = IntToPtrOp1->getOperand(0);
6678 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6679 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6680 }
6681
6682 if (NewOp1)
6683 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6684 }
6685
6686 if (Instruction *R = foldICmpWithTrunc(ICmp))
6687 return R;
6688
6689 return foldICmpWithZextOrSext(ICmp);
6690}
6691
6693 bool IsSigned) {
6694 switch (BinaryOp) {
6695 default:
6696 llvm_unreachable("Unsupported binary op");
6697 case Instruction::Add:
6698 case Instruction::Sub:
6699 return match(RHS, m_Zero());
6700 case Instruction::Mul:
6701 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6702 match(RHS, m_One());
6703 }
6704}
6705
6708 bool IsSigned, Value *LHS, Value *RHS,
6709 Instruction *CxtI) const {
6710 switch (BinaryOp) {
6711 default:
6712 llvm_unreachable("Unsupported binary op");
6713 case Instruction::Add:
6714 if (IsSigned)
6715 return computeOverflowForSignedAdd(LHS, RHS, CxtI);
6716 else
6717 return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
6718 case Instruction::Sub:
6719 if (IsSigned)
6720 return computeOverflowForSignedSub(LHS, RHS, CxtI);
6721 else
6722 return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
6723 case Instruction::Mul:
6724 if (IsSigned)
6725 return computeOverflowForSignedMul(LHS, RHS, CxtI);
6726 else
6727 return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
6728 }
6729}
6730
6731bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6732 bool IsSigned, Value *LHS,
6733 Value *RHS, Instruction &OrigI,
6734 Value *&Result,
6735 Constant *&Overflow) {
6736 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6737 std::swap(LHS, RHS);
6738
6739 // If the overflow check was an add followed by a compare, the insertion point
6740 // may be pointing to the compare. We want to insert the new instructions
6741 // before the add in case there are uses of the add between the add and the
6742 // compare.
6743 Builder.SetInsertPoint(&OrigI);
6744
6745 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6746 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6747 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6748
6749 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6750 Result = LHS;
6751 Overflow = ConstantInt::getFalse(OverflowTy);
6752 return true;
6753 }
6754
6755 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6757 return false;
6760 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6761 Result->takeName(&OrigI);
6762 Overflow = ConstantInt::getTrue(OverflowTy);
6763 return true;
6765 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6766 Result->takeName(&OrigI);
6767 Overflow = ConstantInt::getFalse(OverflowTy);
6768 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6769 if (IsSigned)
6770 Inst->setHasNoSignedWrap();
6771 else
6772 Inst->setHasNoUnsignedWrap();
6773 }
6774 return true;
6775 }
6776
6777 llvm_unreachable("Unexpected overflow result");
6778}
6779
6780/// Recognize and process idiom involving test for unsigned
6781/// overflow.
6782///
6783/// The caller has matched a pattern of the form:
6784/// I = cmp u (add(zext A, zext B), V
6785/// I = cmp u (mul(zext A, zext B), V
6786/// The function checks if this is a test for overflow and if so replaces
6787/// addition/multiplication with call to the umul intrinsic or the canonical
6788/// form of uadd overflow.
6789///
6790/// \param I Compare instruction.
6791/// \param Val Result of add/mul instruction. It is one of the arguments of
6792/// the compare instruction. Must be of integer type.
6793/// \param OtherVal The other argument of compare instruction.
6794/// \returns Instruction which must replace the compare instruction, NULL if no
6795/// replacement required.
6797 const APInt *OtherVal,
6798 InstCombinerImpl &IC) {
6799 // Don't bother doing this transformation for pointers, don't do it for
6800 // vectors.
6801 if (!isa<IntegerType>(Val->getType()))
6802 return nullptr;
6803
6804 auto *Instr = cast<Instruction>(Val);
6805 unsigned Opcode = Instr->getOpcode();
6806 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6807
6808 auto *LHS = cast<ZExtInst>(Instr->getOperand(0)),
6809 *RHS = cast<ZExtInst>(Instr->getOperand(1));
6810 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6811
6812 // Calculate type and width of the result produced by add/mul.with.overflow.
6813 Type *TyA = A->getType(), *TyB = B->getType();
6814 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6815 WidthB = TyB->getPrimitiveSizeInBits();
6816 unsigned ResultWidth;
6817 Type *ResultType;
6818 if (WidthB > WidthA) {
6819 ResultWidth = WidthB;
6820 ResultType = TyB;
6821 } else {
6822 ResultWidth = WidthA;
6823 ResultType = TyA;
6824 }
6825
6826 // In order to replace the original result with a narrower one, all uses must
6827 // ignore upper bits of the result. The number of used low bits must be not
6828 // greater than the width of add or mul.with.overflow.
6829 if (Val->hasNUsesOrMore(2))
6830 for (User *U : Val->users()) {
6831 if (U == &I)
6832 continue;
6833 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6834 // Check if truncation ignores bits above ResultWidth.
6835 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6836 if (TruncWidth > ResultWidth)
6837 return nullptr;
6838 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6839 // Check if AND ignores bits above ResultWidth.
6840 if (BO->getOpcode() != Instruction::And)
6841 return nullptr;
6842 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6843 const APInt &CVal = CI->getValue();
6844 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
6845 return nullptr;
6846 } else {
6847 // In this case we could have the operand of the binary operation
6848 // being defined in another block, and performing the replacement
6849 // could break the dominance relation.
6850 return nullptr;
6851 }
6852 } else {
6853 // Other uses prohibit this transformation.
6854 return nullptr;
6855 }
6856 }
6857
6858 // Recognize patterns
6859 switch (I.getPredicate()) {
6860 case ICmpInst::ICMP_UGT: {
6861 // Recognize pattern:
6862 // val = add/mul(zext A, zext B)
6863 // cmp ugt val, max
6864 APInt MaxVal = APInt::getMaxValue(ResultWidth);
6865 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6866 if (MaxVal.eq(*OtherVal))
6867 break; // Recognized
6868 return nullptr;
6869 }
6870
6871 case ICmpInst::ICMP_ULT: {
6872 // Recognize pattern:
6873 // val = add/mul(zext A, zext B)
6874 // cmp ult val, max + 1
6875 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), ResultWidth);
6876 if (MaxVal.eq(*OtherVal))
6877 break; // Recognized
6878 return nullptr;
6879 }
6880
6881 default:
6882 return nullptr;
6883 }
6884
6885 InstCombiner::BuilderTy &Builder = IC.Builder;
6886 Builder.SetInsertPoint(Instr);
6887
6888 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
6889 Value *ResultA = A, *ResultB = B;
6890 if (WidthA < ResultWidth)
6891 ResultA = Builder.CreateZExt(A, ResultType);
6892 if (WidthB < ResultWidth)
6893 ResultB = Builder.CreateZExt(B, ResultType);
6894
6895 Value *ArithResult;
6896 Value *OverflowCheck;
6897
6898 if (Opcode == Instruction::Add) {
6899 // Canonical add overflow check: add + compare
6900 ArithResult = Builder.CreateAdd(ResultA, ResultB, "add");
6901 // Overflow if result < either operand (for unsigned add)
6902 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6903 OverflowCheck =
6904 Builder.CreateICmpUGE(ArithResult, ResultA, "not.add.overflow");
6905 else
6906 OverflowCheck =
6907 Builder.CreateICmpULT(ArithResult, ResultA, "add.overflow");
6908 } else {
6909 // For multiplication, the intrinsic is actually the canonical form
6910 Value *Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
6911 ResultType, {ResultA, ResultB},
6912 /*FMFSource=*/nullptr, "umul");
6913 ArithResult = Builder.CreateExtractValue(Call, 0, "umul.value");
6914 OverflowCheck = Builder.CreateExtractValue(Call, 1, "umul.overflow");
6915 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6916 OverflowCheck = Builder.CreateNot(OverflowCheck);
6917 }
6918
6919 IC.addToWorklist(Instr);
6920
6921 // Replace uses of the original add/mul result with the new arithmetic result
6922 if (Val->hasNUsesOrMore(2)) {
6923 for (User *U : make_early_inc_range(Val->users())) {
6924 if (U == &I)
6925 continue;
6926 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6927 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
6928 IC.replaceInstUsesWith(*TI, ArithResult);
6929 else
6930 TI->setOperand(0, ArithResult);
6931 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6932 assert(BO->getOpcode() == Instruction::And);
6933 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
6934 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6935 APInt ShortMask = CI->getValue().trunc(ResultWidth);
6936 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
6937 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6938 IC.replaceInstUsesWith(*BO, Zext);
6939 } else {
6940 llvm_unreachable("Unexpected Binary operation");
6941 }
6943 }
6944 }
6945
6946 return IC.replaceInstUsesWith(I, OverflowCheck);
6947}
6948
6949/// When performing a comparison against a constant, it is possible that not all
6950/// the bits in the LHS are demanded. This helper method computes the mask that
6951/// IS demanded.
6953 const APInt *RHS;
6954 if (!match(I.getOperand(1), m_APInt(RHS)))
6956
6957 // If this is a normal comparison, it demands all bits. If it is a sign bit
6958 // comparison, it only demands the sign bit.
6959 bool UnusedBit;
6960 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
6962
6963 switch (I.getPredicate()) {
6964 // For a UGT comparison, we don't care about any bits that
6965 // correspond to the trailing ones of the comparand. The value of these
6966 // bits doesn't impact the outcome of the comparison, because any value
6967 // greater than the RHS must differ in a bit higher than these due to carry.
6968 case ICmpInst::ICMP_UGT:
6969 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
6970
6971 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
6972 // Any value less than the RHS must differ in a higher bit because of carries.
6973 case ICmpInst::ICMP_ULT:
6974 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
6975
6976 default:
6978 }
6979}
6980
6981/// Check that one use is in the same block as the definition and all
6982/// other uses are in blocks dominated by a given block.
6983///
6984/// \param DI Definition
6985/// \param UI Use
6986/// \param DB Block that must dominate all uses of \p DI outside
6987/// the parent block
6988/// \return true when \p UI is the only use of \p DI in the parent block
6989/// and all other uses of \p DI are in blocks dominated by \p DB.
6990///
6992 const Instruction *UI,
6993 const BasicBlock *DB) const {
6994 assert(DI && UI && "Instruction not defined\n");
6995 // Ignore incomplete definitions.
6996 if (!DI->getParent())
6997 return false;
6998 // DI and UI must be in the same block.
6999 if (DI->getParent() != UI->getParent())
7000 return false;
7001 // Protect from self-referencing blocks.
7002 if (DI->getParent() == DB)
7003 return false;
7004 for (const User *U : DI->users()) {
7005 auto *Usr = cast<Instruction>(U);
7006 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
7007 return false;
7008 }
7009 return true;
7010}
7011
7012/// Return true when the instruction sequence within a block is select-cmp-br.
7014 const BasicBlock *BB = SI->getParent();
7015 if (!BB)
7016 return false;
7018 if (!BI)
7019 return false;
7020 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7021 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7022 return false;
7023 return true;
7024}
7025
7026/// True when a select result is replaced by one of its operands
7027/// in select-icmp sequence. This will eventually result in the elimination
7028/// of the select.
7029///
7030/// \param SI Select instruction
7031/// \param Icmp Compare instruction
7032/// \param SIOpd Operand that replaces the select
7033///
7034/// Notes:
7035/// - The replacement is global and requires dominator information
7036/// - The caller is responsible for the actual replacement
7037///
7038/// Example:
7039///
7040/// entry:
7041/// %4 = select i1 %3, %C* %0, %C* null
7042/// %5 = icmp eq %C* %4, null
7043/// br i1 %5, label %9, label %7
7044/// ...
7045/// ; <label>:7 ; preds = %entry
7046/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7047/// ...
7048///
7049/// can be transformed to
7050///
7051/// %5 = icmp eq %C* %0, null
7052/// %6 = select i1 %3, i1 %5, i1 true
7053/// br i1 %6, label %9, label %7
7054/// ...
7055/// ; <label>:7 ; preds = %entry
7056/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7057///
7058/// Similar when the first operand of the select is a constant or/and
7059/// the compare is for not equal rather than equal.
7060///
7061/// NOTE: The function is only called when the select and compare constants
7062/// are equal, the optimization can work only for EQ predicates. This is not a
7063/// major restriction since a NE compare should be 'normalized' to an equal
7064/// compare, which usually happens in the combiner and test case
7065/// select-cmp-br.ll checks for it.
7067 const ICmpInst *Icmp,
7068 const unsigned SIOpd) {
7069 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7071 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7072 // The check for the single predecessor is not the best that can be
7073 // done. But it protects efficiently against cases like when SI's
7074 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7075 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7076 // replaced can be reached on either path. So the uniqueness check
7077 // guarantees that the path all uses of SI (outside SI's parent) are on
7078 // is disjoint from all other paths out of SI. But that information
7079 // is more expensive to compute, and the trade-off here is in favor
7080 // of compile-time. It should also be noticed that we check for a single
7081 // predecessor and not only uniqueness. This to handle the situation when
7082 // Succ and Succ1 points to the same basic block.
7083 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7084 NumSel++;
7085 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7086 return true;
7087 }
7088 }
7089 return false;
7090}
7091
7092/// Try to fold the comparison based on range information we can get by checking
7093/// whether bits are known to be zero or one in the inputs.
7095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7096 Type *Ty = Op0->getType();
7097 ICmpInst::Predicate Pred = I.getPredicate();
7098
7099 // Get scalar or pointer size.
7100 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7101 ? Ty->getScalarSizeInBits()
7102 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7103
7104 if (!BitWidth)
7105 return nullptr;
7106
7107 KnownBits Op0Known(BitWidth);
7108 KnownBits Op1Known(BitWidth);
7109
7110 {
7111 // Don't use dominating conditions when folding icmp using known bits. This
7112 // may convert signed into unsigned predicates in ways that other passes
7113 // (especially IndVarSimplify) may not be able to reliably undo.
7114 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7116 Op0Known, Q))
7117 return &I;
7118
7119 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7120 return &I;
7121 }
7122
7123 // If an unsigned samesign comparison is not poison, both operands have the
7124 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7125 // values so the existing range folds can use that constraint.
7126 if (I.hasSameSign() && I.isUnsigned()) {
7127 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7128 if (To.isNegative() || To.isNonNegative())
7129 return;
7130 if (From.isNegative())
7131 To.makeNegative();
7132 else if (From.isNonNegative())
7133 To.makeNonNegative();
7134 };
7135 PropagateSignBit(Op0Known, Op1Known);
7136 PropagateSignBit(Op1Known, Op0Known);
7137 }
7138
7139 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7140 return new ICmpInst(
7141 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7142 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7143 return new ICmpInst(
7144 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7145
7146 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7147 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7148
7149 // Given the known and unknown bits, compute a range that the LHS could be
7150 // in. Compute the Min, Max and RHS values based on the known bits. For the
7151 // EQ and NE we use unsigned values.
7152 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7153 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7154 if (I.isSigned()) {
7155 Op0Min = Op0Known.getSignedMinValue();
7156 Op0Max = Op0Known.getSignedMaxValue();
7157 Op1Min = Op1Known.getSignedMinValue();
7158 Op1Max = Op1Known.getSignedMaxValue();
7159 } else {
7160 Op0Min = Op0Known.getMinValue();
7161 Op0Max = Op0Known.getMaxValue();
7162 Op1Min = Op1Known.getMinValue();
7163 Op1Max = Op1Known.getMaxValue();
7164 }
7165
7166 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7167 // min/max canonical compare with some other compare. That could lead to
7168 // conflict with select canonicalization and infinite looping.
7169 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7170 auto isMinMaxCmp = [&](Instruction &Cmp) {
7171 if (!Cmp.hasOneUse())
7172 return false;
7173 Value *A, *B;
7174 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7176 return false;
7177 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7178 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7179 };
7180 if (!isMinMaxCmp(I)) {
7181 switch (Pred) {
7182 default:
7183 break;
7184 case ICmpInst::ICMP_ULT: {
7185 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7186 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7187 const APInt *CmpC;
7188 if (match(Op1, m_APInt(CmpC))) {
7189 // A <u C -> A == C-1 if min(A)+1 == C
7190 if (*CmpC == Op0Min + 1)
7191 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7192 ConstantInt::get(Op1->getType(), *CmpC - 1));
7193 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7194 // exceeds the log2 of C.
7195 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7196 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7197 Constant::getNullValue(Op1->getType()));
7198 }
7199 break;
7200 }
7201 case ICmpInst::ICMP_UGT: {
7202 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7203 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7204 const APInt *CmpC;
7205 if (match(Op1, m_APInt(CmpC))) {
7206 // A >u C -> A == C+1 if max(a)-1 == C
7207 if (*CmpC == Op0Max - 1)
7208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7209 ConstantInt::get(Op1->getType(), *CmpC + 1));
7210 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7211 // exceeds the log2 of C.
7212 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7213 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7214 Constant::getNullValue(Op1->getType()));
7215 }
7216 break;
7217 }
7218 case ICmpInst::ICMP_SLT: {
7219 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7220 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7221 const APInt *CmpC;
7222 if (match(Op1, m_APInt(CmpC))) {
7223 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7224 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7225 ConstantInt::get(Op1->getType(), *CmpC - 1));
7226 }
7227 break;
7228 }
7229 case ICmpInst::ICMP_SGT: {
7230 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7231 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7232 const APInt *CmpC;
7233 if (match(Op1, m_APInt(CmpC))) {
7234 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7235 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7236 ConstantInt::get(Op1->getType(), *CmpC + 1));
7237 }
7238 break;
7239 }
7240 }
7241 }
7242
7243 // Based on the range information we know about the LHS, see if we can
7244 // simplify this comparison. For example, (x&4) < 8 is always true.
7245 switch (Pred) {
7246 default:
7247 break;
7248 case ICmpInst::ICMP_EQ:
7249 case ICmpInst::ICMP_NE: {
7250 // If all bits are known zero except for one, then we know at most one bit
7251 // is set. If the comparison is against zero, then this is a check to see if
7252 // *that* bit is set.
7253 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7254 if (Op1Known.isZero()) {
7255 // If the LHS is an AND with the same constant, look through it.
7256 Value *LHS = nullptr;
7257 const APInt *LHSC;
7258 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7259 *LHSC != Op0KnownZeroInverted)
7260 LHS = Op0;
7261
7262 Value *X;
7263 const APInt *C1;
7264 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7265 Type *XTy = X->getType();
7266 unsigned Log2C1 = C1->countr_zero();
7267 APInt C2 = Op0KnownZeroInverted;
7268 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7269 if (C2Pow2.isPowerOf2()) {
7270 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7271 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7272 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7273 unsigned Log2C2 = C2Pow2.countr_zero();
7274 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7275 auto NewPred =
7277 return new ICmpInst(NewPred, X, CmpC);
7278 }
7279 }
7280 }
7281
7282 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7283 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7284 (Op0Known & Op1Known) == Op0Known)
7285 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7286 ConstantInt::getNullValue(Op1->getType()));
7287 break;
7288 }
7289 case ICmpInst::ICMP_SGE:
7290 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7291 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7292 break;
7293 case ICmpInst::ICMP_SLE:
7294 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7295 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7296 break;
7297 case ICmpInst::ICMP_UGE:
7298 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7299 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7300 break;
7301 case ICmpInst::ICMP_ULE:
7302 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7303 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7304 break;
7305 }
7306
7307 // Turn a signed comparison into an unsigned one if both operands are known to
7308 // have the same sign. Set samesign if possible (except for equality
7309 // predicates).
7310 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7311 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7312 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7313 I.setPredicate(I.getUnsignedPredicate());
7314 I.setSameSign();
7315 return &I;
7316 }
7317
7318 return nullptr;
7319}
7320
7321/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7322/// then try to reduce patterns based on that limit.
7324 Value *X, *Y;
7325 CmpPredicate Pred;
7326
7327 // X must be 0 and bool must be true for "ULT":
7328 // X <u (zext i1 Y) --> (X == 0) & Y
7329 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7330 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7331 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7332
7333 // X must be 0 or bool must be true for "ULE":
7334 // X <=u (sext i1 Y) --> (X == 0) | Y
7335 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7336 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7337 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7338
7339 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7340 CmpPredicate Pred1, Pred2;
7341 const APInt *C;
7342 Instruction *ExtI;
7343 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7346 m_APInt(C)))))) &&
7347 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7348 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7349 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7350 auto CreateRangeCheck = [&] {
7351 Value *CmpV1 =
7352 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7353 Value *CmpV2 = Builder.CreateICmp(
7354 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7356 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7357 CmpV1, CmpV2);
7358 };
7359 if (C->isZero()) {
7360 if (Pred2 == ICmpInst::ICMP_EQ) {
7361 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7362 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7363 return replaceInstUsesWith(
7364 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7365 } else if (!IsSExt || HasOneUse) {
7366 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7367 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7368 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7369 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7370 return CreateRangeCheck();
7371 }
7372 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7373 if (Pred2 == ICmpInst::ICMP_NE) {
7374 // icmp eq X, (zext (icmp ne X, 1)) --> false
7375 // icmp ne X, (zext (icmp ne X, 1)) --> true
7376 // icmp eq X, (sext (icmp ne X, -1)) --> false
7377 // icmp ne X, (sext (icmp ne X, -1)) --> true
7378 return replaceInstUsesWith(
7379 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7380 } else if (!IsSExt || HasOneUse) {
7381 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7382 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7383 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7384 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7385 return CreateRangeCheck();
7386 }
7387 } else {
7388 // when C != 0 && C != 1:
7389 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7390 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7391 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7392 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7393 // when C != 0 && C != -1:
7394 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7395 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7396 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7397 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7398 return ICmpInst::Create(
7399 Instruction::ICmp, Pred1, X,
7400 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7401 ? (IsSExt ? -1 : 1)
7402 : 0));
7403 }
7404 }
7405
7406 return nullptr;
7407}
7408
7409/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7410/// it into the appropriate icmp lt or icmp gt instruction. This transform
7411/// allows them to be folded in visitICmpInst.
7413 CmpPredicate Pred = I.getCmpPredicate();
7414 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7416 return nullptr;
7417
7418 Value *Op0 = I.getOperand(0);
7419 Value *Op1 = I.getOperand(1);
7420 auto *Op1C = dyn_cast<Constant>(Op1);
7421 if (!Op1C)
7422 return nullptr;
7423
7424 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7425 if (!FlippedStrictness)
7426 return nullptr;
7427
7428 auto *NewCmp =
7429 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7430 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7431 return NewCmp;
7432}
7433
7434/// If we have a comparison with a non-canonical predicate, if we can update
7435/// all the users, invert the predicate and adjust all the users.
7437 // Is the predicate already canonical?
7438 CmpInst::Predicate Pred = I.getPredicate();
7440 return nullptr;
7441
7442 // Can all users be adjusted to predicate inversion?
7443 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7444 return nullptr;
7445
7446 // Ok, we can canonicalize comparison!
7447 // Let's first invert the comparison's predicate.
7448 I.setPredicate(CmpInst::getInversePredicate(Pred));
7449 I.setName(I.getName() + ".not");
7450
7451 // And, adapt users.
7453
7454 return &I;
7455}
7456
7457/// Integer compare with boolean values can always be turned into bitwise ops.
7459 InstCombiner::BuilderTy &Builder) {
7460 Value *A = I.getOperand(0), *B = I.getOperand(1);
7461 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7462
7463 // A boolean compared to true/false can be simplified to Op0/true/false in
7464 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7465 // Cases not handled by InstSimplify are always 'not' of Op0.
7466 if (match(B, m_Zero())) {
7467 switch (I.getPredicate()) {
7468 case CmpInst::ICMP_EQ: // A == 0 -> !A
7469 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7470 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7472 default:
7473 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7474 }
7475 } else if (match(B, m_One())) {
7476 switch (I.getPredicate()) {
7477 case CmpInst::ICMP_NE: // A != 1 -> !A
7478 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7479 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7481 default:
7482 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7483 }
7484 }
7485
7486 switch (I.getPredicate()) {
7487 default:
7488 llvm_unreachable("Invalid icmp instruction!");
7489 case ICmpInst::ICMP_EQ:
7490 // icmp eq i1 A, B -> ~(A ^ B)
7491 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7492
7493 case ICmpInst::ICMP_NE:
7494 // icmp ne i1 A, B -> A ^ B
7495 return BinaryOperator::CreateXor(A, B);
7496
7497 case ICmpInst::ICMP_UGT:
7498 // icmp ugt -> icmp ult
7499 std::swap(A, B);
7500 [[fallthrough]];
7501 case ICmpInst::ICMP_ULT:
7502 // icmp ult i1 A, B -> ~A & B
7503 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7504
7505 case ICmpInst::ICMP_SGT:
7506 // icmp sgt -> icmp slt
7507 std::swap(A, B);
7508 [[fallthrough]];
7509 case ICmpInst::ICMP_SLT:
7510 // icmp slt i1 A, B -> A & ~B
7511 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7512
7513 case ICmpInst::ICMP_UGE:
7514 // icmp uge -> icmp ule
7515 std::swap(A, B);
7516 [[fallthrough]];
7517 case ICmpInst::ICMP_ULE:
7518 // icmp ule i1 A, B -> ~A | B
7519 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7520
7521 case ICmpInst::ICMP_SGE:
7522 // icmp sge -> icmp sle
7523 std::swap(A, B);
7524 [[fallthrough]];
7525 case ICmpInst::ICMP_SLE:
7526 // icmp sle i1 A, B -> A | ~B
7527 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7528 }
7529}
7530
7531// Transform pattern like:
7532// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7533// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7534// Into:
7535// (X l>> Y) != 0
7536// (X l>> Y) == 0
7538 InstCombiner::BuilderTy &Builder) {
7539 CmpPredicate Pred, NewPred;
7540 Value *X, *Y;
7541 if (match(&Cmp,
7542 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7543 switch (Pred) {
7544 case ICmpInst::ICMP_ULE:
7545 NewPred = ICmpInst::ICMP_NE;
7546 break;
7547 case ICmpInst::ICMP_UGT:
7548 NewPred = ICmpInst::ICMP_EQ;
7549 break;
7550 default:
7551 return nullptr;
7552 }
7553 } else if (match(&Cmp, m_c_ICmp(Pred,
7556 m_Add(m_Shl(m_One(), m_Value(Y)),
7557 m_AllOnes()))),
7558 m_Value(X)))) {
7559 // The variant with 'add' is not canonical, (the variant with 'not' is)
7560 // we only get it because it has extra uses, and can't be canonicalized,
7561
7562 switch (Pred) {
7563 case ICmpInst::ICMP_ULT:
7564 NewPred = ICmpInst::ICMP_NE;
7565 break;
7566 case ICmpInst::ICMP_UGE:
7567 NewPred = ICmpInst::ICMP_EQ;
7568 break;
7569 default:
7570 return nullptr;
7571 }
7572 } else
7573 return nullptr;
7574
7575 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7576 Constant *Zero = Constant::getNullValue(NewX->getType());
7577 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7578}
7579
7581 InstCombiner::BuilderTy &Builder) {
7582 const CmpInst::Predicate Pred = Cmp.getPredicate();
7583 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7584 Value *V1, *V2;
7585
7586 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7587 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7588 if (auto *I = dyn_cast<Instruction>(V))
7589 I->copyIRFlags(&Cmp);
7590 Module *M = Cmp.getModule();
7592 M, Intrinsic::vector_reverse, V->getType());
7593 return CallInst::Create(F, V);
7594 };
7595
7596 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7597 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7598 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7599 (LHS->hasOneUse() || RHS->hasOneUse()))
7600 return createCmpReverse(Pred, V1, V2);
7601
7602 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7603 if (LHS->hasOneUse() && isSplatValue(RHS))
7604 return createCmpReverse(Pred, V1, RHS);
7605 }
7606 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7607 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7608 return createCmpReverse(Pred, LHS, V2);
7609
7610 ArrayRef<int> M;
7611 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7612 return nullptr;
7613
7614 // If both arguments of the cmp are shuffles that use the same mask and
7615 // shuffle within a single vector, move the shuffle after the cmp:
7616 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7617 Type *V1Ty = V1->getType();
7618 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7619 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7620 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7621 return new ShuffleVectorInst(NewCmp, M);
7622 }
7623
7624 // Try to canonicalize compare with splatted operand and splat constant.
7625 // TODO: We could generalize this for more than splats. See/use the code in
7626 // InstCombiner::foldVectorBinop().
7627 Constant *C;
7628 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7629 return nullptr;
7630
7631 // Length-changing splats are ok, so adjust the constants as needed:
7632 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7633 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7634 int MaskSplatIndex;
7635 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7636 // We allow poison in matching, but this transform removes it for safety.
7637 // Demanded elements analysis should be able to recover some/all of that.
7638 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7639 ScalarC);
7640 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7641 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7642 return new ShuffleVectorInst(NewCmp, NewM);
7643 }
7644
7645 return nullptr;
7646}
7647
7648// extract(uadd.with.overflow(A, B), 0) ult A
7649// -> extract(uadd.with.overflow(A, B), 1)
7651 CmpInst::Predicate Pred = I.getPredicate();
7652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7653
7654 Value *UAddOv;
7655 Value *A, *B;
7656 auto UAddOvResultPat = m_ExtractValue<0>(
7658 if (match(Op0, UAddOvResultPat) &&
7659 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7660 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7661 (match(A, m_One()) || match(B, m_One()))) ||
7662 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7663 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7664 // extract(uadd.with.overflow(A, B), 0) < A
7665 // extract(uadd.with.overflow(A, 1), 0) == 0
7666 // extract(uadd.with.overflow(A, -1), 0) != -1
7667 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7668 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7669 (Op0 == A || Op0 == B))
7670 // A > extract(uadd.with.overflow(A, B), 0)
7671 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7672 else
7673 return nullptr;
7674
7675 return ExtractValueInst::Create(UAddOv, 1);
7676}
7677
7679 if (!I.getOperand(0)->getType()->isPointerTy() ||
7681 I.getParent()->getParent(),
7682 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7683 return nullptr;
7684 }
7685 Instruction *Op;
7686 if (match(I.getOperand(0), m_Instruction(Op)) &&
7687 match(I.getOperand(1), m_Zero()) &&
7688 Op->isLaunderOrStripInvariantGroup()) {
7689 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
7690 Op->getOperand(0), I.getOperand(1));
7691 }
7692 return nullptr;
7693}
7694
7696 IRBuilderBase &Builder) {
7697 if (!ICmpInst::isEquality(I.getPredicate()))
7698 return nullptr;
7699
7700 // The caller puts constants after non-constants.
7701 Value *Op = I.getOperand(0);
7702 Value *Const = I.getOperand(1);
7703
7704 // For Cond an equality condition, fold
7705 //
7706 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7707 // icmp (eq|ne) Op, (Zero|AllOnes)
7708 //
7709 // with a bitcast.
7710 Value *Vec;
7711 if ((match(Const, m_ZeroInt()) &&
7713 m_Value(Vec))))) ||
7714 (match(Const, m_AllOnes()) &&
7716 m_Value(Vec)))))) {
7717 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7718 if (!VecTy)
7719 return nullptr;
7720 Type *VecEltTy = VecTy->getElementType();
7721 unsigned ScalarBW =
7722 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7723 if (!DL.fitsInLegalInteger(ScalarBW))
7724 return nullptr;
7725 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7726 Value *NewConst = match(Const, m_ZeroInt())
7727 ? ConstantInt::get(ScalarTy, 0)
7728 : ConstantInt::getAllOnesValue(ScalarTy);
7729 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7730 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7731 }
7732 return nullptr;
7733}
7734
7735/// This function folds patterns produced by lowering of reduce idioms, such as
7736/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7737/// attempts to generate fewer number of scalar comparisons instead of vector
7738/// comparisons when possible.
7740 InstCombiner::BuilderTy &Builder,
7741 const DataLayout &DL) {
7742 if (I.getType()->isVectorTy())
7743 return nullptr;
7744 CmpPredicate OuterPred, InnerPred;
7745 Value *LHS, *RHS;
7746
7747 // Match lowering of @llvm.vector.reduce.and. Turn
7748 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7749 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7750 /// %res = icmp <pred> i8 %scalar_ne, 0
7751 ///
7752 /// into
7753 ///
7754 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7755 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7756 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7757 ///
7758 /// for <pred> in {ne, eq}.
7759 if (!match(&I, m_ICmp(OuterPred,
7761 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7762 m_Zero())))
7763 return nullptr;
7764 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7765 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7766 return nullptr;
7767 unsigned NumBits =
7768 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7769 // TODO: Relax this to "not wider than max legal integer type"?
7770 if (!DL.isLegalInteger(NumBits))
7771 return nullptr;
7772
7773 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7774 auto *ScalarTy = Builder.getIntNTy(NumBits);
7775 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7776 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7777 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7778 I.getName());
7779 }
7780
7781 return nullptr;
7782}
7783
7784// This helper will be called with icmp operands in both orders.
7786 Value *Op0, Value *Op1,
7787 ICmpInst &CxtI) {
7788 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7789 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7790 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CxtI))
7791 return NI;
7792
7793 if (auto *SI = dyn_cast<SelectInst>(Op0))
7794 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CxtI))
7795 return NI;
7796
7797 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7798 if (Instruction *Res = foldICmpWithMinMax(CxtI, MinMax, Op1, Pred))
7799 return Res;
7800
7801 if (Instruction *Res = foldICmpWithClamp(CxtI, Op1, MinMax))
7802 return Res;
7803 }
7804
7805 {
7806 Value *X;
7807 const APInt *C;
7808 // icmp X+Cst, X
7809 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7810 return foldICmpAddOpConst(X, *C, Pred);
7811 }
7812
7813 // abs(X) >= X --> true
7814 // abs(X) u<= X --> true
7815 // abs(X) < X --> false
7816 // abs(X) u> X --> false
7817 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7818 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7819 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7820 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7821 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7822 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7823 {
7824 Value *X;
7825 Constant *C;
7827 match(Op1, m_Specific(X))) {
7828 Value *NullValue = Constant::getNullValue(X->getType());
7829 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7830 const APInt SMin =
7831 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7832 bool IsIntMinPosion = C->isAllOnesValue();
7833 switch (Pred) {
7834 case CmpInst::ICMP_ULE:
7835 case CmpInst::ICMP_SGE:
7836 return replaceInstUsesWith(CxtI, ConstantInt::getTrue(CxtI.getType()));
7837 case CmpInst::ICMP_UGT:
7838 case CmpInst::ICMP_SLT:
7840 case CmpInst::ICMP_UGE:
7841 case CmpInst::ICMP_SLE:
7842 case CmpInst::ICMP_EQ: {
7843 return replaceInstUsesWith(
7844 CxtI, IsIntMinPosion
7845 ? Builder.CreateICmpSGT(X, AllOnesValue)
7846 : Builder.CreateICmpULT(
7847 X, ConstantInt::get(X->getType(), SMin + 1)));
7848 }
7849 case CmpInst::ICMP_ULT:
7850 case CmpInst::ICMP_SGT:
7851 case CmpInst::ICMP_NE: {
7852 return replaceInstUsesWith(
7853 CxtI, IsIntMinPosion
7854 ? Builder.CreateICmpSLT(X, NullValue)
7855 : Builder.CreateICmpUGT(
7856 X, ConstantInt::get(X->getType(), SMin)));
7857 }
7858 default:
7859 llvm_unreachable("Invalid predicate!");
7860 }
7861 }
7862 }
7863
7864 const SimplifyQuery Q = SQ.getWithInstruction(&CxtI);
7865 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7866 return replaceInstUsesWith(CxtI, V);
7867
7868 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7869 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7870 {
7871 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7872 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7874 }
7875
7876 if (!ICmpInst::isUnsigned(Pred) &&
7877 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7878 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7880 }
7881 }
7882
7883 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7884 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7885 {
7886 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7887 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7889 }
7890
7891 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7892 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7893 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7895 }
7896 }
7897
7898 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7899 // -> icmp X, (add nsw/nuw Y, K >> L)
7900 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7901 Value *X;
7902 uint64_t ShAmt;
7903 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7904 !CxtI.isSigned()) {
7905 if (ShAmt >= X->getType()->getScalarSizeInBits())
7906 return nullptr;
7907 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7908 ShiftSemantics::Unsigned, &CxtI)) {
7909 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7911 return new ICmpInst(Pred, X, NewOp1);
7912 }
7913 }
7914
7915 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7916 !CxtI.isUnsigned()) {
7917 if (ShAmt >= X->getType()->getScalarSizeInBits())
7918 return nullptr;
7919 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7920 ShiftSemantics::Signed, &CxtI)) {
7921 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7923 return new ICmpInst(Pred, X, NewOp1);
7924 }
7925 }
7926 return nullptr;
7927}
7928
7930 bool Changed = false;
7931 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7933 unsigned Op0Cplxity = getComplexity(Op0);
7934 unsigned Op1Cplxity = getComplexity(Op1);
7935
7936 /// Orders the operands of the compare so that they are listed from most
7937 /// complex to least complex. This puts constants before unary operators,
7938 /// before binary operators.
7939 if (Op0Cplxity < Op1Cplxity) {
7940 I.swapOperands();
7941 std::swap(Op0, Op1);
7942 Changed = true;
7943 }
7944
7945 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7946 return replaceInstUsesWith(I, V);
7947
7948 // Comparing -val or val with non-zero is the same as just comparing val
7949 // ie, abs(val) != 0 -> val != 0
7950 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
7951 Value *Cond, *SelectTrue, *SelectFalse;
7952 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
7953 m_Value(SelectFalse)))) {
7954 if (Value *V = dyn_castNegVal(SelectTrue)) {
7955 if (V == SelectFalse)
7956 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7957 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
7958 if (V == SelectTrue)
7959 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
7960 }
7961 }
7962 }
7963
7965 return Res;
7966
7967 if (Op0->getType()->isIntOrIntVectorTy(1))
7969 return Res;
7970
7972 return Res;
7973
7975 return Res;
7976
7978 return Res;
7979
7981 return Res;
7982
7984 return Res;
7985
7987 return Res;
7988
7990 return Res;
7991
7992 // Test if the ICmpInst instruction is used exclusively by a select as
7993 // part of a minimum or maximum operation. If so, refrain from doing
7994 // any other folding. This helps out other analyses which understand
7995 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
7996 // and CodeGen. And in this case, at least one of the comparison
7997 // operands has at least one user besides the compare (the select),
7998 // which would often largely negate the benefit of folding anyway.
7999 //
8000 // Do the same for the other patterns recognized by matchSelectPattern.
8001 if (I.hasOneUse())
8002 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8003 Value *A, *B;
8005 if (SPR.Flavor != SPF_UNKNOWN)
8006 return nullptr;
8007 }
8008
8009 // Do this after checking for min/max to prevent infinite looping.
8010 if (Instruction *Res = foldICmpWithZero(I))
8011 return Res;
8012
8013 Value *X;
8014 const APInt *C;
8015 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8016 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8017 match(Op1, m_Not(m_Specific(X)))) {
8018 if (C->isNonNegative())
8019 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8020 Constant::getNullValue(X->getType()));
8021 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8022 ConstantInt::get(X->getType(), ~*C));
8023 }
8024
8025 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8026 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8027 match(Op1, m_Not(m_Specific(X)))) {
8028 if (C->isNonNegative())
8029 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8030 Constant::getAllOnesValue(X->getType()));
8031 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8032 ConstantInt::get(X->getType(), ~*C));
8033 }
8034
8035 // FIXME: We only do this after checking for min/max to prevent infinite
8036 // looping caused by a reverse canonicalization of these patterns for min/max.
8037 // FIXME: The organization of folds is a mess. These would naturally go into
8038 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8039 // down here after the min/max restriction.
8040 ICmpInst::Predicate Pred = I.getPredicate();
8041 if (match(Op1, m_APInt(C))) {
8042 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8043 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8044 Constant *Zero = Constant::getNullValue(Op0->getType());
8045 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8046 }
8047
8048 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8049 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8051 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8052 }
8053 }
8054
8055 // The folds in here may rely on wrapping flags and special constants, so
8056 // they can break up min/max idioms in some cases but not seemingly similar
8057 // patterns.
8058 // FIXME: It may be possible to enhance select folding to make this
8059 // unnecessary. It may also be moot if we canonicalize to min/max
8060 // intrinsics.
8061 if (Instruction *Res = foldICmpBinOp(I, Q))
8062 return Res;
8063
8065 return Res;
8066
8067 // Try to match comparison as a sign bit test. Intentionally do this after
8068 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8069 if (Instruction *New = foldSignBitTest(I))
8070 return New;
8071
8072 if (auto *PN = dyn_cast<PHINode>(Op0))
8073 if (Instruction *NV = foldOpIntoPhi(I, PN))
8074 return NV;
8075 if (auto *PN = dyn_cast<PHINode>(Op1))
8076 if (Instruction *NV = foldOpIntoPhi(I, PN))
8077 return NV;
8078
8080 return Res;
8081
8082 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8083 return Res;
8084 if (Instruction *Res =
8085 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8086 return Res;
8087
8088 if (I.isCommutative()) {
8089 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8090 replaceOperand(I, 0, Pair->first);
8091 replaceOperand(I, 1, Pair->second);
8092 return &I;
8093 }
8094 }
8095
8096 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8097 // when all select arms are constants, via truth table.
8099 return R;
8100
8101 // In case of a comparison with two select instructions having the same
8102 // condition, check whether one of the resulting branches can be simplified.
8103 // If so, just compare the other branch and select the appropriate result.
8104 // For example:
8105 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8106 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8107 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8108 // The icmp will result false for the false value of selects and the result
8109 // will depend upon the comparison of true values of selects if %cmp is
8110 // true. Thus, transform this into:
8111 // %cmp = icmp slt i32 %y, %z
8112 // %sel = select i1 %cond, i1 %cmp, i1 false
8113 // This handles similar cases to transform.
8114 {
8115 Value *Cond, *A, *B, *C, *D;
8116 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8118 (Op0->hasOneUse() || Op1->hasOneUse())) {
8119 // Check whether comparison of TrueValues can be simplified
8120 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8121 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8122 return SelectInst::Create(
8123 Cond, Res, NewICMP, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8125 }
8126 // Check whether comparison of FalseValues can be simplified
8127 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8128 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8129 return SelectInst::Create(
8130 Cond, NewICMP, Res, /*NameStr=*/"", /*InsertBefore=*/nullptr,
8132 }
8133 }
8134 }
8135
8136 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8137 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8138 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8139 {
8140 Value *A, *B;
8141 CmpPredicate CmpPred;
8142 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8144 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8145 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8146 bool I0NUW = I0->hasNoUnsignedWrap();
8147 bool I1NUW = I1->hasNoUnsignedWrap();
8148 bool I0NSW = I0->hasNoSignedWrap();
8149 bool I1NSW = I1->hasNoSignedWrap();
8150 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8151 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8152 (ICmpInst::isEquality(Pred) &&
8153 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8154 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8155 ConstantInt::get(Op0->getType(), 0));
8156 }
8157 }
8158 }
8159
8160 // Try to optimize equality comparisons against alloca-based pointers.
8161 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8162 assert(Op1->getType()->isPointerTy() &&
8163 "Comparing pointer with non-pointer?");
8164 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8165 if (foldAllocaCmp(Alloca))
8166 return nullptr;
8167 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8168 if (foldAllocaCmp(Alloca))
8169 return nullptr;
8170 }
8171
8172 if (Instruction *Res = foldICmpBitCast(I))
8173 return Res;
8174
8175 // TODO: Hoist this above the min/max bailout.
8177 return R;
8178
8179 {
8180 Value *X, *Y;
8181 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8182 // and (X & ~Y) != 0 --> (X & Y) == 0
8183 // if A is a power of 2.
8184 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8185 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8186 I.isEquality())
8187 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8188 Op1);
8189
8190 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8191 if (Op0->getType()->isIntOrIntVectorTy()) {
8192 bool ConsumesOp0, ConsumesOp1;
8193 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8194 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8195 (ConsumesOp0 || ConsumesOp1)) {
8196 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8197 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8198 assert(InvOp0 && InvOp1 &&
8199 "Mismatch between isFreeToInvert and getFreelyInverted");
8200 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8201 }
8202 }
8203
8204 Instruction *AddI = nullptr;
8206 m_Instruction(AddI))) &&
8207 isa<IntegerType>(X->getType())) {
8208 Value *Result;
8209 Constant *Overflow;
8210 // m_UAddWithOverflow can match patterns that do not include an explicit
8211 // "add" instruction, so check the opcode of the matched op.
8212 if (AddI->getOpcode() == Instruction::Add &&
8213 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8214 Result, Overflow)) {
8215 replaceInstUsesWith(*AddI, Result);
8216 eraseInstFromFunction(*AddI);
8217 return replaceInstUsesWith(I, Overflow);
8218 }
8219 }
8220
8221 // (zext X) + (zext Y) --> add + overflow check.
8222 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8223 if ((match(Op0, m_NUWAdd(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) ||
8224 match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y))))) &&
8225 match(Op1, m_APInt(C))) {
8226 if (Instruction *R = processUZExtIdiom(I, Op0, C, *this))
8227 return R;
8228 }
8229
8230 // Signbit test folds
8231 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8232 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8233 Instruction *ExtI;
8234 if ((I.isUnsigned() || I.isEquality()) &&
8235 match(Op1,
8237 Y->getType()->getScalarSizeInBits() == 1 &&
8238 (Op0->hasOneUse() || Op1->hasOneUse())) {
8239 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8240 Instruction *ShiftI;
8241 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8243 OpWidth - 1))))) {
8244 unsigned ExtOpc = ExtI->getOpcode();
8245 unsigned ShiftOpc = ShiftI->getOpcode();
8246 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8247 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8248 Value *SLTZero =
8249 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8250 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8251 return replaceInstUsesWith(I, Cmp);
8252 }
8253 }
8254 }
8255 }
8256
8257 if (Instruction *Res = foldICmpEquality(I))
8258 return Res;
8259
8261 return Res;
8262
8263 if (Instruction *Res = foldICmpOfUAddOv(I))
8264 return Res;
8265
8267 return Res;
8268
8269 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8270 // an i1 which indicates whether or not we successfully did the swap.
8271 //
8272 // Replace comparisons between the old value and the expected value with the
8273 // indicator that 'cmpxchg' returns.
8274 //
8275 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8276 // spuriously fail. In those cases, the old value may equal the expected
8277 // value but it is possible for the swap to not occur.
8278 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8279 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8280 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8281 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8282 !ACXI->isWeak())
8283 return ExtractValueInst::Create(ACXI, 1);
8284
8286 return Res;
8287
8288 if (I.getType()->isVectorTy())
8289 if (Instruction *Res = foldVectorCmp(I, Builder))
8290 return Res;
8291
8293 return Res;
8294
8296 return Res;
8297
8298 {
8299 Value *A;
8300 const APInt *C1, *C2;
8301 ICmpInst::Predicate Pred = I.getPredicate();
8302 if (ICmpInst::isEquality(Pred)) {
8303 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8304 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8305 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8306 match(Op1, m_APInt(C2))) {
8307 Type *InputTy = A->getType();
8308 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8309 // c2 must be non-negative at the bitwidth of a.
8310 if (C2->getActiveBits() < InputBitWidth) {
8311 APInt TruncC1 = C1->trunc(InputBitWidth);
8312 // Check if there are 1s in C1 high bits of size InputBitWidth.
8313 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8314 TruncC1.setBit(InputBitWidth - 1);
8315 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8316 return new ICmpInst(
8317 Pred, AndInst,
8318 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8319 }
8320 }
8321 }
8322 }
8323
8324 return Changed ? &I : nullptr;
8325}
8326
8327/// Fold fcmp ([us]itofp x, cst) if possible.
8329 Instruction *LHSI,
8330 Constant *RHSC) {
8331 const APFloat *RHS;
8332 if (!match(RHSC, m_APFloat(RHS)))
8333 return nullptr;
8334
8335 // Get the width of the mantissa. We don't want to hack on conversions that
8336 // might lose information from the integer, e.g. "i64 -> float"
8337 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8338 if (MantissaWidth == -1)
8339 return nullptr; // Unknown.
8340
8341 Type *IntTy = LHSI->getOperand(0)->getType();
8342 unsigned IntWidth = IntTy->getScalarSizeInBits();
8343 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8344
8345 if (I.isEquality()) {
8346 FCmpInst::Predicate P = I.getPredicate();
8347 bool IsExact = false;
8348 APSInt RHSCvt(IntWidth, LHSUnsigned);
8349 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8350
8351 // If the floating point constant isn't an integer value, we know if we will
8352 // ever compare equal / not equal to it.
8353 if (!IsExact) {
8354 // TODO: Can never be -0.0 and other non-representable values
8355 APFloat RHSRoundInt(*RHS);
8357 if (*RHS != RHSRoundInt) {
8359 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8360
8362 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8363 }
8364 }
8365
8366 // TODO: If the constant is exactly representable, is it always OK to do
8367 // equality compares as integer?
8368 }
8369
8370 // Check to see that the input is converted from an integer type that is small
8371 // enough that preserves all bits. TODO: check here for "known" sign bits.
8372 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8373
8374 // Following test does NOT adjust IntWidth downwards for signed inputs,
8375 // because the most negative value still requires all the mantissa bits
8376 // to distinguish it from one less than that value.
8377 if ((int)IntWidth > MantissaWidth) {
8378 // Conversion would lose accuracy. Check if loss can impact comparison.
8379 int Exp = ilogb(*RHS);
8380 if (Exp == APFloat::IEK_Inf) {
8381 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8382 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8383 // Conversion could create infinity.
8384 return nullptr;
8385 } else {
8386 // Note that if RHS is zero or NaN, then Exp is negative
8387 // and first condition is trivially false.
8388 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8389 // Conversion could affect comparison.
8390 return nullptr;
8391 }
8392 }
8393
8394 // Otherwise, we can potentially simplify the comparison. We know that it
8395 // will always come through as an integer value and we know the constant is
8396 // not a NAN (it would have been previously simplified).
8397 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8398
8400 switch (I.getPredicate()) {
8401 default:
8402 llvm_unreachable("Unexpected predicate!");
8403 case FCmpInst::FCMP_UEQ:
8404 case FCmpInst::FCMP_OEQ:
8405 Pred = ICmpInst::ICMP_EQ;
8406 break;
8407 case FCmpInst::FCMP_UGT:
8408 case FCmpInst::FCMP_OGT:
8409 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8410 break;
8411 case FCmpInst::FCMP_UGE:
8412 case FCmpInst::FCMP_OGE:
8413 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8414 break;
8415 case FCmpInst::FCMP_ULT:
8416 case FCmpInst::FCMP_OLT:
8417 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8418 break;
8419 case FCmpInst::FCMP_ULE:
8420 case FCmpInst::FCMP_OLE:
8421 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8422 break;
8423 case FCmpInst::FCMP_UNE:
8424 case FCmpInst::FCMP_ONE:
8425 Pred = ICmpInst::ICMP_NE;
8426 break;
8427 case FCmpInst::FCMP_ORD:
8428 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8429 case FCmpInst::FCMP_UNO:
8430 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8431 }
8432
8433 // Now we know that the APFloat is a normal number, zero or inf.
8434
8435 // See if the FP constant is too large for the integer. For example,
8436 // comparing an i8 to 300.0.
8437 if (!LHSUnsigned) {
8438 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8439 // and large values.
8440 APFloat SMax(RHS->getSemantics());
8441 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8443 if (SMax < *RHS) { // smax < 13123.0
8444 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8445 Pred == ICmpInst::ICMP_SLE)
8446 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8447 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8448 }
8449 } else {
8450 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8451 // +INF and large values.
8452 APFloat UMax(RHS->getSemantics());
8453 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8455 if (UMax < *RHS) { // umax < 13123.0
8456 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8457 Pred == ICmpInst::ICMP_ULE)
8458 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8459 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8460 }
8461 }
8462
8463 if (!LHSUnsigned) {
8464 // See if the RHS value is < SignedMin.
8465 APFloat SMin(RHS->getSemantics());
8466 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8468 if (SMin > *RHS) { // smin > 12312.0
8469 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8470 Pred == ICmpInst::ICMP_SGE)
8471 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8472 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8473 }
8474 } else {
8475 // See if the RHS value is < UnsignedMin.
8476 APFloat UMin(RHS->getSemantics());
8477 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8479 if (UMin > *RHS) { // umin > 12312.0
8480 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8481 Pred == ICmpInst::ICMP_UGE)
8482 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8483 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8484 }
8485 }
8486
8487 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8488 // [0, UMAX], but it may still be fractional. Check whether this is the case
8489 // using the IsExact flag.
8490 // Don't do this for zero, because -0.0 is not fractional.
8491 APSInt RHSInt(IntWidth, LHSUnsigned);
8492 bool IsExact;
8493 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8494 if (!RHS->isZero()) {
8495 if (!IsExact) {
8496 // If we had a comparison against a fractional value, we have to adjust
8497 // the compare predicate and sometimes the value. RHSC is rounded towards
8498 // zero at this point.
8499 switch (Pred) {
8500 default:
8501 llvm_unreachable("Unexpected integer comparison!");
8502 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8503 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8504 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8505 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8506 case ICmpInst::ICMP_ULE:
8507 // (float)int <= 4.4 --> int <= 4
8508 // (float)int <= -4.4 --> false
8509 if (RHS->isNegative())
8510 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8511 break;
8512 case ICmpInst::ICMP_SLE:
8513 // (float)int <= 4.4 --> int <= 4
8514 // (float)int <= -4.4 --> int < -4
8515 if (RHS->isNegative())
8516 Pred = ICmpInst::ICMP_SLT;
8517 break;
8518 case ICmpInst::ICMP_ULT:
8519 // (float)int < -4.4 --> false
8520 // (float)int < 4.4 --> int <= 4
8521 if (RHS->isNegative())
8522 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8523 Pred = ICmpInst::ICMP_ULE;
8524 break;
8525 case ICmpInst::ICMP_SLT:
8526 // (float)int < -4.4 --> int < -4
8527 // (float)int < 4.4 --> int <= 4
8528 if (!RHS->isNegative())
8529 Pred = ICmpInst::ICMP_SLE;
8530 break;
8531 case ICmpInst::ICMP_UGT:
8532 // (float)int > 4.4 --> int > 4
8533 // (float)int > -4.4 --> true
8534 if (RHS->isNegative())
8535 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8536 break;
8537 case ICmpInst::ICMP_SGT:
8538 // (float)int > 4.4 --> int > 4
8539 // (float)int > -4.4 --> int >= -4
8540 if (RHS->isNegative())
8541 Pred = ICmpInst::ICMP_SGE;
8542 break;
8543 case ICmpInst::ICMP_UGE:
8544 // (float)int >= -4.4 --> true
8545 // (float)int >= 4.4 --> int > 4
8546 if (RHS->isNegative())
8547 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8548 Pred = ICmpInst::ICMP_UGT;
8549 break;
8550 case ICmpInst::ICMP_SGE:
8551 // (float)int >= -4.4 --> int >= -4
8552 // (float)int >= 4.4 --> int > 4
8553 if (!RHS->isNegative())
8554 Pred = ICmpInst::ICMP_SGT;
8555 break;
8556 }
8557 }
8558 }
8559
8560 // Lower this FP comparison into an appropriate integer version of the
8561 // comparison.
8562 return new ICmpInst(Pred, LHSI->getOperand(0),
8563 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8564}
8565
8566/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8567/// where all true/false values are constants that allow the compare to be
8568/// constant-folded for every combination of C1 and C2.
8569/// We compute a 4-entry truth table and use createLogicFromTable to
8570/// synthesize a boolean expression of C1 and C2.
8572 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8573 Value *C1, *C2;
8574 Constant *TV1, *FV1, *TV2, *FV2;
8575
8576 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8577 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8578 return nullptr;
8579
8580 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8581 return nullptr;
8582
8583 unsigned Pred = I.getPredicate();
8584 const DataLayout &DL = I.getDataLayout();
8585
8586 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8587 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8588 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8589 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8590
8591 if (!Res00 || !Res01 || !Res10 || !Res11)
8592 return nullptr;
8593
8594 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8595 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8596 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8597 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8598 return nullptr;
8599
8600 std::bitset<4> Table;
8601 if (!Res00->isNullValue())
8602 Table.set(0);
8603 if (!Res01->isNullValue())
8604 Table.set(1);
8605 if (!Res10->isNullValue())
8606 Table.set(2);
8607 if (!Res11->isNullValue())
8608 Table.set(3);
8609
8610 Value *Res = createLogicFromTable(Table, C1, C2, Builder,
8611 Op0->hasOneUse() && Op1->hasOneUse());
8612 if (!Res)
8613 return nullptr;
8614 return replaceInstUsesWith(I, Res);
8615}
8616
8617/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8619 Constant *RHSC) {
8620 // When C is not 0.0 and infinities are not allowed:
8621 // (C / X) < 0.0 is a sign-bit test of X
8622 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8623 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8624 //
8625 // Proof:
8626 // Multiply (C / X) < 0.0 by X * X / C.
8627 // - X is non zero, if it is the flag 'ninf' is violated.
8628 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8629 // the predicate. C is also non zero by definition.
8630 //
8631 // Thus X * X / C is non zero and the transformation is valid. [qed]
8632
8633 FCmpInst::Predicate Pred = I.getPredicate();
8634
8635 // Check that predicates are valid.
8636 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8637 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8638 return nullptr;
8639
8640 // Check that RHS operand is zero.
8641 if (!match(RHSC, m_AnyZeroFP()))
8642 return nullptr;
8643
8644 // Check fastmath flags ('ninf').
8645 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8646 return nullptr;
8647
8648 // Check the properties of the dividend. It must not be zero to avoid a
8649 // division by zero (see Proof).
8650 const APFloat *C;
8651 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8652 return nullptr;
8653
8654 if (C->isZero())
8655 return nullptr;
8656
8657 // Get swapped predicate if necessary.
8658 if (C->isNegative())
8659 Pred = I.getSwappedPredicate();
8660
8661 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8662}
8663
8664// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8665// Patterns include:
8666// fptrunc(x) < C --> x < ext(C)
8667// fptrunc(x) <= C --> x <= ext(C)
8668// fptrunc(x) > C --> x > ext(C)
8669// fptrunc(x) >= C --> x >= ext(C)
8670// fptrunc(x) ord/uno C --> x ord/uno 0
8671// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8672// due to precision loss.
8674 const Constant &C) {
8675 FCmpInst::Predicate Pred = I.getPredicate();
8676 Type *DestType = FPTrunc.getOperand(0)->getType();
8677
8678 const APFloat *CValue;
8679 // TODO: support vec
8680 if (!match(&C, m_APFloat(CValue)))
8681 return nullptr;
8682
8683 // Handle ord/uno
8684 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8685 assert(!CValue->isNaN() &&
8686 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8687 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8688 ConstantFP::getZero(DestType), "", &I);
8689 }
8690
8691 // Handle <, >, <=, >=
8692 bool RoundDown = false;
8693
8694 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8695 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8696 RoundDown = true;
8697 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8698 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8699 RoundDown = false;
8700 else
8701 return nullptr;
8702
8703 if (CValue->isNaN() || CValue->isInfinity())
8704 return nullptr;
8705
8706 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8707 bool LosesInfo;
8708 APFloat Dest = Src;
8709 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8710 return Dest;
8711 };
8712
8713 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8714 APFloat NextValue = Value;
8715 NextValue.next(RoundDown);
8716 return NextValue;
8717 };
8718
8719 APFloat NextCValue = NextValue(*CValue, RoundDown);
8720
8721 const fltSemantics &DestFltSema =
8722 DestType->getScalarType()->getFltSemantics();
8723
8724 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8725 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8726
8727 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8728 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8729 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8730 // value of 'CValue'.
8731 if (NextCValue.isInfinity()) {
8732 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8733 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8734
8735 ExtNextCValue = ExtCValue + Bias;
8736 }
8737
8738 APFloat ExtMidValue =
8739 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8740
8741 const fltSemantics &SrcFltSema =
8742 C.getType()->getScalarType()->getFltSemantics();
8743
8744 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8745 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8746 if (MidValue != *CValue)
8747 ExtMidValue.next(!RoundDown);
8748
8749 // Check whether 'ExtMidValue' is a valid result since the assumption on
8750 // imaged 'NextCValue' might not hold for new float types.
8751 // ppc_fp128 can't pass here when converting from max float because of
8752 // APFloat implementation.
8753 if (NextCValue.isInfinity()) {
8754 // ExtMidValue --- narrowed ---> Finite
8755 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8756 return nullptr;
8757
8758 // NextExtMidValue --- narrowed ---> Infinity
8759 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8760 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8761 return nullptr;
8762 }
8763
8764 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8765 ConstantFP::get(DestType, ExtMidValue), "", &I);
8766}
8767
8768/// Optimize fabs(X) compared with zero.
8770 Value *X;
8771 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8772 return nullptr;
8773
8774 const APFloat *C;
8775 if (!match(I.getOperand(1), m_APFloat(C)))
8776 return nullptr;
8777
8778 if (!C->isPosZero()) {
8779 if (!C->isSmallestNormalized())
8780 return nullptr;
8781
8782 const Function *F = I.getFunction();
8783 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8784 if (Mode.Input == DenormalMode::PreserveSign ||
8786
8787 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8788 Constant *Zero = ConstantFP::getZero(X->getType());
8789 return new FCmpInst(P, X, Zero, "", I);
8790 };
8791
8792 switch (I.getPredicate()) {
8793 case FCmpInst::FCMP_OLT:
8794 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8795 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8796 case FCmpInst::FCMP_UGE:
8797 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8798 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8799 case FCmpInst::FCMP_OGE:
8800 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8801 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8802 case FCmpInst::FCMP_ULT:
8803 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8804 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8805 default:
8806 break;
8807 }
8808 }
8809
8810 return nullptr;
8811 }
8812
8813 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8814 I->setPredicate(P);
8815 return IC.replaceOperand(*I, 0, X);
8816 };
8817
8818 switch (I.getPredicate()) {
8819 case FCmpInst::FCMP_UGE:
8820 case FCmpInst::FCMP_OLT:
8821 // fabs(X) >= 0.0 --> true
8822 // fabs(X) < 0.0 --> false
8823 llvm_unreachable("fcmp should have simplified");
8824
8825 case FCmpInst::FCMP_OGT:
8826 // fabs(X) > 0.0 --> X != 0.0
8827 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8828
8829 case FCmpInst::FCMP_UGT:
8830 // fabs(X) u> 0.0 --> X u!= 0.0
8831 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8832
8833 case FCmpInst::FCMP_OLE:
8834 // fabs(X) <= 0.0 --> X == 0.0
8835 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8836
8837 case FCmpInst::FCMP_ULE:
8838 // fabs(X) u<= 0.0 --> X u== 0.0
8839 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8840
8841 case FCmpInst::FCMP_OGE:
8842 // fabs(X) >= 0.0 --> !isnan(X)
8843 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8844 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8845
8846 case FCmpInst::FCMP_ULT:
8847 // fabs(X) u< 0.0 --> isnan(X)
8848 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8849 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8850
8851 case FCmpInst::FCMP_OEQ:
8852 case FCmpInst::FCMP_UEQ:
8853 case FCmpInst::FCMP_ONE:
8854 case FCmpInst::FCMP_UNE:
8855 case FCmpInst::FCMP_ORD:
8856 case FCmpInst::FCMP_UNO:
8857 // Look through the fabs() because it doesn't change anything but the sign.
8858 // fabs(X) == 0.0 --> X == 0.0,
8859 // fabs(X) != 0.0 --> X != 0.0
8860 // isnan(fabs(X)) --> isnan(X)
8861 // !isnan(fabs(X) --> !isnan(X)
8862 return replacePredAndOp0(&I, I.getPredicate(), X);
8863
8864 default:
8865 return nullptr;
8866 }
8867}
8868
8869/// Optimize sqrt(X) compared with zero.
8871 Value *X;
8872 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8873 return nullptr;
8874
8875 if (!match(I.getOperand(1), m_PosZeroFP()))
8876 return nullptr;
8877
8878 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8879 I.setPredicate(P);
8880 return IC.replaceOperand(I, 0, X);
8881 };
8882
8883 // Clear ninf flag if sqrt doesn't have it.
8884 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8885 I.setHasNoInfs(false);
8886
8887 switch (I.getPredicate()) {
8888 case FCmpInst::FCMP_OLT:
8889 case FCmpInst::FCMP_UGE:
8890 // sqrt(X) < 0.0 --> false
8891 // sqrt(X) u>= 0.0 --> true
8892 llvm_unreachable("fcmp should have simplified");
8893 case FCmpInst::FCMP_ULT:
8894 case FCmpInst::FCMP_ULE:
8895 case FCmpInst::FCMP_OGT:
8896 case FCmpInst::FCMP_OGE:
8897 case FCmpInst::FCMP_OEQ:
8898 case FCmpInst::FCMP_UNE:
8899 // sqrt(X) u< 0.0 --> X u< 0.0
8900 // sqrt(X) u<= 0.0 --> X u<= 0.0
8901 // sqrt(X) > 0.0 --> X > 0.0
8902 // sqrt(X) >= 0.0 --> X >= 0.0
8903 // sqrt(X) == 0.0 --> X == 0.0
8904 // sqrt(X) u!= 0.0 --> X u!= 0.0
8905 return IC.replaceOperand(I, 0, X);
8906
8907 case FCmpInst::FCMP_OLE:
8908 // sqrt(X) <= 0.0 --> X == 0.0
8909 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8910 case FCmpInst::FCMP_UGT:
8911 // sqrt(X) u> 0.0 --> X u!= 0.0
8912 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8913 case FCmpInst::FCMP_UEQ:
8914 // sqrt(X) u== 0.0 --> X u<= 0.0
8915 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8916 case FCmpInst::FCMP_ONE:
8917 // sqrt(X) != 0.0 --> X > 0.0
8918 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8919 case FCmpInst::FCMP_ORD:
8920 // !isnan(sqrt(X)) --> X >= 0.0
8921 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8922 case FCmpInst::FCMP_UNO:
8923 // isnan(sqrt(X)) --> X u< 0.0
8924 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8925 default:
8926 llvm_unreachable("Unexpected predicate!");
8927 }
8928}
8929
8931 CmpInst::Predicate Pred = I.getPredicate();
8932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8933
8934 // Canonicalize fneg as Op1.
8935 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
8936 std::swap(Op0, Op1);
8937 Pred = I.getSwappedPredicate();
8938 }
8939
8940 if (!match(Op1, m_FNeg(m_Specific(Op0))))
8941 return nullptr;
8942
8943 // Replace the negated operand with 0.0:
8944 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8945 Constant *Zero = ConstantFP::getZero(Op0->getType());
8946 return new FCmpInst(Pred, Op0, Zero, "", &I);
8947}
8948
8950 Constant *RHSC, InstCombinerImpl &CI) {
8951 const CmpInst::Predicate Pred = I.getPredicate();
8952 Value *X = LHSI->getOperand(0);
8953 Value *Y = LHSI->getOperand(1);
8954 switch (Pred) {
8955 default:
8956 break;
8957 case FCmpInst::FCMP_UGT:
8958 case FCmpInst::FCMP_ULT:
8959 case FCmpInst::FCMP_UNE:
8960 case FCmpInst::FCMP_OEQ:
8961 case FCmpInst::FCMP_OGE:
8962 case FCmpInst::FCMP_OLE:
8963 // The optimization is not valid if X and Y are infinities of the same
8964 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
8965 // flag then we can assume we do not have that case. Otherwise we might be
8966 // able to prove that either X or Y is not infinity.
8967 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
8971 break;
8972
8973 [[fallthrough]];
8974 case FCmpInst::FCMP_OGT:
8975 case FCmpInst::FCMP_OLT:
8976 case FCmpInst::FCMP_ONE:
8977 case FCmpInst::FCMP_UEQ:
8978 case FCmpInst::FCMP_UGE:
8979 case FCmpInst::FCMP_ULE:
8980 // fcmp pred (x - y), 0 --> fcmp pred x, y
8981 if (match(RHSC, m_AnyZeroFP()) &&
8982 I.getFunction()->getDenormalMode(
8983 LHSI->getType()->getScalarType()->getFltSemantics()) ==
8985 CI.replaceOperand(I, 0, X);
8986 CI.replaceOperand(I, 1, Y);
8987 I.setHasNoInfs(LHSI->hasNoInfs());
8988 if (LHSI->hasNoNaNs())
8989 I.setHasNoNaNs(true);
8990 return &I;
8991 }
8992 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
8993 // where C and Y can't be arbitrary floating-point values.
8994 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
8995 // to `1.0f`, so the source compare is false while the rewritten compare is
8996 // true.
8997 // We need to make sure (C - Y) never rounds back to C
8998 const APFloat *C;
8999 Value *IntSrc;
9000 if (match(RHSC, m_APFloat(C)) &&
9001 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
9002 C->isNormal()) {
9003 // Requirements on C and Y:
9004 // 1. C is finite, nonzero, normal.
9005 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9006 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9007 // must be integer-valued with an absolute value of at least 1;
9008 // as long as the step size near C does not exceed 1,
9009 // C - Y cannot be rounded back to C when Y != 0.
9010 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9011 // 0, 0` for ordered and unordered predicates as long as C is finite and
9012 // nonzero.
9013 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9014 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
9015 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
9016 I.setPredicate(I.getSwappedPredicate());
9017 CI.replaceOperand(I, 0, Y);
9018 CI.replaceOperand(I, 1, ZeroC);
9019 return &I;
9020 }
9021 }
9022 break;
9023 }
9024
9025 return nullptr;
9026}
9027
9028/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9029/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9030/// float when the uitofp casts are exact and C is in the valid range.
9031///
9032/// Since exact uitofp means distinct integers map to distinct floats, the only
9033/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9034/// There are no values in the open interval (0, 1), so:
9035/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9036// fabs(..) >= C where C >= 1.0 -> a != b
9037///
9038/// The same logic applies to sitofp.
9040 Value *FAbsArg;
9041 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
9042 return nullptr;
9043
9044 const APFloat *C;
9045 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
9046 return nullptr;
9047
9048 FCmpInst::Predicate Pred = I.getPredicate();
9049 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9050 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9051 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9052 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9053 if (!IsStrictLt && !IsStrictGt && !IsGe)
9054 return nullptr;
9055
9056 APFloat One = APFloat::getOne(C->getSemantics());
9057 APFloat::cmpResult Cmp = C->compare(One);
9058
9059 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9060 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9061 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9062 return nullptr;
9063 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9064 return nullptr;
9065 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9066 return nullptr;
9067 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9068 return nullptr;
9069
9070 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9071 Value *A, *B;
9072 bool IsSigned;
9073 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
9074 IsSigned = false;
9075 } else if (match(FAbsArg,
9077 IsSigned = true;
9078 } else {
9079 return nullptr;
9080 }
9081
9082 // A and B must have the same integer type
9083 if (A->getType() != B->getType())
9084 return nullptr;
9085
9086 Type *FPTy = FAbsArg->getType();
9087 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
9088 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
9089 return nullptr;
9090 ICmpInst::Predicate ResultPred =
9091 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9092 return new ICmpInst(ResultPred, A, B);
9093}
9094
9096 InstCombinerImpl &IC) {
9097 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9098 Type *OpType = LHS->getType();
9099 CmpInst::Predicate Pred = I.getPredicate();
9100
9103
9104 if (!FloorX && !CeilX) {
9107 std::swap(LHS, RHS);
9108 Pred = I.getSwappedPredicate();
9109 }
9110 }
9111
9112 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9113 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9114 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9115 // where pred is oeq, one, ord, ueq, une, uno.
9116 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
9117 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9118 }
9119
9120 switch (Pred) {
9121 case FCmpInst::FCMP_OLE:
9122 // fcmp ole floor(x), x => fcmp ord x, 0
9123 if (FloorX)
9125 "", &I);
9126 break;
9127 case FCmpInst::FCMP_OGT:
9128 // fcmp ogt floor(x), x => false
9129 if (FloorX)
9130 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9131 break;
9132 case FCmpInst::FCMP_OGE:
9133 // fcmp oge ceil(x), x => fcmp ord x, 0
9134 if (CeilX)
9136 "", &I);
9137 break;
9138 case FCmpInst::FCMP_OLT:
9139 // fcmp olt ceil(x), x => false
9140 if (CeilX)
9141 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9142 break;
9143 case FCmpInst::FCMP_ULE:
9144 // fcmp ule floor(x), x => true
9145 if (FloorX)
9146 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9147 break;
9148 case FCmpInst::FCMP_UGT:
9149 // fcmp ugt floor(x), x => fcmp uno x, 0
9150 if (FloorX)
9152 "", &I);
9153 break;
9154 case FCmpInst::FCMP_UGE:
9155 // fcmp uge ceil(x), x => true
9156 if (CeilX)
9157 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9158 break;
9159 case FCmpInst::FCMP_ULT:
9160 // fcmp ult ceil(x), x => fcmp uno x, 0
9161 if (CeilX)
9163 "", &I);
9164 break;
9165 default:
9166 break;
9167 }
9168
9169 return nullptr;
9170}
9171
9172/// Returns true if a select that implements a min/max is redundant and
9173/// select result can be replaced with its non-constant operand, e.g.,
9174/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9175/// where C is the FP constant equal to the minimum integer value
9176/// representable by A.
9178 Value *B) {
9179 const APFloat *APF;
9180 if (!match(B, m_APFloat(APF)))
9181 return false;
9182
9183 auto *I = dyn_cast<Instruction>(A);
9184 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9185 I->getOpcode() == Instruction::UIToFP))
9186 return false;
9187
9188 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9189 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9190 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9191 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9192 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9193 APSInt ConvertedInt(BitWidth, IsUnsigned);
9194 bool IsExact;
9196 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9197 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9198}
9199
9201 bool Changed = false;
9202
9203 /// Orders the operands of the compare so that they are listed from most
9204 /// complex to least complex. This puts constants before unary operators,
9205 /// before binary operators.
9206 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9207 I.swapOperands();
9208 Changed = true;
9209 }
9210
9211 const CmpInst::Predicate Pred = I.getPredicate();
9212 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9213 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9214 SQ.getWithInstruction(&I)))
9215 return replaceInstUsesWith(I, V);
9216
9217 // Simplify 'fcmp pred X, X'
9218 Type *OpType = Op0->getType();
9219 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9220 if (Op0 == Op1) {
9221 switch (Pred) {
9222 default:
9223 break;
9224 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9225 case FCmpInst::FCMP_ULT: // True if unordered or less than
9226 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9227 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9228 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9229 I.setPredicate(FCmpInst::FCMP_UNO);
9230 I.setOperand(1, Constant::getNullValue(OpType));
9231 return &I;
9232
9233 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9234 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9235 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9236 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9237 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9238 I.setPredicate(FCmpInst::FCMP_ORD);
9239 I.setOperand(1, Constant::getNullValue(OpType));
9240 return &I;
9241 }
9242 }
9243
9244 if (I.isCommutative()) {
9245 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9246 replaceOperand(I, 0, Pair->first);
9247 replaceOperand(I, 1, Pair->second);
9248 return &I;
9249 }
9250 }
9251
9252 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9253 // then canonicalize the operand to 0.0.
9254 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9255 if (!match(Op0, m_PosZeroFP()) &&
9256 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9257 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9258
9259 if (!match(Op1, m_PosZeroFP()) &&
9260 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9261 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9262 }
9263
9264 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9265 Value *X, *Y;
9266 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
9267 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9268
9270 return R;
9271
9272 // Test if the FCmpInst instruction is used exclusively by a select as
9273 // part of a minimum or maximum operation. If so, refrain from doing
9274 // any other folding. This helps out other analyses which understand
9275 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9276 // and CodeGen. And in this case, at least one of the comparison
9277 // operands has at least one user besides the compare (the select),
9278 // which would often largely negate the benefit of folding anyway.
9279 if (I.hasOneUse())
9280 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9281 Value *A, *B;
9283 bool IsRedundantMinMaxClamp =
9284 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9286 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9287 return nullptr;
9288 }
9289
9290 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9291 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9292 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9293 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9294
9295 // Canonicalize:
9296 // fcmp olt X, +inf -> fcmp one X, +inf
9297 // fcmp ole X, +inf -> fcmp ord X, 0
9298 // fcmp ogt X, +inf -> false
9299 // fcmp oge X, +inf -> fcmp oeq X, +inf
9300 // fcmp ult X, +inf -> fcmp une X, +inf
9301 // fcmp ule X, +inf -> true
9302 // fcmp ugt X, +inf -> fcmp uno X, 0
9303 // fcmp uge X, +inf -> fcmp ueq X, +inf
9304 // fcmp olt X, -inf -> false
9305 // fcmp ole X, -inf -> fcmp oeq X, -inf
9306 // fcmp ogt X, -inf -> fcmp one X, -inf
9307 // fcmp oge X, -inf -> fcmp ord X, 0
9308 // fcmp ult X, -inf -> fcmp uno X, 0
9309 // fcmp ule X, -inf -> fcmp ueq X, -inf
9310 // fcmp ugt X, -inf -> fcmp une X, -inf
9311 // fcmp uge X, -inf -> true
9312 const APFloat *C;
9313 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9314 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9315 default:
9316 break;
9317 case FCmpInst::FCMP_ORD:
9318 case FCmpInst::FCMP_UNO:
9321 case FCmpInst::FCMP_OGT:
9322 case FCmpInst::FCMP_ULE:
9323 llvm_unreachable("Should be simplified by InstSimplify");
9324 case FCmpInst::FCMP_OLT:
9325 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9326 case FCmpInst::FCMP_OLE:
9327 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9328 "", &I);
9329 case FCmpInst::FCMP_OGE:
9330 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9331 case FCmpInst::FCMP_ULT:
9332 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9333 case FCmpInst::FCMP_UGT:
9334 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9335 "", &I);
9336 case FCmpInst::FCMP_UGE:
9337 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9338 }
9339 }
9340
9341 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9342 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9343 if (match(Op1, m_PosZeroFP()) &&
9345 X->getType()->isIntOrIntVectorTy() &&
9346 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9347 .inputsMayBeZero()) {
9349 if (Pred == FCmpInst::FCMP_OEQ)
9350 IntPred = ICmpInst::ICMP_EQ;
9351 else if (Pred == FCmpInst::FCMP_UNE)
9352 IntPred = ICmpInst::ICMP_NE;
9353
9354 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9355 Type *IntTy = X->getType();
9356 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9357 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9358 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9359 }
9360 }
9361
9362 // Handle fcmp with instruction LHS and constant RHS.
9363 Instruction *LHSI;
9364 Constant *RHSC;
9365 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9366 switch (LHSI->getOpcode()) {
9367 case Instruction::Select:
9368 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9369 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9371 return replaceOperand(I, 0, X);
9373 return NV;
9374 break;
9375 case Instruction::FSub:
9376 if (LHSI->hasOneUse())
9377 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9378 return NV;
9379 break;
9380 case Instruction::PHI:
9381 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9382 return NV;
9383 break;
9384 case Instruction::SIToFP:
9385 case Instruction::UIToFP:
9386 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9387 return NV;
9388 break;
9389 case Instruction::FDiv:
9390 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9391 return NV;
9392 break;
9393 case Instruction::Load:
9394 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
9395 if (Instruction *Res =
9397 return Res;
9398 break;
9399 case Instruction::FPTrunc:
9400 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9401 return NV;
9402 break;
9403 }
9404 }
9405
9406 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9407 return R;
9408
9409 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9410 return R;
9411
9412 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9413 return R;
9414
9415 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9416 return R;
9417
9419 return R;
9420
9421 if (match(Op0, m_FNeg(m_Value(X)))) {
9422 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9423 Constant *C;
9424 if (match(Op1, m_Constant(C)))
9425 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9426 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9427 }
9428
9429 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9430 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9431 return new FCmpInst(Pred, X, Op1, "", &I);
9432
9433 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9434 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9435 return new FCmpInst(Pred, Op0, Y, "", &I);
9436
9437 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9438 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9439 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9440 X->getType() == Y->getType())
9441 return new FCmpInst(Pred, X, Y, "", &I);
9442
9443 if (match(Op0, m_FPExt(m_Value(X)))) {
9444 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9445 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9446 return new FCmpInst(Pred, X, Y, "", &I);
9447
9448 const APFloat *C;
9449 if (match(Op1, m_APFloat(C))) {
9450 const fltSemantics &FPSem =
9451 X->getType()->getScalarType()->getFltSemantics();
9452 bool Lossy;
9453 APFloat TruncC = *C;
9455
9456 if (Lossy) {
9457 // X can't possibly equal the higher-precision constant, so reduce any
9458 // equality comparison.
9459 // TODO: Other predicates can be handled via getFCmpCode().
9460 switch (Pred) {
9461 case FCmpInst::FCMP_OEQ:
9462 // X is ordered and equal to an impossible constant --> false
9463 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9464 case FCmpInst::FCMP_ONE:
9465 // X is ordered and not equal to an impossible constant --> ordered
9466 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9467 ConstantFP::getZero(X->getType()));
9468 case FCmpInst::FCMP_UEQ:
9469 // X is unordered or equal to an impossible constant --> unordered
9470 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9471 ConstantFP::getZero(X->getType()));
9472 case FCmpInst::FCMP_UNE:
9473 // X is unordered or not equal to an impossible constant --> true
9474 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9475 default:
9476 break;
9477 }
9478 }
9479
9480 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9481 // Avoid lossy conversions and denormals.
9482 // Zero is a special case that's OK to convert.
9483 APFloat Fabs = TruncC;
9484 Fabs.clearSign();
9485 if (!Lossy &&
9486 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9487 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9488 return new FCmpInst(Pred, X, NewC, "", &I);
9489 }
9490 }
9491 }
9492
9493 // Convert a sign-bit test of an FP value into a cast and integer compare.
9494 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9495 // TODO: Handle non-zero compare constants.
9496 // TODO: Handle other predicates.
9498 m_Value(X)))) &&
9499 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9500 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9501 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9502 IntType = VectorType::get(IntType, VecTy->getElementCount());
9503
9504 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9505 if (Pred == FCmpInst::FCMP_OLT) {
9506 Value *IntX = Builder.CreateBitCast(X, IntType);
9507 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9508 ConstantInt::getNullValue(IntType));
9509 }
9510 }
9511
9512 {
9513 Value *CanonLHS = nullptr;
9515 // (canonicalize(x) == x) => (x == x)
9516 if (CanonLHS == Op1)
9517 return new FCmpInst(Pred, Op1, Op1, "", &I);
9518
9519 Value *CanonRHS = nullptr;
9521 // (x == canonicalize(x)) => (x == x)
9522 if (CanonRHS == Op0)
9523 return new FCmpInst(Pred, Op0, Op0, "", &I);
9524
9525 // (canonicalize(x) == canonicalize(y)) => (x == y)
9526 if (CanonLHS && CanonRHS)
9527 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9528 }
9529
9530 if (I.getType()->isVectorTy())
9531 if (Instruction *Res = foldVectorCmp(I, Builder))
9532 return Res;
9533
9534 return Changed ? &I : nullptr;
9535}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define Check(C,...)
Hexagon Common GEP
static Instruction * foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
static Instruction * foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize fabs(X) compared with zero.
static void collectOffsetOp(Value *V, SmallVectorImpl< OffsetOp > &Offsets, bool AllowRecursion)
static Value * rewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags NW, const DataLayout &DL, SetVector< Value * > &Explored, InstCombiner &IC)
Returns a re-written value of Start as an indexed GEP using Base as a pointer.
static bool isMinMaxCmpSelectEliminable(SelectPatternFlavor Flavor, Value *A, Value *B)
Returns true if a select that implements a min/max is redundant and select result can be replaced wit...
static Instruction * foldICmpEqualityWithOffset(ICmpInst &I, InstCombiner::BuilderTy &Builder, const SimplifyQuery &SQ)
Offset both sides of an equality icmp to see if we can save some instructions: icmp eq/ne X,...
static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1+In2, returning true if the result overflowed for this type.
static Instruction * foldICmpOfVectorReduce(ICmpInst &I, const DataLayout &DL, IRBuilderBase &Builder)
static Instruction * foldICmpAndXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * foldVectorCmp(CmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q, unsigned Depth=0)
static Value * createLogicFromTable(const std::bitset< 4 > &Table, Value *Op0, Value *Op1, IRBuilderBase &Builder, bool HasOneUse)
static Instruction * foldICmpOfUAddOv(ICmpInst &I)
static bool isChainSelectCmpBranch(const SelectInst *SI)
Return true when the instruction sequence within a block is select-cmp-br.
static Instruction * foldICmpInvariantGroup(ICmpInst &I)
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static Instruction * foldReductionIdiom(ICmpInst &I, InstCombiner::BuilderTy &Builder, const DataLayout &DL)
This function folds patterns produced by lowering of reduce idioms, such as llvm.vector....
static Instruction * canonicalizeICmpBool(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Integer compare with boolean values can always be turned into bitwise ops.
static Instruction * foldFCmpFSubIntoFCmp(FCmpInst &I, Instruction *LHSI, Constant *RHSC, InstCombinerImpl &CI)
static Value * foldICmpOrXorSubChain(ICmpInst &Cmp, BinaryOperator *Or, InstCombiner::BuilderTy &Builder)
Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
static bool hasBranchUse(ICmpInst &I)
Given an icmp instruction, return true if any use of this comparison is a branch on sign bit comparis...
static Value * foldICmpWithLowBitMaskedVal(CmpPredicate Pred, Value *Op0, Value *Op1, const SimplifyQuery &Q, InstCombiner &IC)
Some comparisons can be simplified.
static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth)
When performing a comparison against a constant, it is possible that not all the bits in the LHS are ...
static Instruction * foldICmpShlLHSC(ICmpInst &Cmp, Instruction *Shl, const APInt &C)
Fold icmp (shl nuw C2, Y), C.
static Instruction * foldFCmpWithFloorAndCeil(FCmpInst &I, InstCombinerImpl &IC)
static Instruction * foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
static Instruction * processUZExtIdiom(ICmpInst &I, Value *Val, const APInt *OtherVal, InstCombinerImpl &IC)
Recognize and process idiom involving test for unsigned overflow.
static Instruction * foldICmpOfCmpIntrinsicWithConstant(CmpPredicate Pred, IntrinsicInst *I, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldSqrtWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC)
Optimize sqrt(X) compared with zero.
static Instruction * foldFCmpFNegCommonOp(FCmpInst &I)
static Instruction * foldICmpWithHighBitMask(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
static ICmpInst * canonicalizeCmpWithConstant(ICmpInst &I)
If we have an icmp le or icmp ge instruction with a constant operand, turn it into the appropriate ic...
static Instruction * foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp, InstCombiner::BuilderTy &Builder)
Fold an icmp with LLVM intrinsics.
static Instruction * foldICmpUSubSatOrUAddSatWithConstant(CmpPredicate Pred, SaturatingInst *II, const APInt &C, InstCombiner::BuilderTy &Builder)
static Instruction * foldICmpPow2Test(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2, bool IsSigned=false)
Compute Result = In1-In2, returning true if the result overflowed for this type.
static bool canRewriteGEPAsOffset(Value *Start, Value *Base, GEPNoWrapFlags &NW, const DataLayout &DL, SetVector< Value * > &Explored)
Returns true if we can rewrite Start as a GEP with pointer Base and some integer offset.
static Instruction * foldFCmpFpTrunc(FCmpInst &I, const Instruction &FPTrunc, const Constant &C)
static Instruction * foldICmpXNegX(ICmpInst &I, InstCombiner::BuilderTy &Builder)
static Instruction * processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B, ConstantInt *CI2, ConstantInt *CI1, InstCombinerImpl &IC)
The caller has matched a pattern of the form: I = icmp ugt (add (add A, B), CI2), CI1 If this is of t...
static Value * foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ, InstCombiner::BuilderTy &Builder)
static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C)
Returns true if the exploded icmp can be expressed as a signed comparison to zero and updates the pre...
static Instruction * transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, const DataLayout &DL, InstCombiner &IC)
Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
static Instruction * foldCtpopPow2Test(ICmpInst &I, IntrinsicInst *CtpopLhs, const APInt &CRhs, InstCombiner::BuilderTy &Builder, const SimplifyQuery &Q)
static Instruction * foldFCmpFAbsFSubIntToFP(FCmpInst &I, InstCombinerImpl &IC)
Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b where 'pred' is olt, ult, ogt,...
static void setInsertionPoint(IRBuilder<> &Builder, Value *V, bool Before=true)
static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned)
static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q)
Return true if X is a multiple of C.
static Value * foldICmpWithTruncSignExtendedVal(ICmpInst &I, InstCombiner::BuilderTy &Builder)
Some comparisons can be simplified.
static Instruction * foldICmpOrXX(ICmpInst &I, const SimplifyQuery &Q, InstCombinerImpl &IC)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:322
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6010
void clearSign()
Definition APFloat.h:1402
bool isNaN() const
Definition APFloat.h:1581
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1192
bool isZero() const
Definition APFloat.h:1579
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1262
APInt bitcastToAPInt() const
Definition APFloat.h:1475
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
opStatus next(bool nextDown)
Definition APFloat.h:1358
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5939
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1352
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:446
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:226
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
unsigned ceilLogBase2() const
Definition APInt.h:1785
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1986
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:463
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1084
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1489
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1473
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1636
unsigned logBase2() const
Definition APInt.h:1782
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:472
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:402
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1677
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition APSInt.h:310
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition APSInt.h:302
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
LLVM_ABI bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
LLVM_ABI ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:68
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
iterator end()
Definition DenseMap.h:141
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:214
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This instruction compares its operands according to the predicate given to the constructor.
static bool isCommutative(Predicate Pred)
static bool isEquality(Predicate Pred)
Represents flags for the getelementptr instruction/expression.
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
Definition Operator.h:390
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:86
Value * getPointerOperand()
Definition Operator.h:417
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
Definition Operator.h:464
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1580
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2502
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1602
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:492
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2910
Instruction * foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr, const APInt &C)
Fold icmp ({al}shr X, Y), C.
Instruction * foldICmpWithZextOrSext(ICmpInst &ICmp)
Instruction * foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select, ConstantInt *C)
Instruction * foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Instruction * foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
Instruction * foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, const APInt &C)
Fold icmp (or X, Y), C.
Instruction * foldICmpTruncWithTruncOrExt(ICmpInst &Cmp, const SimplifyQuery &Q)
Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
Instruction * foldSignBitTest(ICmpInst &I)
Fold equality-comparison between zero and any (maybe truncated) right-shift by one-less-than-bitwidth...
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi, bool isSigned, bool Inside)
Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise (V < Lo || V >= Hi).
Instruction * foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ)
Try to fold icmp (binop), X or icmp X, (binop).
Instruction * foldCmpLoadFromIndexedGlobal(LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst=nullptr)
This is called when we see this pattern: cmp pred (load (gep GV, ...)), cmpcst where GV is a global v...
Instruction * foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub, const APInt &C)
Fold icmp (sub X, Y), C.
Instruction * foldICmpWithClamp(ICmpInst &Cmp, Value *X, MinMaxIntrinsic *Min)
Match and fold patterns like: icmp eq/ne X, min(max(X, Lo), Hi) which represents a range check and ca...
Instruction * foldICmpInstWithConstantNotInt(ICmpInst &Cmp)
Handle icmp with constant (but not simple integer constant) RHS.
bool SimplifyDemandedBits(Instruction *I, unsigned Op, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0) override
This form of SimplifyDemandedBits simplifies the specified instruction operand if possible,...
Instruction * foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (shl AP2, A), AP1)" -> (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
Value * reassociateShiftAmtsOfTwoSameDirectionShifts(BinaryOperator *Sh0, const SimplifyQuery &SQ, bool AnalyzeForSignBitExtraction=false)
Instruction * foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an equality icmp with LLVM intrinsic and constant operand.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Value * foldMultiplicationOverflowCheck(ICmpInst &Cmp)
Fold (-1 u/ x) u< y ((x * y) ?
Instruction * foldICmpWithConstant(ICmpInst &Cmp)
Fold icmp Pred X, C.
CmpInst * canonicalizeICmpPredicate(CmpInst &I)
If we have a comparison with a non-canonical predicate, if we can update all the users,...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * foldICmpWithZero(ICmpInst &Cmp)
Instruction * foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1, ICmpInst &CxtI)
Instruction * foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp equality instruction with binary operator LHS and constant RHS: icmp eq/ne BO,...
Instruction * foldICmpUsingBoolRange(ICmpInst &I)
If one operand of an icmp is effectively a bool (value range of {0,1}), then try to reduce patterns b...
Instruction * foldICmpWithTrunc(ICmpInst &Cmp)
Instruction * foldCmpSelectOfConstants(CmpInst &I)
Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2) where all true/false values are cons...
Instruction * foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II, const APInt &C)
Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS, ConstantInt *&Less, ConstantInt *&Equal, ConstantInt *&Greater)
Match a select chain which produces one of three values based on whether the LHS is less than,...
Instruction * visitFCmpInst(FCmpInst &I)
Instruction * foldICmpUsingKnownBits(ICmpInst &Cmp)
Try to fold the comparison based on range information we can get by checking whether bits are known t...
Instruction * foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div, const APInt &C)
Fold icmp ({su}div X, Y), C.
Instruction * foldIRemByPowerOfTwoToBitTest(ICmpInst &I)
If we have: icmp eq/ne (urem/srem x, y), 0 iff y is a power-of-two, we can replace this with a bit te...
Instruction * foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI, Constant *RHSC)
Fold fcmp ([us]itofp x, cst) if possible.
Instruction * foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Fold icmp (udiv X, Y), C.
Instruction * foldICmpAddOpConst(Value *X, const APInt &C, CmpPredicate Pred)
Fold "icmp pred (X+C), X".
Instruction * foldICmpWithCastOp(ICmpInst &ICmp)
Handle icmp (cast x), (cast or constant).
Instruction * foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc, const APInt &C)
Fold icmp (trunc X), C.
Instruction * foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add, const APInt &C)
Fold icmp (add X, Y), C.
Instruction * foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul, const APInt &C)
Fold icmp (mul X, Y), C.
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Instruction * foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
Fold icmp (xor X, Y), C.
Instruction * foldSelectICmp(CmpPredicate Pred, SelectInst *SI, Value *RHS, const ICmpInst &I)
Instruction * foldICmpInstWithConstantAllowPoison(ICmpInst &Cmp, const APInt &C)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldIsMultipleOfAPowerOfTwo(ICmpInst &Cmp)
Fold icmp eq (num + mask) & ~mask, num to icmp eq (and num, mask), 0 Where mask is a low bit mask.
Instruction * foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1, const APInt &C2)
Fold icmp (and (sh X, Y), C2), C1.
Instruction * foldICmpBinOpWithConstantViaTruthTable(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Instruction * foldICmpInstWithConstant(ICmpInst &Cmp)
Try to fold integer comparisons with a constant operand: icmp Pred X, C where X is some kind of instr...
Instruction * foldICmpXorShiftConst(ICmpInst &Cmp, BinaryOperator *Xor, const APInt &C)
For power-of-2 C: ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1) ((X s>> ShiftC) ^ X) u> (C - 1) -...
Instruction * foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl, const APInt &C)
Fold icmp (shl X, Y), C.
Instruction * foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And, const APInt &C)
Fold icmp (and X, Y), C.
Instruction * foldICmpEquality(ICmpInst &Cmp)
Instruction * foldICmpWithMinMax(Instruction &I, MinMaxIntrinsic *MinMax, Value *Z, CmpPredicate Pred)
Fold icmp Pred min|max(X, Y), Z.
bool dominatesAllUses(const Instruction *DI, const Instruction *UI, const BasicBlock *DB) const
True when DB dominates all uses of DI except UI.
bool foldAllocaCmp(AllocaInst *Alloca)
Instruction * visitICmpInst(ICmpInst &I)
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CxtI) const
Instruction * foldICmpWithDominatingICmp(ICmpInst &Cmp)
Canonicalize icmp instructions based on dominating conditions.
bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp, const unsigned SIOpd)
Try to replace select with select operand SIOpd in SI-ICmp sequence.
Instruction * foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1, const APInt &C2)
Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" -> (icmp eq/ne A, Log2(AP2/AP1)) -> (icmp eq/ne A,...
void freelyInvertAllUsersOf(Value *V, Value *IgnoredUser=nullptr)
Freely adapt every user of V as-if V was changed to !V.
Instruction * foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And, const APInt &C1)
Fold icmp (and X, C2), C1.
Instruction * foldICmpBitCast(ICmpInst &Cmp)
Instruction * foldGEPICmp(GEPOperator *GEPLHS, Value *RHS, CmpPredicate Cond, Instruction &I)
Fold comparisons between a GEP instruction and something else.
The core instruction combiner logic.
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
SimplifyQuery SQ
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CxtI=nullptr, unsigned Depth=0) const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI, bool IsNSW=false) const
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
LLVM_ABI bool canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned, const Instruction *CxtI=nullptr) const
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
static bool isCanonicalPredicate(CmpPredicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
const DataLayout & DL
DomConditionCache DC
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CxtI, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
bool canFreelyInvertAllUsersOf(Instruction *V, Value *IgnoredUser)
Given i1 V, can every user of V be freely adapted if V is changed to !V ?
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CxtI) const
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CxtI) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CxtI=nullptr, unsigned Depth=0)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
bool isArithmeticShift() const
Return true if this is an arithmetic shift right.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents min/max intrinsics.
Value * getLHS() const
Value * getRHS() const
static bool isMin(Intrinsic::ID ID)
Whether the intrinsic is a smin or umin.
static bool isSigned(Intrinsic::ID ID)
Whether the intrinsic is signed or unsigned.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Represents a saturating add/sub intrinsic.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:237
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:155
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2801
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2819
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
cst_pred_ty< is_negated_power2_or_zero > m_NegatedPower2OrZero()
Match a integer or vector negated power-of-2.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
cst_pred_ty< custom_checkfn< APInt > > m_CheckedInt(function_ref< bool(const APInt &)> CheckFn)
Match an integer or vector where CheckFn(ele) for each element is true.
SelectLike_match< CondTy, LTy, RTy > m_SelectLike(const CondTy &C, const LTy &TrueC, const RTy &FalseC)
Matches a value that behaves like a boolean-controlled select, i.e.
cst_pred_ty< is_lowbit_mask_or_zero > m_LowBitMaskOrZero()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastInst_match< OpTy, UIToFPInst > m_UIToFP(const OpTy &Op)
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
cstfp_pred_ty< is_finitenonzero > m_FiniteNonZero()
Match a finite non-zero FP constant.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
CastInst_match< OpTy, SIToFPInst > m_SIToFP(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:830
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:60
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ BinaryOp
One of the operands is a binary op.
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI Value * simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:915
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1701
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2166
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
@ Continue
Definition DWP.h:26
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< DecomposedBitTest > decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate Pred, bool LookThroughTrunc=true, bool AllowNonZeroC=false, bool DecomposeAnd=false)
Decompose an icmp into the form ((X & Mask) pred C) if possible.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define NC
Definition regutils.h:42
Value * materialize(InstCombiner::BuilderTy &Builder) const
static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV, Instruction *MDFrom)
static OffsetResult value(Value *V)
static OffsetResult invalid()
This callback is used in conjunction with PointerMayBeCaptured.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
static constexpr DenormalMode getIEEE()
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
APInt getSignedMaxValue() const
Return the maximal signed value possible given these KnownBits.
Definition KnownBits.h:152
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:136
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:212
GEPNoWrapFlags Flags
Definition Loads.h:217
Matching combinators.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
Capture information for a specific Use.