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
45/// Compute Result = In1+In2, returning true if the result overflowed for this
46/// type.
47static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
48 bool IsSigned = false) {
49 bool Overflow;
50 if (IsSigned)
51 Result = In1.sadd_ov(In2, Overflow);
52 else
53 Result = In1.uadd_ov(In2, Overflow);
54
55 return Overflow;
56}
57
58/// Compute Result = In1-In2, returning true if the result overflowed for this
59/// type.
60static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
61 bool IsSigned = false) {
62 bool Overflow;
63 if (IsSigned)
64 Result = In1.ssub_ov(In2, Overflow);
65 else
66 Result = In1.usub_ov(In2, Overflow);
67
68 return Overflow;
69}
70
71/// Given an icmp instruction, return true if any use of this comparison is a
72/// branch on sign bit comparison.
73static bool hasBranchUse(ICmpInst &I) {
74 for (auto *U : I.users())
75 if (isa<CondBrInst>(U))
76 return true;
77 return false;
78}
79
80/// Returns true if the exploded icmp can be expressed as a signed comparison
81/// to zero and updates the predicate accordingly.
82/// The signedness of the comparison is preserved.
83/// TODO: Refactor with decomposeBitTestICmp()?
84static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
85 if (!ICmpInst::isSigned(Pred))
86 return false;
87
88 if (C.isZero())
89 return ICmpInst::isRelational(Pred);
90
91 if (C.isOne()) {
92 if (Pred == ICmpInst::ICMP_SLT) {
93 Pred = ICmpInst::ICMP_SLE;
94 return true;
95 }
96 } else if (C.isAllOnes()) {
97 if (Pred == ICmpInst::ICMP_SGT) {
98 Pred = ICmpInst::ICMP_SGE;
99 return true;
100 }
101 }
102
103 return false;
104}
105
106/// This is called when we see this pattern:
107/// cmp pred (load (gep GV, ...)), cmpcst
108/// where GV is a global variable with a constant initializer. Try to simplify
109/// this into some simple computation that does not need the load. For example
110/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
111///
112/// If AndCst is non-null, then the loaded value is masked with that constant
113/// before doing the comparison. This handles cases like "A[i]&4 == 0".
114///
115/// We allow multi-use cases in this fold, even though it can increase
116/// instruction count, because it appears to be mostly beneficial in practice.
117/// Even if there are multiple uses, they can often be sunk into the block
118/// guarded by the icmp.
120 LoadInst *LI, GetElementPtrInst *GEP, CmpInst &ICI, ConstantInt *AndCst) {
122 if (LI->isVolatile() || !GV || !GV->isConstant() ||
123 !GV->hasDefinitiveInitializer())
124 return nullptr;
125
126 Type *EltTy = LI->getType();
127 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
128 if (EltSize.isScalable())
129 return nullptr;
130
132 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
133 return nullptr;
134
135 Constant *Init = GV->getInitializer();
136 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
137
138 Value *Idx = Expr.Index;
139 const APInt &Stride = Expr.Scale;
140 const APInt &ConstOffset = Expr.Offset;
141
142 // Allow an additional context offset, but only within the stride.
143 if (!ConstOffset.ult(Stride))
144 return nullptr;
145
146 // Don't handle overlapping loads for now.
147 if (!Stride.uge(EltSize.getFixedValue()))
148 return nullptr;
149
150 // Don't blow up on huge arrays.
151 uint64_t ArrayElementCount =
152 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
153 Stride.getZExtValue());
154 if (ArrayElementCount > CLOpts.maxarray_size)
155 return nullptr;
156
157 enum { Overdefined = -3, Undefined = -2 };
158
159 // Variables for our state machines.
160
161 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
162 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
163 // and 87 is the second (and last) index. FirstTrueElement is -2 when
164 // undefined, otherwise set to the first true element. SecondTrueElement is
165 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
166 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
167
168 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
169 // form "i != 47 & i != 87". Same state transitions as for true elements.
170 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
171
172 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
173 /// define a state machine that triggers for ranges of values that the index
174 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
175 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
176 /// index in the range (inclusive). We use -2 for undefined here because we
177 /// use relative comparisons and don't want 0-1 to match -1.
178 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
179
180 // MagicBitvector - This is a magic bitvector where we set a bit if the
181 // comparison is true for element 'i'. If there are 64 elements or less in
182 // the array, this will fully represent all the comparison results.
183 uint64_t MagicBitvector = 0;
184
185 // Scan the array and see if one of our patterns matches.
186 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
187 APInt Offset = ConstOffset;
188 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
190 if (!Elt)
191 return nullptr;
192
193 // If the element is masked, handle it.
194 if (AndCst) {
195 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
196 if (!Elt)
197 return nullptr;
198 }
199
200 // Find out if the comparison would be true or false for the i'th element.
202 CompareRHS, DL, &TLI);
203 if (!C)
204 return nullptr;
205
206 // If the result is undef for this element, ignore it.
207 if (isa<UndefValue>(C)) {
208 // Extend range state machines to cover this element in case there is an
209 // undef in the middle of the range.
210 if (TrueRangeEnd == (int)i - 1)
211 TrueRangeEnd = i;
212 if (FalseRangeEnd == (int)i - 1)
213 FalseRangeEnd = i;
214 continue;
215 }
216
217 // If we can't compute the result for any of the elements, we have to give
218 // up evaluating the entire conditional.
219 if (!isa<ConstantInt>(C))
220 return nullptr;
221
222 // Otherwise, we know if the comparison is true or false for this element,
223 // update our state machines.
224 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
225
226 // State machine for single/double/range index comparison.
227 if (IsTrueForElt) {
228 // Update the TrueElement state machine.
229 if (FirstTrueElement == Undefined)
230 FirstTrueElement = TrueRangeEnd = i; // First true element.
231 else {
232 // Update double-compare state machine.
233 if (SecondTrueElement == Undefined)
234 SecondTrueElement = i;
235 else
236 SecondTrueElement = Overdefined;
237
238 // Update range state machine.
239 if (TrueRangeEnd == (int)i - 1)
240 TrueRangeEnd = i;
241 else
242 TrueRangeEnd = Overdefined;
243 }
244 } else {
245 // Update the FalseElement state machine.
246 if (FirstFalseElement == Undefined)
247 FirstFalseElement = FalseRangeEnd = i; // First false element.
248 else {
249 // Update double-compare state machine.
250 if (SecondFalseElement == Undefined)
251 SecondFalseElement = i;
252 else
253 SecondFalseElement = Overdefined;
254
255 // Update range state machine.
256 if (FalseRangeEnd == (int)i - 1)
257 FalseRangeEnd = i;
258 else
259 FalseRangeEnd = Overdefined;
260 }
261 }
262
263 // If this element is in range, update our magic bitvector.
264 if (i < 64 && IsTrueForElt)
265 MagicBitvector |= 1ULL << i;
266
267 // If all of our states become overdefined, bail out early. Since the
268 // predicate is expensive, only check it every 8 elements. This is only
269 // really useful for really huge arrays.
270 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
271 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
272 FalseRangeEnd == Overdefined)
273 return nullptr;
274 }
275
276 // Now that we've scanned the entire array, emit our new comparison(s). We
277 // order the state machines in complexity of the generated code.
278
279 // If inbounds keyword is not present, Idx * Stride can overflow.
280 // Let's assume that Stride is 2 and the wanted value is at offset 0.
281 // Then, there are two possible values for Idx to match offset 0:
282 // 0x00..00, 0x80..00.
283 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
284 // comparison is false if Idx was 0x80..00.
285 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
286 auto MaskIdx = [&](Value *Idx) {
287 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
289 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
290 Idx = Builder.CreateAnd(Idx, Mask);
291 }
292 return Idx;
293 };
294
295 // If the comparison is only true for one or two elements, emit direct
296 // comparisons.
297 if (SecondTrueElement != Overdefined) {
298 Idx = MaskIdx(Idx);
299 // None true -> false.
300 if (FirstTrueElement == Undefined)
301 return replaceInstUsesWith(ICI, Builder.getFalse());
302
303 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
304
305 // True for one element -> 'i == 47'.
306 if (SecondTrueElement == Undefined)
307 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
308
309 // True for two elements -> 'i == 47 | i == 72'.
310 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
311 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
312 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
313 return BinaryOperator::CreateOr(C1, C2);
314 }
315
316 // If the comparison is only false for one or two elements, emit direct
317 // comparisons.
318 if (SecondFalseElement != Overdefined) {
319 Idx = MaskIdx(Idx);
320 // None false -> true.
321 if (FirstFalseElement == Undefined)
322 return replaceInstUsesWith(ICI, Builder.getTrue());
323
324 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
325
326 // False for one element -> 'i != 47'.
327 if (SecondFalseElement == Undefined)
328 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
329
330 // False for two elements -> 'i != 47 & i != 72'.
331 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
332 Value *SecondFalseIdx =
333 ConstantInt::get(Idx->getType(), SecondFalseElement);
334 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
335 return BinaryOperator::CreateAnd(C1, C2);
336 }
337
338 // If the comparison can be replaced with a range comparison for the elements
339 // where it is true, emit the range check.
340 if (TrueRangeEnd != Overdefined) {
341 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
342 Idx = MaskIdx(Idx);
343
344 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
345 if (FirstTrueElement) {
346 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
347 Idx = Builder.CreateAdd(Idx, Offs);
348 }
349
350 Value *End =
351 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
352 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
353 }
354
355 // False range check.
356 if (FalseRangeEnd != Overdefined) {
357 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
358 Idx = MaskIdx(Idx);
359 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
360 if (FirstFalseElement) {
361 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
362 Idx = Builder.CreateAdd(Idx, Offs);
363 }
364
365 Value *End =
366 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
367 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
368 }
369
370 // If a magic bitvector captures the entire comparison state
371 // of this load, replace it with computation that does:
372 // ((magic_cst >> i) & 1) != 0
373 {
374 Type *Ty = nullptr;
375
376 // Look for an appropriate type:
377 // - The type of Idx if the magic fits
378 // - The smallest fitting legal type
379 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
380 Ty = Idx->getType();
381 else
382 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
383
384 if (Ty) {
385 Idx = MaskIdx(Idx);
386 Value *V = Builder.CreateIntCast(Idx, Ty, false);
387 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
388 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
389 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
390 }
391 }
392
393 return nullptr;
394}
395
396/// Returns true if we can rewrite Start as a GEP with pointer Base
397/// and some integer offset. The nodes that need to be re-written
398/// for this transformation will be added to Explored.
400 const DataLayout &DL,
401 SetVector<Value *> &Explored) {
402 SmallVector<Value *, 16> WorkList(1, Start);
403 Explored.insert(Base);
404
405 // The following traversal gives us an order which can be used
406 // when doing the final transformation. Since in the final
407 // transformation we create the PHI replacement instructions first,
408 // we don't have to get them in any particular order.
409 //
410 // However, for other instructions we will have to traverse the
411 // operands of an instruction first, which means that we have to
412 // do a post-order traversal.
413 while (!WorkList.empty()) {
415
416 while (!WorkList.empty()) {
417 if (Explored.size() >= 100)
418 return false;
419
420 Value *V = WorkList.back();
421
422 if (Explored.contains(V)) {
423 WorkList.pop_back();
424 continue;
425 }
426
428 // We've found some value that we can't explore which is different from
429 // the base. Therefore we can't do this transformation.
430 return false;
431
432 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
433 // Only allow inbounds GEPs with at most one variable offset.
434 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
435 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
436 return false;
437
438 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
439 if (!Explored.contains(GEP->getOperand(0)))
440 WorkList.push_back(GEP->getOperand(0));
441 }
442
443 if (WorkList.back() == V) {
444 WorkList.pop_back();
445 // We've finished visiting this node, mark it as such.
446 Explored.insert(V);
447 }
448
449 if (auto *PN = dyn_cast<PHINode>(V)) {
450 // We cannot transform PHIs on unsplittable basic blocks.
451 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
452 return false;
453 Explored.insert(PN);
454 PHIs.insert(PN);
455 }
456 }
457
458 // Explore the PHI nodes further.
459 for (auto *PN : PHIs)
460 for (Value *Op : PN->incoming_values())
461 if (!Explored.contains(Op))
462 WorkList.push_back(Op);
463 }
464
465 // Make sure that we can do this. Since we can't insert GEPs in a basic
466 // block before a PHI node, we can't easily do this transformation if
467 // we have PHI node users of transformed instructions.
468 for (Value *Val : Explored) {
469 for (Value *Use : Val->uses()) {
470
471 auto *PHI = dyn_cast<PHINode>(Use);
472 auto *Inst = dyn_cast<Instruction>(Val);
473
474 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
475 !Explored.contains(PHI))
476 continue;
477
478 if (PHI->getParent() == Inst->getParent())
479 return false;
480 }
481 }
482 return true;
483}
484
485// Sets the appropriate insert point on Builder where we can add
486// a replacement Instruction for V (if that is possible).
487static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
488 bool Before = true) {
489 if (auto *PHI = dyn_cast<PHINode>(V)) {
490 BasicBlock *Parent = PHI->getParent();
491 Builder.SetInsertPoint(Parent, Parent->getFirstInsertionPt());
492 return;
493 }
494 if (auto *I = dyn_cast<Instruction>(V)) {
495 if (!Before)
496 I = &*std::next(I->getIterator());
497 Builder.SetInsertPoint(I);
498 return;
499 }
500 if (auto *A = dyn_cast<Argument>(V)) {
501 // Set the insertion point in the entry block.
502 BasicBlock &Entry = A->getParent()->getEntryBlock();
503 Builder.SetInsertPoint(&Entry, Entry.getFirstInsertionPt());
504 return;
505 }
506 // Otherwise, this is a constant and we don't need to set a new
507 // insertion point.
508 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
509}
510
511/// Returns a re-written value of Start as an indexed GEP using Base as a
512/// pointer.
514 const DataLayout &DL,
515 SetVector<Value *> &Explored,
516 InstCombiner &IC) {
517 // Perform all the substitutions. This is a bit tricky because we can
518 // have cycles in our use-def chains.
519 // 1. Create the PHI nodes without any incoming values.
520 // 2. Create all the other values.
521 // 3. Add the edges for the PHI nodes.
522 // 4. Emit GEPs to get the original pointers.
523 // 5. Remove the original instructions.
524 Type *IndexType = IntegerType::get(
525 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
526
528 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
529
530 // Create the new PHI nodes, without adding any incoming values.
531 for (Value *Val : Explored) {
532 if (Val == Base)
533 continue;
534 // Create empty phi nodes. This avoids cyclic dependencies when creating
535 // the remaining instructions.
536 if (auto *PHI = dyn_cast<PHINode>(Val))
537 NewInsts[PHI] =
538 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
539 PHI->getName() + ".idx", PHI->getIterator());
540 }
541 IRBuilder<> Builder(Base->getContext());
542
543 // Create all the other instructions.
544 for (Value *Val : Explored) {
545 if (NewInsts.contains(Val))
546 continue;
547
548 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
549 setInsertionPoint(Builder, GEP);
550 Value *Op = NewInsts[GEP->getOperand(0)];
551 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
553 NewInsts[GEP] = OffsetV;
554 else
555 NewInsts[GEP] = Builder.CreateAdd(
556 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
557 /*NUW=*/NW.hasNoUnsignedWrap(),
558 /*NSW=*/NW.hasNoUnsignedSignedWrap());
559 continue;
560 }
561 if (isa<PHINode>(Val))
562 continue;
563
564 llvm_unreachable("Unexpected instruction type");
565 }
566
567 // Add the incoming values to the PHI nodes.
568 for (Value *Val : Explored) {
569 if (Val == Base)
570 continue;
571 // All the instructions have been created, we can now add edges to the
572 // phi nodes.
573 if (auto *PHI = dyn_cast<PHINode>(Val)) {
574 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
575 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
576 Value *NewIncoming = PHI->getIncomingValue(I);
577
578 auto It = NewInsts.find(NewIncoming);
579 if (It != NewInsts.end())
580 NewIncoming = It->second;
581
582 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
583 }
584 }
585 }
586
587 for (Value *Val : Explored) {
588 if (Val == Base)
589 continue;
590
591 setInsertionPoint(Builder, Val, false);
592 // Create GEP for external users.
593 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
594 Val->getName() + ".ptr", NW);
595 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
596 // Add old instruction to worklist for DCE. We don't directly remove it
597 // here because the original compare is one of the users.
599 }
600
601 return NewInsts[Start];
602}
603
604/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
605/// We can look through PHIs, GEPs and casts in order to determine a common base
606/// between GEPLHS and RHS.
609 const DataLayout &DL,
610 InstCombiner &IC) {
611 // FIXME: Support vector of pointers.
612 if (GEPLHS->getType()->isVectorTy())
613 return nullptr;
614
615 if (!GEPLHS->hasAllConstantIndices())
616 return nullptr;
617
618 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
619 Value *PtrBase =
621 /*AllowNonInbounds*/ false);
622
623 // Bail if we looked through addrspacecast.
624 if (PtrBase->getType() != GEPLHS->getType())
625 return nullptr;
626
627 // The set of nodes that will take part in this transformation.
628 SetVector<Value *> Nodes;
629 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
630 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
631 return nullptr;
632
633 // We know we can re-write this as
634 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
635 // Since we've only looked through inbouds GEPs we know that we
636 // can't have overflow on either side. We can therefore re-write
637 // this as:
638 // OFFSET1 cmp OFFSET2
639 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
640
641 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
642 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
643 // offset. Since Index is the offset of LHS to the base pointer, we will now
644 // compare the offsets instead of comparing the pointers.
646 IC.Builder.getInt(Offset), NewRHS);
647}
648
649/// Fold comparisons between a GEP instruction and something else. At this point
650/// we know that the GEP is on the LHS of the comparison.
653 // Don't transform signed compares of GEPs into index compares. Even if the
654 // GEP is inbounds, the final add of the base pointer can have signed overflow
655 // and would change the result of the icmp.
656 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
657 // the maximum signed value for the pointer type.
659 return nullptr;
660
661 // Look through bitcasts and addrspacecasts. We do not however want to remove
662 // 0 GEPs.
663 if (!isa<GetElementPtrInst>(RHS))
664 RHS = RHS->stripPointerCasts();
665
666 auto CanFold = [Cond](GEPNoWrapFlags NW) {
668 return true;
669
670 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
672 return NW != GEPNoWrapFlags::none();
673 };
674
675 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
676 if (!NW.hasNoUnsignedWrap()) {
677 // Convert signed to unsigned comparison.
678 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
679 }
680
681 auto *I = new ICmpInst(Cond, Op1, Op2);
682 I->setSameSign(NW.hasNoUnsignedSignedWrap());
683 return I;
684 };
685
687 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
688 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
689 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
690 Value *Offset =
691 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
692 return NewICmp(Base.LHSNW, Offset,
693 Constant::getNullValue(Offset->getType()));
694 }
695
696 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
698 !NullPointerIsDefined(I.getFunction(),
699 RHS->getType()->getPointerAddressSpace())) {
700 // For most address spaces, an allocation can't be placed at null, but null
701 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
702 // the only valid inbounds address derived from null, is null itself.
703 // Thus, we have four cases to consider:
704 // 1) Base == nullptr, Offset == 0 -> inbounds, null
705 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
706 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
707 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
708 //
709 // (Note if we're indexing a type of size 0, that simply collapses into one
710 // of the buckets above.)
711 //
712 // In general, we're allowed to make values less poison (i.e. remove
713 // sources of full UB), so in this case, we just select between the two
714 // non-poison cases (1 and 4 above).
715 //
716 // For vectors, we apply the same reasoning on a per-lane basis.
717 auto *Base = GEPLHS->getPointerOperand();
718 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
719 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
720 Base = Builder.CreateVectorSplat(EC, Base);
721 }
722 return new ICmpInst(Cond, Base,
724 cast<Constant>(RHS), Base->getType()));
725 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
726 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
727
728 // If the base pointers are different, but the indices are the same, just
729 // compare the base pointer.
730 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
731 bool IndicesTheSame =
732 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
733 GEPLHS->getPointerOperand()->getType() ==
734 GEPRHS->getPointerOperand()->getType() &&
735 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
736 if (IndicesTheSame)
737 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
738 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
739 IndicesTheSame = false;
740 break;
741 }
742
743 // If all indices are the same, just compare the base pointers.
744 Type *BaseType = GEPLHS->getOperand(0)->getType();
745 if (IndicesTheSame &&
746 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
747 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
748
749 // If we're comparing GEPs with two base pointers that only differ in type
750 // and both GEPs have only constant indices or just one use, then fold
751 // the compare with the adjusted indices.
752 // FIXME: Support vector of pointers.
753 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
754 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
755 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
756 GEPLHS->getOperand(0)->stripPointerCasts() ==
757 GEPRHS->getOperand(0)->stripPointerCasts() &&
758 !GEPLHS->getType()->isVectorTy()) {
759 Value *LOffset = EmitGEPOffset(GEPLHS);
760 Value *ROffset = EmitGEPOffset(GEPRHS);
761
762 // If we looked through an addrspacecast between different sized address
763 // spaces, the LHS and RHS pointers are different sized
764 // integers. Truncate to the smaller one.
765 Type *LHSIndexTy = LOffset->getType();
766 Type *RHSIndexTy = ROffset->getType();
767 if (LHSIndexTy != RHSIndexTy) {
768 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
769 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
770 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
771 } else
772 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
773 }
774
776 LOffset, ROffset);
777 return replaceInstUsesWith(I, Cmp);
778 }
779 }
780
781 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
782 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
783 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
784 // If the GEPs only differ by one index, compare it.
785 unsigned NumDifferences = 0; // Keep track of # differences.
786 unsigned DiffOperand = 0; // The operand that differs.
787 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
788 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
789 Type *LHSType = GEPLHS->getOperand(i)->getType();
790 Type *RHSType = GEPRHS->getOperand(i)->getType();
791 // FIXME: Better support for vector of pointers.
792 if (LHSType->getPrimitiveSizeInBits() !=
793 RHSType->getPrimitiveSizeInBits() ||
794 (GEPLHS->getType()->isVectorTy() &&
795 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
796 // Irreconcilable differences.
797 NumDifferences = 2;
798 break;
799 }
800
801 if (NumDifferences++)
802 break;
803 DiffOperand = i;
804 }
805
806 if (NumDifferences == 0) // SAME GEP?
807 return replaceInstUsesWith(
808 I, // No comparison is needed here.
809 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
810 // If two GEPs only differ by an index, compare them.
811 // Note that nowrap flags are always needed when comparing two indices.
812 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
813 Value *LHSV = GEPLHS->getOperand(DiffOperand);
814 Value *RHSV = GEPRHS->getOperand(DiffOperand);
815 return NewICmp(NW, LHSV, RHSV);
816 }
817 }
818
819 if (Base.Ptr && !Base.isExpensive()) {
820 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
821 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
822
823 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
824 // Without the flags, we can still fold if the offsets are constant and
825 // they cross the base's alignment boundary the same number of times, so
826 // either both arguments will wrap, or none of them will.
827 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
828 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
829 APInt LOff(BW, 0);
830 APInt ROff(BW, 0);
832 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
833 RHS->stripAndAccumulateConstantOffsets(
834 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
835 DoFold =
838 }
839
840 if (DoFold) {
841 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
842 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
843 /*RewriteGEP=*/true);
844 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
845 /*RewriteGEP=*/true);
846 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
847 }
848 }
849 }
850
851 // Try convert this to an indexed compare by looking through PHIs/casts as a
852 // last resort.
853 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
854}
855
857 // It would be tempting to fold away comparisons between allocas and any
858 // pointer not based on that alloca (e.g. an argument). However, even
859 // though such pointers cannot alias, they can still compare equal.
860 //
861 // But LLVM doesn't specify where allocas get their memory, so if the alloca
862 // doesn't escape we can argue that it's impossible to guess its value, and we
863 // can therefore act as if any such guesses are wrong.
864 //
865 // However, we need to ensure that this folding is consistent: We can't fold
866 // one comparison to false, and then leave a different comparison against the
867 // same value alone (as it might evaluate to true at runtime, leading to a
868 // contradiction). As such, this code ensures that all comparisons are folded
869 // at the same time, and there are no other escapes.
870
871 struct CmpCaptureTracker : public CaptureTracker {
872 AllocaInst *Alloca;
873 bool Captured = false;
874 /// The value of the map is a bit mask of which icmp operands the alloca is
875 /// used in.
877
878 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
879
880 void tooManyUses() override { Captured = true; }
881
882 Action captured(const Use *U, UseCaptureInfo CI) override {
883 // TODO(captures): Use UseCaptureInfo.
884 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
885 // We need to check that U is based *only* on the alloca, and doesn't
886 // have other contributions from a select/phi operand.
887 // TODO: We could check whether getUnderlyingObjects() reduces to one
888 // object, which would allow looking through phi nodes.
889 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
890 // Collect equality icmps of the alloca, and don't treat them as
891 // captures.
892 ICmps[ICmp] |= 1u << U->getOperandNo();
893 return Continue;
894 }
895
896 Captured = true;
897 return Stop;
898 }
899 };
900
901 CmpCaptureTracker Tracker(Alloca);
902 PointerMayBeCaptured(Alloca, &Tracker);
903 if (Tracker.Captured)
904 return false;
905
906 bool Changed = false;
907 for (auto [ICmp, Operands] : Tracker.ICmps) {
908 switch (Operands) {
909 case 1:
910 case 2: {
911 // The alloca is only used in one icmp operand. Assume that the
912 // equality is false.
913 auto *Res = ConstantInt::get(ICmp->getType(),
914 ICmp->getPredicate() == ICmpInst::ICMP_NE);
915 replaceInstUsesWith(*ICmp, Res);
917 Changed = true;
918 break;
919 }
920 case 3:
921 // Both icmp operands are based on the alloca, so this is comparing
922 // pointer offsets, without leaking any information about the address
923 // of the alloca. Ignore such comparisons.
924 break;
925 default:
926 llvm_unreachable("Cannot happen");
927 }
928 }
929
930 return Changed;
931}
932
933/// Fold "icmp pred (X+C), X".
935 CmpPredicate Pred) {
936 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
937 // so the values can never be equal. Similarly for all other "or equals"
938 // operators.
939 assert(!!C && "C should not be zero!");
940
941 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
942 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
943 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
944 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
945 Constant *R =
946 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
947 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
948 }
949
950 // (X+1) >u X --> X <u (0-1) --> X != 255
951 // (X+2) >u X --> X <u (0-2) --> X <u 254
952 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
953 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
954 return new ICmpInst(ICmpInst::ICMP_ULT, X,
955 ConstantInt::get(X->getType(), -C));
956
957 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
958
959 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
960 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
961 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
962 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
963 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
964 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
965 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
966 return new ICmpInst(ICmpInst::ICMP_SGT, X,
967 ConstantInt::get(X->getType(), SMax - C));
968
969 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
970 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
971 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
972 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
973 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
974 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
975
976 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
977 return new ICmpInst(ICmpInst::ICMP_SLT, X,
978 ConstantInt::get(X->getType(), SMax - (C - 1)));
979}
980
981/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
982/// (icmp eq/ne A, Log2(AP2/AP1)) ->
983/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
985 const APInt &AP1,
986 const APInt &AP2) {
987 assert(I.isEquality() && "Cannot fold icmp gt/lt");
988
989 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
990 if (I.getPredicate() == I.ICMP_NE)
991 Pred = CmpInst::getInversePredicate(Pred);
992 return new ICmpInst(Pred, LHS, RHS);
993 };
994
995 // Don't bother doing any work for cases which InstSimplify handles.
996 if (AP2.isZero())
997 return nullptr;
998
999 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1000 if (IsAShr) {
1001 if (AP2.isAllOnes())
1002 return nullptr;
1003 if (AP2.isNegative() != AP1.isNegative())
1004 return nullptr;
1005 if (AP2.sgt(AP1))
1006 return nullptr;
1007 }
1008
1009 if (!AP1)
1010 // 'A' must be large enough to shift out the highest set bit.
1011 return getICmp(I.ICMP_UGT, A,
1012 ConstantInt::get(A->getType(), AP2.logBase2()));
1013
1014 if (AP1 == AP2)
1015 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1016
1017 int Shift;
1018 if (IsAShr && AP1.isNegative())
1019 Shift = AP1.countl_one() - AP2.countl_one();
1020 else
1021 Shift = AP1.countl_zero() - AP2.countl_zero();
1022
1023 if (Shift > 0) {
1024 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1025 // There are multiple solutions if we are comparing against -1 and the LHS
1026 // of the ashr is not a power of two.
1027 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1028 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1029 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1030 } else if (AP1 == AP2.lshr(Shift)) {
1031 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1032 }
1033 }
1034
1035 // Shifting const2 will never be equal to const1.
1036 // FIXME: This should always be handled by InstSimplify?
1037 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1038 return replaceInstUsesWith(I, TorF);
1039}
1040
1041/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1042/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1044 const APInt &AP1,
1045 const APInt &AP2) {
1046 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1047
1048 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1049 if (I.getPredicate() == I.ICMP_NE)
1050 Pred = CmpInst::getInversePredicate(Pred);
1051 return new ICmpInst(Pred, LHS, RHS);
1052 };
1053
1054 // Don't bother doing any work for cases which InstSimplify handles.
1055 if (AP2.isZero())
1056 return nullptr;
1057
1058 unsigned AP2TrailingZeros = AP2.countr_zero();
1059
1060 if (!AP1 && AP2TrailingZeros != 0)
1061 return getICmp(
1062 I.ICMP_UGE, A,
1063 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1064
1065 if (AP1 == AP2)
1066 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1067
1068 // Get the distance between the lowest bits that are set.
1069 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1070
1071 if (Shift > 0 && AP2.shl(Shift) == AP1)
1072 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1073
1074 // Shifting const2 will never be equal to const1.
1075 // FIXME: This should always be handled by InstSimplify?
1076 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1077 return replaceInstUsesWith(I, TorF);
1078}
1079
1080/// The caller has matched a pattern of the form:
1081/// I = icmp ugt (add (add A, B), CI2), CI1
1082/// If this is of the form:
1083/// sum = a + b
1084/// if (sum+128 >u 255)
1085/// Then replace it with llvm.sadd.with.overflow.i8.
1086///
1088 ConstantInt *CI2, ConstantInt *CI1,
1089 InstCombinerImpl &IC) {
1090 // The transformation we're trying to do here is to transform this into an
1091 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1092 // with a narrower add, and discard the add-with-constant that is part of the
1093 // range check (if we can't eliminate it, this isn't profitable).
1094
1095 // In order to eliminate the add-with-constant, the compare can be its only
1096 // use.
1097 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1098 if (!AddWithCst->hasOneUse())
1099 return nullptr;
1100
1101 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1102 if (!CI2->getValue().isPowerOf2())
1103 return nullptr;
1104 unsigned NewWidth = CI2->getValue().countr_zero();
1105 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1106 return nullptr;
1107
1108 // The width of the new add formed is 1 more than the bias.
1109 ++NewWidth;
1110
1111 // Check to see that CI1 is an all-ones value with NewWidth bits.
1112 if (CI1->getBitWidth() == NewWidth ||
1113 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1114 return nullptr;
1115
1116 // This is only really a signed overflow check if the inputs have been
1117 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1118 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1119 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1120 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1121 return nullptr;
1122
1123 // In order to replace the original add with a narrower
1124 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1125 // and truncates that discard the high bits of the add. Verify that this is
1126 // the case.
1127 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1128 for (User *U : OrigAdd->users()) {
1129 if (U == AddWithCst)
1130 continue;
1131
1132 // Only accept truncates for now. We would really like a nice recursive
1133 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1134 // chain to see which bits of a value are actually demanded. If the
1135 // original add had another add which was then immediately truncated, we
1136 // could still do the transformation.
1138 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1139 return nullptr;
1140 }
1141
1142 // If the pattern matches, truncate the inputs to the narrower type and
1143 // use the sadd_with_overflow intrinsic to efficiently compute both the
1144 // result and the overflow bit.
1145 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1147 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1148
1149 InstCombiner::BuilderTy &Builder = IC.Builder;
1150
1151 // Put the new code above the original add, in case there are any uses of the
1152 // add between the add and the compare.
1153 Builder.SetInsertPoint(OrigAdd);
1154
1155 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1156 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1157 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1158 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1159 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1160
1161 // The inner add was the result of the narrow add, zero extended to the
1162 // wider type. Replace it with the result computed by the intrinsic.
1163 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1164 IC.eraseInstFromFunction(*OrigAdd);
1165
1166 // The original icmp gets replaced with the overflow value.
1167 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1168}
1169
1170/// If we have:
1171/// icmp eq/ne (urem/srem %x, %y), 0
1172/// iff %y is a power-of-two, we can replace this with a bit test:
1173/// icmp eq/ne (and %x, (add %y, -1)), 0
1175 // This fold is only valid for equality predicates.
1176 if (!I.isEquality())
1177 return nullptr;
1178 CmpPredicate Pred;
1179 Value *X, *Y, *Zero;
1180 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1181 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1182 return nullptr;
1183 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1184 return nullptr;
1185 // This may increase instruction count, we don't enforce that Y is a constant.
1186 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1187 Value *Masked = Builder.CreateAnd(X, Mask);
1188 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1189}
1190
1191/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1192/// by one-less-than-bitwidth into a sign test on the original value.
1194 Instruction *Val;
1195 CmpPredicate Pred;
1196 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1197 return nullptr;
1198
1199 Value *X;
1200 Type *XTy;
1201
1202 Constant *C;
1203 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1204 XTy = X->getType();
1205 unsigned XBitWidth = XTy->getScalarSizeInBits();
1207 APInt(XBitWidth, XBitWidth - 1))))
1208 return nullptr;
1209 } else if (isa<BinaryOperator>(Val) &&
1211 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1212 /*AnalyzeForSignBitExtraction=*/true))) {
1213 XTy = X->getType();
1214 } else
1215 return nullptr;
1216
1217 return ICmpInst::Create(Instruction::ICmp,
1221}
1222
1223// Handle icmp pred X, 0
1225 CmpInst::Predicate Pred = Cmp.getPredicate();
1226 if (!match(Cmp.getOperand(1), m_Zero()))
1227 return nullptr;
1228
1229 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1230 if (Pred == ICmpInst::ICMP_SGT) {
1231 Value *A, *B;
1232 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1233 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1234 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1235 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1236 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1237 }
1238 }
1239
1241 return New;
1242
1243 // Given:
1244 // icmp eq/ne (urem %x, %y), 0
1245 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1246 // icmp eq/ne %x, 0
1247 Value *X, *Y;
1248 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1249 ICmpInst::isEquality(Pred)) {
1250 KnownBits XKnown = computeKnownBits(X, &Cmp);
1251 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1252 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1253 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1254 }
1255
1256 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1257 // odd/non-zero/there is no overflow.
1258 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1259 ICmpInst::isEquality(Pred)) {
1260
1261 KnownBits XKnown = computeKnownBits(X, &Cmp);
1262 // if X % 2 != 0
1263 // (icmp eq/ne Y)
1264 if (XKnown.countMaxTrailingZeros() == 0)
1265 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1266
1267 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1268 // if Y % 2 != 0
1269 // (icmp eq/ne X)
1270 if (YKnown.countMaxTrailingZeros() == 0)
1271 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1272
1273 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1274 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1275 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1276 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1277 // but to avoid unnecessary work, first just if this is an obvious case.
1278
1279 // if X non-zero and NoOverflow(X * Y)
1280 // (icmp eq/ne Y)
1281 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1282 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1283
1284 // if Y non-zero and NoOverflow(X * Y)
1285 // (icmp eq/ne X)
1286 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1287 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1288 }
1289 // Note, we are skipping cases:
1290 // if Y % 2 != 0 AND X % 2 != 0
1291 // (false/true)
1292 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1293 // (false/true)
1294 // Those can be simplified later as we would have already replaced the (icmp
1295 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1296 // will fold to a constant elsewhere.
1297 }
1298
1299 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1300 // where f(X) == 0 if and only if X == 0
1301 if (ICmpInst::isEquality(Pred))
1302 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1303 return new ICmpInst(Pred, Stripped,
1304 Constant::getNullValue(Stripped->getType()));
1305
1306 return nullptr;
1307}
1308
1309/// Fold icmp eq (num + mask) & ~mask, num
1310/// to
1311/// icmp eq (and num, mask), 0
1312/// Where mask is a low bit mask.
1314 Value *Num;
1315 CmpPredicate Pred;
1316 const APInt *Mask, *Neg;
1317
1318 if (!match(&Cmp,
1319 m_c_ICmp(Pred, m_Value(Num),
1321 m_LowBitMask(Mask))),
1322 m_APInt(Neg))))))
1323 return nullptr;
1324
1325 if (*Neg != ~*Mask)
1326 return nullptr;
1327
1328 if (!ICmpInst::isEquality(Pred))
1329 return nullptr;
1330
1331 // Create new icmp eq (num & mask), 0
1332 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1333 auto *Zero = Constant::getNullValue(Num->getType());
1334
1335 return new ICmpInst(Pred, NewAnd, Zero);
1336}
1337
1338/// Fold icmp Pred X, C.
1339/// TODO: This code structure does not make sense. The saturating add fold
1340/// should be moved to some other helper and extended as noted below (it is also
1341/// possible that code has been made unnecessary - do we canonicalize IR to
1342/// overflow/saturating intrinsics or not?).
1344 // Match the following pattern, which is a common idiom when writing
1345 // overflow-safe integer arithmetic functions. The source performs an addition
1346 // in wider type and explicitly checks for overflow using comparisons against
1347 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1348 //
1349 // TODO: This could probably be generalized to handle other overflow-safe
1350 // operations if we worked out the formulas to compute the appropriate magic
1351 // constants.
1352 //
1353 // sum = a + b
1354 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1355 CmpInst::Predicate Pred = Cmp.getPredicate();
1356 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1357 Value *A, *B;
1358 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1359 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1360 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1361 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1362 return Res;
1363
1364 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1366 if (!C)
1367 return nullptr;
1368
1369 if (auto *Phi = dyn_cast<PHINode>(Op0))
1370 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1372 for (Value *V : Phi->incoming_values()) {
1373 Constant *Res =
1375 if (!Res)
1376 return nullptr;
1377 Ops.push_back(Res);
1378 }
1379 Builder.SetInsertPoint(Phi);
1380 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1381 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1382 NewPhi->addIncoming(V, Pred);
1383 return replaceInstUsesWith(Cmp, NewPhi);
1384 }
1385
1387 return R;
1388
1389 return nullptr;
1390}
1391
1392/// Canonicalize icmp instructions based on dominating conditions.
1394 // We already checked simple implication in InstSimplify, only handle complex
1395 // cases here.
1396 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1397 const APInt *C;
1398 if (!match(Y, m_APInt(C)))
1399 return nullptr;
1400
1401 CmpInst::Predicate Pred = Cmp.getPredicate();
1403
1404 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1405 const APInt *DomC) -> Instruction * {
1406 // We have 2 compares of a variable with constants. Calculate the constant
1407 // ranges of those compares to see if we can transform the 2nd compare:
1408 // DomBB:
1409 // DomCond = icmp DomPred X, DomC
1410 // br DomCond, CmpBB, FalseBB
1411 // CmpBB:
1412 // Cmp = icmp Pred X, C
1413 ConstantRange DominatingCR =
1414 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1415 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1416 ConstantRange Difference = DominatingCR.difference(CR);
1417 if (Intersection.isEmptySet())
1418 return replaceInstUsesWith(Cmp, Builder.getFalse());
1419 if (Difference.isEmptySet())
1420 return replaceInstUsesWith(Cmp, Builder.getTrue());
1421
1422 // Canonicalizing a sign bit comparison that gets used in a branch,
1423 // pessimizes codegen by generating branch on zero instruction instead
1424 // of a test and branch. So we avoid canonicalizing in such situations
1425 // because test and branch instruction has better branch displacement
1426 // than compare and branch instruction.
1427 bool UnusedBit;
1428 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1429 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1430 return nullptr;
1431
1432 // Avoid an infinite loop with min/max canonicalization.
1433 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1434 if (Cmp.hasOneUse() &&
1435 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1436 return nullptr;
1437
1438 if (const APInt *EqC = Intersection.getSingleElement())
1439 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1440 if (const APInt *NeC = Difference.getSingleElement())
1441 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1442 return nullptr;
1443 };
1444
1445 for (CondBrInst *BI : DC.conditionsFor(X)) {
1446 CmpPredicate DomPred;
1447 const APInt *DomC;
1448 if (!match(BI->getCondition(),
1449 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1450 continue;
1451
1452 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1453 if (DT.dominates(Edge0, Cmp.getParent())) {
1454 if (auto *V = handleDomCond(DomPred, DomC))
1455 return V;
1456 } else {
1457 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1458 if (DT.dominates(Edge1, Cmp.getParent()))
1459 if (auto *V =
1460 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1461 return V;
1462 }
1463 }
1464
1465 return nullptr;
1466}
1467
1468/// Fold icmp (trunc X), C.
1470 TruncInst *Trunc,
1471 const APInt &C) {
1472 ICmpInst::Predicate Pred = Cmp.getPredicate();
1473 Value *X = Trunc->getOperand(0);
1474 Type *SrcTy = X->getType();
1475 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1476 SrcBits = SrcTy->getScalarSizeInBits();
1477
1478 // Match (icmp pred (trunc nuw/nsw X), C)
1479 // Which we can convert to (icmp pred X, (sext/zext C))
1480 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1481 if (Trunc->hasNoSignedWrap())
1482 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1483 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1484 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1485 }
1486
1487 if (C.isOne() && C.getBitWidth() > 1) {
1488 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1489 Value *V = nullptr;
1490 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1491 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1492 ConstantInt::get(V->getType(), 1));
1493 }
1494
1495 // TODO: Handle non-equality predicates.
1496 Value *Y;
1497 const APInt *Pow2;
1498 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1499 DstBits > Pow2->logBase2()) {
1500 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1501 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1502 // iff N > log2(Pow2)
1503 if (C.isZero()) {
1504 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1505 return new ICmpInst(NewPred, Y,
1506 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1507 }
1508 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1509 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1510 if (C.isPowerOf2())
1511 return new ICmpInst(
1512 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1513 }
1514
1515 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1516 // Canonicalize to a mask and wider compare if the wide type is suitable:
1517 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1518 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1519 Constant *Mask =
1520 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1521 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1522 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1523 return new ICmpInst(Pred, And, WideC);
1524 }
1525
1526 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1527 // of the high bits truncated out of x are known.
1529
1530 // If all the high bits are known, we can do this xform.
1531 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1532 // Pull in the high bits from known-ones set.
1533 APInt NewRHS = C.zext(SrcBits);
1534 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1535 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1536 }
1537 }
1538
1539 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1540 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1541 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1542 Value *ShOp;
1543 uint64_t ShAmt;
1544 bool TrueIfSigned;
1545 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1546 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1547 DstBits == SrcBits - ShAmt) {
1548 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1550 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1552 }
1553
1554 return nullptr;
1555}
1556
1557/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1558/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1561 const SimplifyQuery &Q) {
1562 Value *X, *Y;
1563 CmpPredicate Pred;
1564 bool YIsSExt = false;
1565 // Try to match icmp (trunc X), (trunc Y)
1566 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1567 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1568 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1569 if (Cmp.isSigned()) {
1570 // For signed comparisons, both truncs must be nsw.
1571 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1572 return nullptr;
1573 } else {
1574 // For unsigned and equality comparisons, either both must be nuw or
1575 // both must be nsw, we don't care which.
1576 if (!NoWrapFlags)
1577 return nullptr;
1578 }
1579
1580 if (X->getType() != Y->getType() &&
1581 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1582 return nullptr;
1583 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1584 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1585 std::swap(X, Y);
1586 Pred = Cmp.getSwappedPredicate(Pred);
1587 }
1588 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1589 }
1590 // Try to match icmp (trunc nuw X), (zext Y)
1591 else if (!Cmp.isSigned() &&
1592 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1593 m_OneUse(m_ZExt(m_Value(Y)))))) {
1594 // Can fold trunc nuw + zext for unsigned and equality predicates.
1595 }
1596 // Try to match icmp (trunc nsw X), (sext Y)
1597 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1599 // Can fold trunc nsw + zext/sext for all predicates.
1600 YIsSExt =
1601 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1602 } else
1603 return nullptr;
1604
1605 Type *TruncTy = Cmp.getOperand(0)->getType();
1606 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1607
1608 // If this transform will end up changing from desirable types -> undesirable
1609 // types skip it.
1610 if (isDesirableIntType(TruncBits) &&
1611 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1612 return nullptr;
1613
1614 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1615 return new ICmpInst(Pred, X, NewY);
1616}
1617
1618/// Fold icmp (xor X, Y), C.
1621 const APInt &C) {
1622 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1623 return I;
1624
1625 Value *X = Xor->getOperand(0);
1626 Value *Y = Xor->getOperand(1);
1627 const APInt *XorC;
1628 if (!match(Y, m_APInt(XorC)))
1629 return nullptr;
1630
1631 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1632 // fold the xor.
1633 ICmpInst::Predicate Pred = Cmp.getPredicate();
1634 bool TrueIfSigned = false;
1635 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1636
1637 // If the sign bit of the XorCst is not set, there is no change to
1638 // the operation, just stop using the Xor.
1639 if (!XorC->isNegative())
1640 return replaceOperand(Cmp, 0, X);
1641
1642 // Emit the opposite comparison.
1643 if (TrueIfSigned)
1644 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1645 ConstantInt::getAllOnesValue(X->getType()));
1646 else
1647 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1648 ConstantInt::getNullValue(X->getType()));
1649 }
1650
1651 if (Xor->hasOneUse()) {
1652 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1653 if (!Cmp.isEquality() && XorC->isSignMask()) {
1654 Pred = Cmp.getFlippedSignednessPredicate();
1655 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1656 }
1657
1658 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1659 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1660 Pred = Cmp.getFlippedSignednessPredicate();
1661 Pred = Cmp.getSwappedPredicate(Pred);
1662 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1663 }
1664 }
1665
1666 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1667 if (Pred == ICmpInst::ICMP_UGT) {
1668 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1669 if (*XorC == ~C && (C + 1).isPowerOf2())
1670 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1671 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1672 if (*XorC == C && (C + 1).isPowerOf2())
1673 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1674 }
1675 if (Pred == ICmpInst::ICMP_ULT) {
1676 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1677 if (*XorC == -C && C.isPowerOf2())
1678 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1679 ConstantInt::get(X->getType(), ~C));
1680 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1681 if (*XorC == C && (-C).isPowerOf2())
1682 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1683 ConstantInt::get(X->getType(), ~C));
1684 }
1685 return nullptr;
1686}
1687
1688/// For power-of-2 C:
1689/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1690/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1693 const APInt &C) {
1694 CmpInst::Predicate Pred = Cmp.getPredicate();
1695 APInt PowerOf2;
1696 if (Pred == ICmpInst::ICMP_ULT)
1697 PowerOf2 = C;
1698 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1699 PowerOf2 = C + 1;
1700 else
1701 return nullptr;
1702 if (!PowerOf2.isPowerOf2())
1703 return nullptr;
1704 Value *X;
1705 const APInt *ShiftC;
1707 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1708 return nullptr;
1709 uint64_t Shift = ShiftC->getLimitedValue();
1710 Type *XType = X->getType();
1711 if (Shift == 0 || PowerOf2.isMinSignedValue())
1712 return nullptr;
1713 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1714 APInt Bound =
1715 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1716 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1717}
1718
1719/// Fold icmp (and (sh X, Y), C2), C1.
1722 const APInt &C1,
1723 const APInt &C2) {
1724 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1725 if (!Shift || !Shift->isShift())
1726 return nullptr;
1727
1728 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1729 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1730 // code produced by the clang front-end, for bitfield access.
1731 // This seemingly simple opportunity to fold away a shift turns out to be
1732 // rather complicated. See PR17827 for details.
1733 unsigned ShiftOpcode = Shift->getOpcode();
1734 bool IsShl = ShiftOpcode == Instruction::Shl;
1735 const APInt *C3;
1736 if (match(Shift->getOperand(1), m_APInt(C3))) {
1737 APInt NewAndCst, NewCmpCst;
1738 bool AnyCmpCstBitsShiftedOut;
1739 if (ShiftOpcode == Instruction::Shl) {
1740 // For a left shift, we can fold if the comparison is not signed. We can
1741 // also fold a signed comparison if the mask value and comparison value
1742 // are not negative. These constraints may not be obvious, but we can
1743 // prove that they are correct using an SMT solver.
1744 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1745 return nullptr;
1746
1747 NewCmpCst = C1.lshr(*C3);
1748 NewAndCst = C2.lshr(*C3);
1749 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1750 } else if (ShiftOpcode == Instruction::LShr) {
1751 // For a logical right shift, we can fold if the comparison is not signed.
1752 // We can also fold a signed comparison if the shifted mask value and the
1753 // shifted comparison value are not negative. These constraints may not be
1754 // obvious, but we can prove that they are correct using an SMT solver.
1755 NewCmpCst = C1.shl(*C3);
1756 NewAndCst = C2.shl(*C3);
1757 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1758 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1759 return nullptr;
1760 } else {
1761 // For an arithmetic shift, check that both constants don't use (in a
1762 // signed sense) the top bits being shifted out.
1763 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1764 NewCmpCst = C1.shl(*C3);
1765 NewAndCst = C2.shl(*C3);
1766 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1767 if (NewAndCst.ashr(*C3) != C2)
1768 return nullptr;
1769 }
1770
1771 if (AnyCmpCstBitsShiftedOut) {
1772 // If we shifted bits out, the fold is not going to work out. As a
1773 // special case, check to see if this means that the result is always
1774 // true or false now.
1775 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1776 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1777 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1778 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1779 } else {
1780 Value *NewAnd = Builder.CreateAnd(
1781 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1782 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1783 ConstantInt::get(And->getType(), NewCmpCst));
1784 }
1785 }
1786
1787 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1788 // preferable because it allows the C2 << Y expression to be hoisted out of a
1789 // loop if Y is invariant and X is not.
1790 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1791 !Shift->isArithmeticShift() &&
1792 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1793 // Compute C2 << Y.
1794 Value *NewShift =
1795 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1796 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1797
1798 // Compute X & (C2 << Y).
1799 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1800 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1801 }
1802
1803 return nullptr;
1804}
1805
1806/// Fold icmp (and X, C2), C1.
1809 const APInt &C1) {
1810 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1811
1812 // icmp ne (and X, 1), 0 --> trunc X to i1
1813 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1814 return new TruncInst(And->getOperand(0), Cmp.getType());
1815
1816 const APInt *C2;
1817 Value *X;
1818 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1819 return nullptr;
1820
1821 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1822 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1823 C2->isNegatedPowerOf2())
1824 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1825 ConstantInt::get(X->getType(), ~*C2));
1826 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1827 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1828 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1829 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1830 ConstantInt::get(X->getType(), -*C2));
1831
1832 // Don't perform the following transforms if the AND has multiple uses
1833 if (!And->hasOneUse())
1834 return nullptr;
1835
1836 if (Cmp.isEquality() && C1.isZero()) {
1837 // Restrict this fold to single-use 'and' (PR10267).
1838 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1839 if (C2->isSignMask()) {
1840 Constant *Zero = Constant::getNullValue(X->getType());
1841 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1842 return new ICmpInst(NewPred, X, Zero);
1843 }
1844
1845 APInt NewC2 = *C2;
1846 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1847 // Set high zeros of C2 to allow matching negated power-of-2.
1848 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1849 Know.countMinLeadingZeros());
1850
1851 // Restrict this fold only for single-use 'and' (PR10267).
1852 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1853 if (NewC2.isNegatedPowerOf2()) {
1854 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1855 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1856 return new ICmpInst(NewPred, X, NegBOC);
1857 }
1858 }
1859
1860 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1861 // the input width without changing the value produced, eliminate the cast:
1862 //
1863 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1864 //
1865 // We can do this transformation if the constants do not have their sign bits
1866 // set or if it is an equality comparison. Extending a relational comparison
1867 // when we're checking the sign bit would not work.
1868 Value *W;
1869 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1870 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1871 // TODO: Is this a good transform for vectors? Wider types may reduce
1872 // throughput. Should this transform be limited (even for scalars) by using
1873 // shouldChangeType()?
1874 if (!Cmp.getType()->isVectorTy()) {
1875 Type *WideType = W->getType();
1876 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1877 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1878 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1879 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1880 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1881 }
1882 }
1883
1884 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1885 return I;
1886
1887 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1888 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1889 //
1890 // iff pred isn't signed
1891 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1892 match(And->getOperand(1), m_One())) {
1893 Constant *One = cast<Constant>(And->getOperand(1));
1894 Value *Or = And->getOperand(0);
1895 Value *A, *B, *LShr;
1896 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1897 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1898 unsigned UsesRemoved = 0;
1899 if (And->hasOneUse())
1900 ++UsesRemoved;
1901 if (Or->hasOneUse())
1902 ++UsesRemoved;
1903 if (LShr->hasOneUse())
1904 ++UsesRemoved;
1905
1906 // Compute A & ((1 << B) | 1)
1907 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1908 if (UsesRemoved >= RequireUsesRemoved) {
1909 Value *NewOr =
1910 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1911 /*HasNUW=*/true),
1912 One, Or->getName());
1913 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1914 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1915 }
1916 }
1917 }
1918
1919 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1920 // llvm.is.fpclass(X, fcInf|fcNan)
1921 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1922 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1923 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1924 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1925 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1926 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1927 Value *V;
1928 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1929 Attribute::NoImplicitFloat) &&
1930 Cmp.isEquality() &&
1932 Type *FPType = V->getType()->getScalarType();
1933 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1934 APInt ExponentMask =
1935 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1936 if (*C2 == ExponentMask) {
1937 unsigned Mask = C1.isZero()
1940 if (isICMP_NE)
1941 Mask = ~Mask & fcAllFlags;
1942 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1943 }
1944 }
1945 }
1946
1947 return nullptr;
1948}
1949
1950/// Fold icmp (and X, Y), C.
1953 const APInt &C) {
1954 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1955 return I;
1956
1957 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1958 bool TrueIfNeg;
1959 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1960 // ((X - 1) & ~X) < 0 --> X == 0
1961 // ((X - 1) & ~X) >= 0 --> X != 0
1962 Value *X;
1963 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1964 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1965 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1966 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1967 }
1968 // (X & -X) < 0 --> X == MinSignedC
1969 // (X & -X) > -1 --> X != MinSignedC
1970 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1971 Constant *MinSignedC = ConstantInt::get(
1972 X->getType(),
1973 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1974 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1975 return new ICmpInst(NewPred, X, MinSignedC);
1976 }
1977 }
1978
1979 // TODO: These all require that Y is constant too, so refactor with the above.
1980
1981 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1982 Value *X = And->getOperand(0);
1983 Value *Y = And->getOperand(1);
1984 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1985 if (auto *LI = dyn_cast<LoadInst>(X))
1986 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
1987 if (Instruction *Res = foldCmpLoadFromIndexedGlobal(LI, GEP, Cmp, C2))
1988 return Res;
1989
1990 if (!Cmp.isEquality())
1991 return nullptr;
1992
1993 // (X & -X) == 0 --> X == 0
1994 // (X & -X) != 0 --> X != 0
1995 // (X & -X) == 1 --> trunc X to i1
1996 // (X & -X) != 1 --> !(trunc X to i1)
1997 // Cmp is == or != by the check above.
1998 Value *MatchedX;
1999 // Match X & -X in either operand order.
2000 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2001 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
2002 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2003 if (C.isZero())
2004 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
2005
2006 // (X & -X) == 1 iff the low bit of X is set.
2007 if (Pred == CmpInst::ICMP_EQ)
2008 return new TruncInst(MatchedX, Cmp.getType());
2009
2010 // The remaining case needs a trunc and not. Require the original and
2011 // to become dead to avoid increasing the instruction count.
2012 if (And->hasOneUse()) {
2013 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
2014 return BinaryOperator::CreateNot(Trunc);
2015 }
2016 }
2017
2018 // X & -C == -C -> X > u ~C
2019 // X & -C != -C -> X <= u ~C
2020 // iff C is a power of 2
2021 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
2022 auto NewPred =
2024 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
2025 }
2026
2027 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2028 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2029 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2030 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2032 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2033 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2034 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2035 Value *And = Builder.CreateAnd(TruncY, X);
2037 }
2038 return BinaryOperator::CreateAnd(TruncY, X);
2039 }
2040
2041 // (icmp eq/ne (and (shl -1, X), Y), 0)
2042 // -> (icmp eq/ne (lshr Y, X), 0)
2043 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2044 // highly unlikely the non-zero case will ever show up in code.
2045 if (C.isZero() &&
2047 m_Value(Y))))) {
2048 Value *LShr = Builder.CreateLShr(Y, X);
2049 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2050 }
2051
2052 // (icmp eq/ne (and (add A, Addend), Msk), C)
2053 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2054 {
2055 Value *A;
2056 const APInt *Addend, *Msk;
2058 m_LowBitMask(Msk)))) &&
2059 C.ule(*Msk)) {
2060 APInt NewComperand = (C - *Addend) & *Msk;
2061 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2062 return new ICmpInst(Pred, MaskA,
2063 ConstantInt::get(MaskA->getType(), NewComperand));
2064 }
2065 }
2066
2067 return nullptr;
2068}
2069
2070/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2072 InstCombiner::BuilderTy &Builder) {
2073 // Are we using xors or subs to bitwise check for a pair or pairs of
2074 // (in)equalities? Convert to a shorter form that has more potential to be
2075 // folded even further.
2076 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2077 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2078 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2079 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2080 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2081 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2083 SmallVector<Value *, 16> WorkList(1, Or);
2084
2085 while (!WorkList.empty()) {
2086 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2087 Value *Lhs, *Rhs;
2088
2089 if (match(OrOperatorArgument,
2090 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2091 CmpValues.emplace_back(Lhs, Rhs);
2092 return;
2093 }
2094
2095 if (match(OrOperatorArgument,
2096 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2097 CmpValues.emplace_back(Lhs, Rhs);
2098 return;
2099 }
2100
2101 WorkList.push_back(OrOperatorArgument);
2102 };
2103
2104 Value *CurrentValue = WorkList.pop_back_val();
2105 Value *OrOperatorLhs, *OrOperatorRhs;
2106
2107 if (!match(CurrentValue,
2108 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2109 return nullptr;
2110 }
2111
2112 MatchOrOperatorArgument(OrOperatorRhs);
2113 MatchOrOperatorArgument(OrOperatorLhs);
2114 }
2115
2116 ICmpInst::Predicate Pred = Cmp.getPredicate();
2117 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2118 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2119 CmpValues.rbegin()->second);
2120
2121 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2122 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2123 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2124 }
2125
2126 return LhsCmp;
2127}
2128
2129/// Fold icmp (or X, Y), C.
2132 const APInt &C) {
2133 ICmpInst::Predicate Pred = Cmp.getPredicate();
2134 if (C.isOne()) {
2135 // icmp slt signum(V) 1 --> icmp slt V, 1
2136 Value *V = nullptr;
2137 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2138 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2139 ConstantInt::get(V->getType(), 1));
2140 }
2141
2142 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2143
2144 // (icmp eq/ne (or disjoint x, C0), C1)
2145 // -> (icmp eq/ne x, C0^C1)
2146 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2147 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2148 Value *NewC =
2149 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2150 return new ICmpInst(Pred, OrOp0, NewC);
2151 }
2152
2153 const APInt *MaskC;
2154 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2155 if (*MaskC == C && (C + 1).isPowerOf2()) {
2156 // X | C == C --> X <=u C
2157 // X | C != C --> X >u C
2158 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2160 return new ICmpInst(Pred, OrOp0, OrOp1);
2161 }
2162
2163 // More general: canonicalize 'equality with set bits mask' to
2164 // 'equality with clear bits mask'.
2165 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2166 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2167 if (Or->hasOneUse()) {
2168 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2169 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2170 return new ICmpInst(Pred, And, NewC);
2171 }
2172 }
2173
2174 // (X | (X-1)) s< 0 --> X s< 1
2175 // (X | (X-1)) s> -1 --> X s> 0
2176 Value *X;
2177 bool TrueIfSigned;
2178 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2180 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2181 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2182 return new ICmpInst(NewPred, X, NewC);
2183 }
2184
2185 const APInt *OrC;
2186 // icmp(X | OrC, C) --> icmp(X, 0)
2187 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2188 switch (Pred) {
2189 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2190 case ICmpInst::ICMP_SLT:
2191 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2192 case ICmpInst::ICMP_SGE:
2193 if (OrC->sge(C))
2194 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2195 break;
2196 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2197 case ICmpInst::ICMP_SLE:
2198 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2199 case ICmpInst::ICMP_SGT:
2200 if (OrC->sgt(C))
2202 ConstantInt::getNullValue(X->getType()));
2203 break;
2204 default:
2205 break;
2206 }
2207 }
2208
2209 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2210 return nullptr;
2211
2212 Value *P, *Q;
2214 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2215 // -> and (icmp eq P, null), (icmp eq Q, null).
2216 Value *CmpP =
2217 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2218 Value *CmpQ =
2219 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2220 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2221 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2222 }
2223
2224 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2225 return replaceInstUsesWith(Cmp, V);
2226
2227 return nullptr;
2228}
2229
2230/// Fold icmp (mul X, Y), C.
2233 const APInt &C) {
2234 ICmpInst::Predicate Pred = Cmp.getPredicate();
2235 Type *MulTy = Mul->getType();
2236 Value *X = Mul->getOperand(0);
2237
2238 // If comparing a square with a constant, try simplifying to comparing square
2239 // roots.
2240 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2241 APInt R = C.sqrtFloor();
2242 bool IsSqr = C == R * R;
2243
2244 // X * X eq/ne C
2245 if (Cmp.isEquality() &&
2246 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2247
2248 // If constant is not a square, eq/ne is false/true respectively
2249 if (!IsSqr)
2250 return replaceInstUsesWith(
2251 Cmp,
2252 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2253
2254 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2255 }
2256
2257 // If the multiply does not wrap
2258 // X * X pred C --> X pred R
2259 if (Mul->hasNoUnsignedWrap()) {
2260
2261 if (IsSqr)
2262 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2263
2264 // If C is not a square, we use floor/ceil of sqrt(C).
2265 //
2266 // If LT or LE, we need R to be an overestimate of sqrt(C),
2267 // then use the strict predicate (LT->LT, LE->LT).
2268 //
2269 // If GT or GE, we need R to be an underestimate of sqrt(C),
2270 // then use the strict predicate (GT->GT, GE->GT).
2271 //
2272 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2273 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2274 ++R;
2275
2276 return new ICmpInst(Cmp.getStrictPredicate(), X,
2277 ConstantInt::get(MulTy, R));
2278 }
2279 }
2280
2281 const APInt *MulC;
2282 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2283 return nullptr;
2284
2285 // If this is a test of the sign bit and the multiply is sign-preserving with
2286 // a constant operand, use the multiply LHS operand instead:
2287 // (X * +MulC) < 0 --> X < 0
2288 // (X * -MulC) < 0 --> X > 0
2289 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2290 if (MulC->isNegative())
2291 Pred = ICmpInst::getSwappedPredicate(Pred);
2292 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2293 }
2294
2295 if (MulC->isZero())
2296 return nullptr;
2297
2298 // If the multiply does not wrap or the constant is odd, try to divide the
2299 // compare constant by the multiplication factor.
2300 if (Cmp.isEquality()) {
2301 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2302 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2303 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2304 return new ICmpInst(Pred, X, NewC);
2305 }
2306
2307 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2308 // correct to transform if MulC * N == C including overflow. I.e with i8
2309 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2310 // miss that case.
2311 if (C.urem(*MulC).isZero()) {
2312 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2313 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2314 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2315 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2316 return new ICmpInst(Pred, X, NewC);
2317 }
2318 }
2319 }
2320
2321 // With a matching no-overflow guarantee, fold the constants:
2322 // (X * MulC) < C --> X < (C / MulC)
2323 // (X * MulC) > C --> X > (C / MulC)
2324 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2325 Constant *NewC = nullptr;
2326 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2327 // MININT / -1 --> overflow.
2328 if (C.isMinSignedValue() && MulC->isAllOnes())
2329 return nullptr;
2330 if (MulC->isNegative())
2331 Pred = ICmpInst::getSwappedPredicate(Pred);
2332
2333 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2334 NewC = ConstantInt::get(
2336 } else {
2337 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2338 "Unexpected predicate");
2339 NewC = ConstantInt::get(
2341 }
2342 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2343 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2344 NewC = ConstantInt::get(
2346 } else {
2347 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2348 "Unexpected predicate");
2349 NewC = ConstantInt::get(
2351 }
2352 }
2353
2354 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2355}
2356
2357/// Fold icmp (shl nuw C2, Y), C.
2359 const APInt &C) {
2360 Value *Y;
2361 const APInt *C2;
2362 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2363 return nullptr;
2364
2365 Type *ShiftType = Shl->getType();
2366 unsigned TypeBits = C.getBitWidth();
2367 ICmpInst::Predicate Pred = Cmp.getPredicate();
2368 if (Cmp.isUnsigned()) {
2369 if (C2->isZero() || C2->ugt(C))
2370 return nullptr;
2371 APInt Div, Rem;
2372 APInt::udivrem(C, *C2, Div, Rem);
2373 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2374
2375 // (1 << Y) pred C -> Y pred Log2(C)
2376 if (!CIsPowerOf2) {
2377 // (1 << Y) < 30 -> Y <= 4
2378 // (1 << Y) <= 30 -> Y <= 4
2379 // (1 << Y) >= 30 -> Y > 4
2380 // (1 << Y) > 30 -> Y > 4
2381 if (Pred == ICmpInst::ICMP_ULT)
2382 Pred = ICmpInst::ICMP_ULE;
2383 else if (Pred == ICmpInst::ICMP_UGE)
2384 Pred = ICmpInst::ICMP_UGT;
2385 }
2386
2387 unsigned CLog2 = Div.logBase2();
2388 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2389 } else if (Cmp.isSigned() && C2->isOne()) {
2390 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2391 // (1 << Y) > 0 -> Y != 31
2392 // (1 << Y) > C -> Y != 31 if C is negative.
2393 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2394 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2395
2396 // (1 << Y) < 0 -> Y == 31
2397 // (1 << Y) < 1 -> Y == 31
2398 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2399 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2400 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2401 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2402 }
2403
2404 return nullptr;
2405}
2406
2407/// Fold icmp (shl X, Y), C.
2409 BinaryOperator *Shl,
2410 const APInt &C) {
2411 const APInt *ShiftVal;
2412 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2413 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2414
2415 ICmpInst::Predicate Pred = Cmp.getPredicate();
2416 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2417 // -> (icmp pred X, Csle0)
2418 //
2419 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2420 // so X's must be what is used.
2421 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2422 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2423
2424 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2425 // -> (icmp eq/ne X, 0)
2426 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2427 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2428 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2429
2430 // (icmp slt (shl nsw X, Y), 0/1)
2431 // -> (icmp slt X, 0/1)
2432 // (icmp sgt (shl nsw X, Y), 0/-1)
2433 // -> (icmp sgt X, 0/-1)
2434 //
2435 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2436 if (Shl->hasNoSignedWrap() &&
2437 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2438 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2439 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2440
2441 const APInt *ShiftAmt;
2442 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2443 return foldICmpShlLHSC(Cmp, Shl, C);
2444
2445 // Check that the shift amount is in range. If not, don't perform undefined
2446 // shifts. When the shift is visited, it will be simplified.
2447 unsigned TypeBits = C.getBitWidth();
2448 if (ShiftAmt->uge(TypeBits))
2449 return nullptr;
2450
2451 Value *X = Shl->getOperand(0);
2452 Type *ShType = Shl->getType();
2453
2454 // NSW guarantees that we are only shifting out sign bits from the high bits,
2455 // so we can ASHR the compare constant without needing a mask and eliminate
2456 // the shift.
2457 if (Shl->hasNoSignedWrap()) {
2458 if (Pred == ICmpInst::ICMP_SGT) {
2459 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2460 APInt ShiftedC = C.ashr(*ShiftAmt);
2461 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2462 }
2463 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2464 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2465 APInt ShiftedC = C.ashr(*ShiftAmt);
2466 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2467 }
2468 if (Pred == ICmpInst::ICMP_SLT) {
2469 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2470 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2471 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2472 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2473 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2474 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2475 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2476 }
2477 }
2478
2479 // NUW guarantees that we are only shifting out zero bits from the high bits,
2480 // so we can LSHR the compare constant without needing a mask and eliminate
2481 // the shift.
2482 if (Shl->hasNoUnsignedWrap()) {
2483 if (Pred == ICmpInst::ICMP_UGT) {
2484 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2485 APInt ShiftedC = C.lshr(*ShiftAmt);
2486 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2487 }
2488 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2489 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2490 APInt ShiftedC = C.lshr(*ShiftAmt);
2491 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2492 }
2493 if (Pred == ICmpInst::ICMP_ULT) {
2494 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2495 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2496 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2497 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2498 assert(C.ugt(0) && "ult 0 should have been eliminated");
2499 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2500 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2501 }
2502 }
2503
2504 if (Cmp.isEquality() && Shl->hasOneUse()) {
2505 // Strength-reduce the shift into an 'and'.
2506 Constant *Mask = ConstantInt::get(
2507 ShType,
2508 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2509 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2510 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2511 return new ICmpInst(Pred, And, LShrC);
2512 }
2513
2514 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2515 bool TrueIfSigned = false;
2516 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2517 // (X << 31) <s 0 --> (X & 1) != 0
2518 Constant *Mask = ConstantInt::get(
2519 ShType,
2520 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2521 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2522 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2523 And, Constant::getNullValue(ShType));
2524 }
2525
2526 // Simplify 'shl' inequality test into 'and' equality test.
2527 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2528 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2529 if ((C + 1).isPowerOf2() &&
2530 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2531 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2532 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2534 And, Constant::getNullValue(ShType));
2535 }
2536 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2537 if (C.isPowerOf2() &&
2538 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2539 Value *And =
2540 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2541 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2543 And, Constant::getNullValue(ShType));
2544 }
2545 }
2546
2547 // Transform (icmp pred iM (shl iM %v, N), C)
2548 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2549 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2550 // This enables us to get rid of the shift in favor of a trunc that may be
2551 // free on the target. It has the additional benefit of comparing to a
2552 // smaller constant that may be more target-friendly.
2553 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2554 if (Shl->hasOneUse() && Amt != 0 &&
2555 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2556 ICmpInst::Predicate CmpPred = Pred;
2557 APInt RHSC = C;
2558
2559 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2560 // Try the flipped strictness predicate.
2561 // e.g.:
2562 // icmp ult i64 (shl X, 32), 8589934593 ->
2563 // icmp ule i64 (shl X, 32), 8589934592 ->
2564 // icmp ule i32 (trunc X, i32), 2 ->
2565 // icmp ult i32 (trunc X, i32), 3
2566 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2567 Pred, ConstantInt::get(ShType->getContext(), C))) {
2568 CmpPred = FlippedStrictness->first;
2569 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2570 }
2571 }
2572
2573 if (RHSC.countr_zero() >= Amt) {
2574 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2575 Constant *NewC =
2576 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2577 return new ICmpInst(CmpPred,
2578 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2579 Shl->hasNoSignedWrap()),
2580 NewC);
2581 }
2582 }
2583
2584 return nullptr;
2585}
2586
2587/// Fold icmp ({al}shr X, Y), C.
2589 BinaryOperator *Shr,
2590 const APInt &C) {
2591 // An exact shr only shifts out zero bits, so:
2592 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2593 Value *X = Shr->getOperand(0);
2594 CmpInst::Predicate Pred = Cmp.getPredicate();
2595 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2596 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2597
2598 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2599 const APInt *ShiftValC;
2600 if (match(X, m_APInt(ShiftValC))) {
2601 if (Cmp.isEquality())
2602 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2603
2604 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2605 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2606 bool TrueIfSigned;
2607 if (!IsAShr && ShiftValC->isNegative() &&
2608 isSignBitCheck(Pred, C, TrueIfSigned))
2609 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2610 Shr->getOperand(1),
2611 ConstantInt::getNullValue(X->getType()));
2612
2613 // If the shifted constant is a power-of-2, test the shift amount directly:
2614 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2615 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2616 if (!IsAShr && ShiftValC->isPowerOf2() &&
2617 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2618 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2619 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2620 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2621
2622 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2623 unsigned ShiftLZ = ShiftValC->countl_zero();
2624 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2625 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2626 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2627 }
2628 }
2629
2630 const APInt *ShiftAmtC;
2631 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2632 return nullptr;
2633
2634 // Check that the shift amount is in range. If not, don't perform undefined
2635 // shifts. When the shift is visited it will be simplified.
2636 unsigned TypeBits = C.getBitWidth();
2637 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2638 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2639 return nullptr;
2640
2641 bool IsExact = Shr->isExact();
2642 Type *ShrTy = Shr->getType();
2643 // TODO: If we could guarantee that InstSimplify would handle all of the
2644 // constant-value-based preconditions in the folds below, then we could assert
2645 // those conditions rather than checking them. This is difficult because of
2646 // undef/poison (PR34838).
2647 if (IsAShr && Shr->hasOneUse()) {
2648 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2649 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2650 // When C - 1 is a power of two and the transform can be legally
2651 // performed, prefer this form so the produced constant is close to a
2652 // power of two.
2653 // icmp slt/ult (ashr exact X, ShAmtC), C
2654 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2655 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2656 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2657 }
2658 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2659 // When ShAmtC can be shifted losslessly:
2660 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2661 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2662 APInt ShiftedC = C.shl(ShAmtVal);
2663 if (ShiftedC.ashr(ShAmtVal) == C)
2664 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2665 }
2666 if (Pred == CmpInst::ICMP_SGT) {
2667 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2668 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2669 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2670 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2671 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2672 }
2673 if (Pred == CmpInst::ICMP_UGT) {
2674 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2675 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2676 // clause accounts for that pattern.
2677 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2678 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2679 (C + 1).shl(ShAmtVal).isMinSignedValue())
2680 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2681 }
2682
2683 // If the compare constant has significant bits above the lowest sign-bit,
2684 // then convert an unsigned cmp to a test of the sign-bit:
2685 // (ashr X, ShiftC) u> C --> X s< 0
2686 // (ashr X, ShiftC) u< C --> X s> -1
2687 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2688 if (Pred == CmpInst::ICMP_UGT) {
2689 return new ICmpInst(CmpInst::ICMP_SLT, X,
2691 }
2692 if (Pred == CmpInst::ICMP_ULT) {
2693 return new ICmpInst(CmpInst::ICMP_SGT, X,
2695 }
2696 }
2697 } else if (!IsAShr) {
2698 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2699 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2700 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2701 APInt ShiftedC = C.shl(ShAmtVal);
2702 if (ShiftedC.lshr(ShAmtVal) == C)
2703 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2704 }
2705 if (Pred == CmpInst::ICMP_UGT) {
2706 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2707 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2708 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2709 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2710 }
2711 }
2712
2713 if (!Cmp.isEquality())
2714 return nullptr;
2715
2716 // Handle equality comparisons of shift-by-constant.
2717
2718 // If the comparison constant changes with the shift, the comparison cannot
2719 // succeed (bits of the comparison constant cannot match the shifted value).
2720 // This should be known by InstSimplify and already be folded to true/false.
2721 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2722 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2723 "Expected icmp+shr simplify did not occur.");
2724
2725 // If the bits shifted out are known zero, compare the unshifted value:
2726 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2727 if (Shr->isExact())
2728 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2729
2730 if (Shr->hasOneUse()) {
2731 // Canonicalize the shift into an 'and':
2732 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2733 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2734 Constant *Mask = ConstantInt::get(ShrTy, Val);
2735 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2736 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2737 }
2738
2739 return nullptr;
2740}
2741
2743 BinaryOperator *SRem,
2744 const APInt &C) {
2745 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2746 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2747 // Canonicalize unsigned predicates to signed:
2748 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2749 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2750 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2751 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2752
2753 const APInt *DivisorC;
2754 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2755 return nullptr;
2756 if (DivisorC->isZero())
2757 return nullptr;
2758
2759 APInt NormalizedC = C;
2760 if (Pred == ICmpInst::ICMP_ULT) {
2761 assert(!NormalizedC.isZero() &&
2762 "ult X, 0 should have been simplified already.");
2763 --NormalizedC;
2764 }
2765 if (C.isNegative())
2766 NormalizedC.flipAllBits();
2767 if (!NormalizedC.uge(DivisorC->abs() - 1))
2768 return nullptr;
2769
2770 Type *Ty = SRem->getType();
2771 if (Pred == ICmpInst::ICMP_UGT)
2772 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2774 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2776 }
2777 // Match an 'is positive' or 'is negative' comparison of remainder by a
2778 // constant power-of-2 value:
2779 // (X % pow2C) sgt/slt 0
2780 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2781 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2782 return nullptr;
2783
2784 // TODO: The one-use check is standard because we do not typically want to
2785 // create longer instruction sequences, but this might be a special-case
2786 // because srem is not good for analysis or codegen.
2787 if (!SRem->hasOneUse())
2788 return nullptr;
2789
2790 const APInt *DivisorC;
2791 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2792 return nullptr;
2793
2794 // For cmp_sgt/cmp_slt only zero valued C is handled.
2795 // For cmp_eq/cmp_ne only positive valued C is handled.
2796 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2797 !C.isZero()) ||
2798 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2799 !C.isStrictlyPositive()))
2800 return nullptr;
2801
2802 // Mask off the sign bit and the modulo bits (low-bits).
2803 Type *Ty = SRem->getType();
2804 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2805 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2806 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2807
2808 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2809 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2810
2811 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2812 // bit is set. Example:
2813 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2814 if (Pred == ICmpInst::ICMP_SGT)
2816
2817 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2818 // bit is set. Example:
2819 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2820 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2821}
2822
2823/// Fold icmp (udiv X, Y), C.
2825 BinaryOperator *UDiv,
2826 const APInt &C) {
2827 ICmpInst::Predicate Pred = Cmp.getPredicate();
2828 Value *X = UDiv->getOperand(0);
2829 Value *Y = UDiv->getOperand(1);
2830 Type *Ty = UDiv->getType();
2831
2832 const APInt *C2;
2833 if (!match(X, m_APInt(C2)))
2834 return nullptr;
2835
2836 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2837
2838 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2839 if (Pred == ICmpInst::ICMP_UGT) {
2840 assert(!C.isMaxValue() &&
2841 "icmp ugt X, UINT_MAX should have been simplified already.");
2842 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2843 ConstantInt::get(Ty, C2->udiv(C + 1)));
2844 }
2845
2846 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2847 if (Pred == ICmpInst::ICMP_ULT) {
2848 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2849 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2850 ConstantInt::get(Ty, C2->udiv(C)));
2851 }
2852
2853 return nullptr;
2854}
2855
2856/// Fold icmp ({su}div X, Y), C.
2858 BinaryOperator *Div,
2859 const APInt &C) {
2860 ICmpInst::Predicate Pred = Cmp.getPredicate();
2861 Value *X = Div->getOperand(0);
2862 Value *Y = Div->getOperand(1);
2863 Type *Ty = Div->getType();
2864 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2865
2866 // If unsigned division and the compare constant is bigger than
2867 // UMAX/2 (negative), there's only one pair of values that satisfies an
2868 // equality check, so eliminate the division:
2869 // (X u/ Y) == C --> (X == C) && (Y == 1)
2870 // (X u/ Y) != C --> (X != C) || (Y != 1)
2871 // Similarly, if signed division and the compare constant is exactly SMIN:
2872 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2873 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2874 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2875 (!DivIsSigned || C.isMinSignedValue())) {
2876 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2877 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2878 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2879 return BinaryOperator::Create(Logic, XBig, YOne);
2880 }
2881
2882 // Fold: icmp pred ([us]div X, C2), C -> range test
2883 // Fold this div into the comparison, producing a range check.
2884 // Determine, based on the divide type, what the range is being
2885 // checked. If there is an overflow on the low or high side, remember
2886 // it, otherwise compute the range [low, hi) bounding the new value.
2887 // See: InsertRangeTest above for the kinds of replacements possible.
2888 const APInt *C2;
2889 if (!match(Y, m_APInt(C2)))
2890 return nullptr;
2891
2892 // FIXME: If the operand types don't match the type of the divide
2893 // then don't attempt this transform. The code below doesn't have the
2894 // logic to deal with a signed divide and an unsigned compare (and
2895 // vice versa). This is because (x /s C2) <s C produces different
2896 // results than (x /s C2) <u C or (x /u C2) <s C or even
2897 // (x /u C2) <u C. Simply casting the operands and result won't
2898 // work. :( The if statement below tests that condition and bails
2899 // if it finds it.
2900 // However, when the divisor is a positive constant and the dividend is
2901 // known non-negative, sdiv is equivalent to udiv, so we can lower
2902 // DivIsSigned and proceed through the unsigned path.
2903 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2904 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2905 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2906 return nullptr;
2907 DivIsSigned = false;
2908 }
2909
2910 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2911 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2912 // division-by-constant cases should be present, we can not assert that they
2913 // have happened before we reach this icmp instruction.
2914 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2915 return nullptr;
2916
2917 // Compute Prod = C * C2. We are essentially solving an equation of
2918 // form X / C2 = C. We solve for X by multiplying C2 and C.
2919 // By solving for X, we can turn this into a range check instead of computing
2920 // a divide.
2921 APInt Prod = C * *C2;
2922
2923 // Determine if the product overflows by seeing if the product is not equal to
2924 // the divide. Make sure we do the same kind of divide as in the LHS
2925 // instruction that we're folding.
2926 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2927
2928 // If the division is known to be exact, then there is no remainder from the
2929 // divide, so the covered range size is unit, otherwise it is the divisor.
2930 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2931
2932 // Figure out the interval that is being checked. For example, a comparison
2933 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2934 // Compute this interval based on the constants involved and the signedness of
2935 // the compare/divide. This computes a half-open interval, keeping track of
2936 // whether either value in the interval overflows. After analysis each
2937 // overflow variable is set to 0 if it's corresponding bound variable is valid
2938 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2939 int LoOverflow = 0, HiOverflow = 0;
2940 APInt LoBound, HiBound;
2941
2942 if (!DivIsSigned) { // udiv
2943 // e.g. X/5 op 3 --> [15, 20)
2944 LoBound = Prod;
2945 HiOverflow = LoOverflow = ProdOV;
2946 if (!HiOverflow) {
2947 // If this is not an exact divide, then many values in the range collapse
2948 // to the same result value.
2949 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2950 }
2951 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2952 if (C.isZero()) { // (X / pos) op 0
2953 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2954 LoBound = -(RangeSize - 1);
2955 HiBound = RangeSize;
2956 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2957 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2958 HiOverflow = LoOverflow = ProdOV;
2959 if (!HiOverflow)
2960 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2961 } else { // (X / pos) op neg
2962 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2963 HiBound = Prod + 1;
2964 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2965 if (!LoOverflow) {
2966 APInt DivNeg = -RangeSize;
2967 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2968 }
2969 }
2970 } else if (C2->isNegative()) { // Divisor is < 0.
2971 if (Div->isExact())
2972 RangeSize.negate();
2973 if (C.isZero()) { // (X / neg) op 0
2974 // e.g. X/-5 op 0 --> [-4, 5)
2975 LoBound = RangeSize + 1;
2976 HiBound = -RangeSize;
2977 if (HiBound == *C2) { // -INTMIN = INTMIN
2978 HiOverflow = 1; // [INTMIN+1, overflow)
2979 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2980 }
2981 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2982 // e.g. X/-5 op 3 --> [-19, -14)
2983 HiBound = Prod + 1;
2984 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2985 if (!LoOverflow)
2986 LoOverflow =
2987 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2988 } else { // (X / neg) op neg
2989 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2990 LoOverflow = HiOverflow = ProdOV;
2991 if (!HiOverflow)
2992 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2993 }
2994
2995 // Dividing by a negative swaps the condition. LT <-> GT
2996 Pred = ICmpInst::getSwappedPredicate(Pred);
2997 }
2998
2999 switch (Pred) {
3000 default:
3001 llvm_unreachable("Unhandled icmp predicate!");
3002 case ICmpInst::ICMP_EQ:
3003 if (LoOverflow && HiOverflow)
3004 return replaceInstUsesWith(Cmp, Builder.getFalse());
3005 if (HiOverflow)
3006 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3007 X, ConstantInt::get(Ty, LoBound));
3008 if (LoOverflow)
3009 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3010 X, ConstantInt::get(Ty, HiBound));
3011 return replaceInstUsesWith(
3012 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
3013 case ICmpInst::ICMP_NE:
3014 if (LoOverflow && HiOverflow)
3015 return replaceInstUsesWith(Cmp, Builder.getTrue());
3016 if (HiOverflow)
3017 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3018 X, ConstantInt::get(Ty, LoBound));
3019 if (LoOverflow)
3020 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3021 X, ConstantInt::get(Ty, HiBound));
3022 return replaceInstUsesWith(
3023 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
3024 case ICmpInst::ICMP_ULT:
3025 case ICmpInst::ICMP_SLT:
3026 if (LoOverflow == +1) // Low bound is greater than input range.
3027 return replaceInstUsesWith(Cmp, Builder.getTrue());
3028 if (LoOverflow == -1) // Low bound is less than input range.
3029 return replaceInstUsesWith(Cmp, Builder.getFalse());
3030 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3031 case ICmpInst::ICMP_UGT:
3032 case ICmpInst::ICMP_SGT:
3033 if (HiOverflow == +1) // High bound greater than input range.
3034 return replaceInstUsesWith(Cmp, Builder.getFalse());
3035 if (HiOverflow == -1) // High bound less than input range.
3036 return replaceInstUsesWith(Cmp, Builder.getTrue());
3037 if (Pred == ICmpInst::ICMP_UGT)
3038 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3039 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3040 }
3041
3042 return nullptr;
3043}
3044
3045/// Fold icmp (sub X, Y), C.
3048 const APInt &C) {
3049 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3050 ICmpInst::Predicate Pred = Cmp.getPredicate();
3051 Type *Ty = Sub->getType();
3052
3053 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3054 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3055 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3056 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3057 const APInt *D;
3058 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3059 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3060 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3061 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3062 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3063 }
3064
3065 // (SubC - Y) == C) --> Y == (SubC - C)
3066 // (SubC - Y) != C) --> Y != (SubC - C)
3067 Constant *SubC;
3068 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3069 return new ICmpInst(Pred, Y,
3070 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3071 }
3072
3073 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3074 const APInt *C2;
3075 APInt SubResult;
3076 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3077 bool HasNSW = Sub->hasNoSignedWrap();
3078 bool HasNUW = Sub->hasNoUnsignedWrap();
3079 if (match(X, m_APInt(C2)) &&
3080 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3081 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3082 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3083
3084 // X - Y == 0 --> X == Y.
3085 // X - Y != 0 --> X != Y.
3086 // TODO: We allow this with multiple uses as long as the other uses are not
3087 // in phis. The phi use check is guarding against a codegen regression
3088 // for a loop test. If the backend could undo this (and possibly
3089 // subsequent transforms), we would not need this hack.
3090 if (Cmp.isEquality() && C.isZero() &&
3091 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3092 return new ICmpInst(Pred, X, Y);
3093
3094 // The following transforms are only worth it if the only user of the subtract
3095 // is the icmp.
3096 // TODO: This is an artificial restriction for all of the transforms below
3097 // that only need a single replacement icmp. Can these use the phi test
3098 // like the transform above here?
3099 if (!Sub->hasOneUse())
3100 return nullptr;
3101
3102 if (Sub->hasNoSignedWrap()) {
3103 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3104 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3105 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3106
3107 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3108 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3109 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3110
3111 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3112 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3113 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3114
3115 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3116 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3117 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3118 }
3119
3120 if (!match(X, m_APInt(C2)))
3121 return nullptr;
3122
3123 // C2 - Y <u C -> (Y | (C - 1)) == C2
3124 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3125 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3126 (*C2 & (C - 1)) == (C - 1))
3127 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3128
3129 // C2 - Y >u C -> (Y | C) != C2
3130 // iff C2 & C == C and C + 1 is a power of 2
3131 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3132 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3133
3134 // We have handled special cases that reduce.
3135 // Canonicalize any remaining sub to add as:
3136 // (C2 - Y) > C --> (Y + ~C2) < ~C
3137 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3138 HasNUW, HasNSW);
3139 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3140}
3141
3142static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3143 Value *Op1, IRBuilderBase &Builder,
3144 bool HasOneUse) {
3145 auto FoldConstant = [&](bool Val) {
3146 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3147 if (Op0->getType()->isVectorTy())
3149 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3150 return Res;
3151 };
3152
3153 switch (Table.to_ulong()) {
3154 case 0: // 0 0 0 0
3155 return FoldConstant(false);
3156 case 1: // 0 0 0 1
3157 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3158 case 2: // 0 0 1 0
3159 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3160 case 3: // 0 0 1 1
3161 return Builder.CreateNot(Op0);
3162 case 4: // 0 1 0 0
3163 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3164 case 5: // 0 1 0 1
3165 return Builder.CreateNot(Op1);
3166 case 6: // 0 1 1 0
3167 return Builder.CreateXor(Op0, Op1);
3168 case 7: // 0 1 1 1
3169 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3170 case 8: // 1 0 0 0
3171 return Builder.CreateAnd(Op0, Op1);
3172 case 9: // 1 0 0 1
3173 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3174 case 10: // 1 0 1 0
3175 return Op1;
3176 case 11: // 1 0 1 1
3177 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3178 case 12: // 1 1 0 0
3179 return Op0;
3180 case 13: // 1 1 0 1
3181 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3182 case 14: // 1 1 1 0
3183 return Builder.CreateOr(Op0, Op1);
3184 case 15: // 1 1 1 1
3185 return FoldConstant(true);
3186 default:
3187 llvm_unreachable("Invalid Operation");
3188 }
3189 return nullptr;
3190}
3191
3193 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3194 Value *A, *B;
3195 Constant *C1, *C2, *C3, *C4;
3196 if (!match(BO->getOperand(0),
3198 !match(BO->getOperand(1),
3200 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3201 return nullptr;
3202
3203 std::bitset<4> Table;
3204 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3205 Constant *L = First ? C1 : C2;
3206 Constant *R = Second ? C3 : C4;
3207 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3208 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3209 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3210 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3211 }
3212 return std::nullopt;
3213 };
3214
3215 for (unsigned I = 0; I < 4; ++I) {
3216 bool First = (I >> 1) & 1;
3217 bool Second = I & 1;
3218 if (auto Res = ComputeTable(First, Second))
3219 Table[I] = *Res;
3220 else
3221 return nullptr;
3222 }
3223
3224 // Synthesize optimal logic.
3225 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3226 return replaceInstUsesWith(Cmp, Cond);
3227 return nullptr;
3228}
3229
3230/// Fold icmp (add X, Y), C.
3233 const APInt &C) {
3234 Value *Y = Add->getOperand(1);
3235 Value *X = Add->getOperand(0);
3236 const CmpPredicate Pred = Cmp.getCmpPredicate();
3237
3238 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3239 // when C <= (1 << ShAmtC).
3240 const APInt *ShAmtC;
3241 Value *A;
3242 unsigned BitWidth = C.getBitWidth();
3243 if (Pred == ICmpInst::ICMP_ULT &&
3244 match(Add,
3245 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3246 ShAmtC->ult(BitWidth) &&
3247 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3248 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3249
3250 const APInt *C2;
3251 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3252 return nullptr;
3253
3254 // Fold icmp pred (add X, C2), C.
3255 Type *Ty = Add->getType();
3256
3257 // If the add does not wrap, we can always adjust the compare by subtracting
3258 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3259 // have been canonicalized to SGT/SLT/UGT/ULT.
3260 if (Add->hasNoUnsignedWrap() &&
3261 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3262 bool Overflow;
3263 APInt NewC = C.usub_ov(*C2, Overflow);
3264 // If there is overflow, the result must be true or false.
3265 if (!Overflow)
3266 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3267 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3268 }
3269
3270 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3271
3272 if (Add->hasNoSignedWrap() &&
3273 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3274 bool Overflow;
3275 APInt NewC = C.ssub_ov(*C2, Overflow);
3276 if (!Overflow)
3277 // icmp samesign ugt/ult (add nsw X, C2), C
3278 // -> icmp sgt/slt X, (C - C2)
3279 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3280 }
3281
3282 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3283 C.isNonNegative() && (C - *C2).isNonNegative() &&
3284 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3285 .add(*C2)
3286 .isAllNonNegative())
3287 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3288 ConstantInt::get(Ty, C - *C2));
3289
3290 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3291 const APInt &Upper = CR.getUpper();
3292 const APInt &Lower = CR.getLower();
3293 if (Cmp.isSigned()) {
3294 if (Lower.isSignMask())
3295 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3296 if (Upper.isSignMask())
3297 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3298 } else {
3299 if (Lower.isMinValue())
3300 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3301 if (Upper.isMinValue())
3302 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3303 }
3304
3305 // This set of folds is intentionally placed after folds that use no-wrapping
3306 // flags because those folds are likely better for later analysis/codegen.
3307 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3308 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3309
3310 // Fold compare with offset to opposite sign compare if it eliminates offset:
3311 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3312 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3313 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3314
3315 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3316 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3317 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3318
3319 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3320 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3321 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3322
3323 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3324 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3325 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3326
3327 // (X + -1) <u C --> X <=u C (if X is never null)
3328 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3329 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3330 if (llvm::isKnownNonZero(X, Q))
3331 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3332 }
3333
3334 if (!Add->hasOneUse())
3335 return nullptr;
3336
3337 // X+C <u C2 -> (X & -C2) == C
3338 // iff C & (C2-1) == 0
3339 // C2 is a power of 2
3340 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3341 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3343
3344 // X+C2 <u C -> (X & C) == 2C
3345 // iff C == -(C2)
3346 // C2 is a power of 2
3347 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3348 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3349 ConstantInt::get(Ty, C * 2));
3350
3351 // X+C >u C2 -> (X & ~C2) != C
3352 // iff C & C2 == 0
3353 // C2+1 is a power of 2
3354 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3355 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3357
3358 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3359 // to the ult form.
3360 // X+C2 >u C -> X+(C2-C-1) <u ~C
3361 if (Pred == ICmpInst::ICMP_UGT)
3362 return new ICmpInst(ICmpInst::ICMP_ULT,
3363 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3364 ConstantInt::get(Ty, ~C));
3365
3366 // zext(V) + C2 pred C -> V + C3 pred' C4
3367 Value *V;
3368 if (match(X, m_ZExt(m_Value(V)))) {
3369 Type *NewCmpTy = V->getType();
3370 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3371 if (shouldChangeType(Ty, NewCmpTy)) {
3372 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3373 CmpInst::Predicate EquivPred;
3374 APInt EquivInt;
3375 APInt EquivOffset;
3376
3377 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3378 return new ICmpInst(
3379 EquivPred,
3380 EquivOffset.isZero()
3381 ? V
3382 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3383 ConstantInt::get(NewCmpTy, EquivInt));
3384 }
3385 }
3386
3387 return nullptr;
3388}
3389
3391 Value *&RHS, ConstantInt *&Less,
3392 ConstantInt *&Equal,
3393 ConstantInt *&Greater) {
3394 // TODO: Generalize this to work with other comparison idioms or ensure
3395 // they get canonicalized into this form.
3396
3397 // select i1 (a == b),
3398 // i32 Equal,
3399 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3400 // where Equal, Less and Greater are placeholders for any three constants.
3401 CmpPredicate PredA;
3402 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3403 !ICmpInst::isEquality(PredA))
3404 return false;
3405 Value *EqualVal = SI->getTrueValue();
3406 Value *UnequalVal = SI->getFalseValue();
3407 // We still can get non-canonical predicate here, so canonicalize.
3408 if (PredA == ICmpInst::ICMP_NE)
3409 std::swap(EqualVal, UnequalVal);
3410 if (!match(EqualVal, m_ConstantInt(Equal)))
3411 return false;
3412 CmpPredicate PredB;
3413 Value *LHS2, *RHS2;
3414 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3415 m_ConstantInt(Less), m_ConstantInt(Greater))))
3416 return false;
3417 // We can get predicate mismatch here, so canonicalize if possible:
3418 // First, ensure that 'LHS' match.
3419 if (LHS2 != LHS) {
3420 // x sgt y <--> y slt x
3421 std::swap(LHS2, RHS2);
3422 PredB = ICmpInst::getSwappedPredicate(PredB);
3423 }
3424 if (LHS2 != LHS)
3425 return false;
3426 // We also need to canonicalize 'RHS'.
3427 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3428 // x sgt C-1 <--> x sge C <--> not(x slt C)
3429 auto FlippedStrictness =
3431 if (!FlippedStrictness)
3432 return false;
3433 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3434 "basic correctness failure");
3435 RHS2 = FlippedStrictness->second;
3436 // And kind-of perform the result swap.
3437 std::swap(Less, Greater);
3438 PredB = ICmpInst::ICMP_SLT;
3439 }
3440 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3441}
3442
3445 ConstantInt *C) {
3446
3447 assert(C && "Cmp RHS should be a constant int!");
3448 // If we're testing a constant value against the result of a three way
3449 // comparison, the result can be expressed directly in terms of the
3450 // original values being compared. Note: We could possibly be more
3451 // aggressive here and remove the hasOneUse test. The original select is
3452 // really likely to simplify or sink when we remove a test of the result.
3453 Value *OrigLHS, *OrigRHS;
3454 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3455 if (Cmp.hasOneUse() &&
3456 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3457 C3GreaterThan)) {
3458 assert(C1LessThan && C2Equal && C3GreaterThan);
3459
3460 bool TrueWhenLessThan = ICmpInst::compare(
3461 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3462 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3463 Cmp.getPredicate());
3464 bool TrueWhenGreaterThan = ICmpInst::compare(
3465 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3466
3467 // This generates the new instruction that will replace the original Cmp
3468 // Instruction. Instead of enumerating the various combinations when
3469 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3470 // false, we rely on chaining of ORs and future passes of InstCombine to
3471 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3472
3473 // When none of the three constants satisfy the predicate for the RHS (C),
3474 // the entire original Cmp can be simplified to a false.
3475 Value *Cond = Builder.getFalse();
3476 if (TrueWhenLessThan)
3477 Cond = Builder.CreateOr(
3478 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3479 if (TrueWhenEqual)
3480 Cond = Builder.CreateOr(
3481 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3482 if (TrueWhenGreaterThan)
3483 Cond = Builder.CreateOr(
3484 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3485
3486 return replaceInstUsesWith(Cmp, Cond);
3487 }
3488 return nullptr;
3489}
3490
3492 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3493 if (!Bitcast)
3494 return nullptr;
3495
3496 ICmpInst::Predicate Pred = Cmp.getPredicate();
3497 Value *Op1 = Cmp.getOperand(1);
3498 Value *BCSrcOp = Bitcast->getOperand(0);
3499 Type *SrcType = Bitcast->getSrcTy();
3500 Type *DstType = Bitcast->getType();
3501
3502 // Make sure the bitcast doesn't change between scalar and vector and
3503 // doesn't change the number of vector elements.
3504 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3505 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3506 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3507 Value *X;
3508 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3509 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3510 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3511 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3512 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3513 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3514 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3515 match(Op1, m_Zero()))
3516 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3517
3518 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3519 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3520 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3521
3522 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3523 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3524 return new ICmpInst(Pred, X,
3525 ConstantInt::getAllOnesValue(X->getType()));
3526 }
3527
3528 // Zero-equality checks are preserved through unsigned floating-point casts:
3529 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3530 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3531 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3532 if (Cmp.isEquality() && match(Op1, m_Zero()))
3533 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3534
3535 const APInt *C;
3536 bool TrueIfSigned;
3537 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3538 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3539 // the FP extend/truncate because that cast does not change the sign-bit.
3540 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3541 // The sign-bit is always the most significant bit in those types.
3542 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3543 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3544 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3545 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3546 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3547 Type *XType = X->getType();
3548
3549 // We can't currently handle Power style floating point operations here.
3550 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3551 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3552 if (auto *XVTy = dyn_cast<VectorType>(XType))
3553 NewType = VectorType::get(NewType, XVTy->getElementCount());
3554 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3555 if (TrueIfSigned)
3556 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3557 ConstantInt::getNullValue(NewType));
3558 else
3559 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3561 }
3562 }
3563
3564 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3565 Type *FPType = SrcType->getScalarType();
3566 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3567 Attribute::NoImplicitFloat) &&
3568 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3569 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3570 if (Mask & (fcInf | fcZero)) {
3571 if (Pred == ICmpInst::ICMP_NE)
3572 Mask = ~Mask;
3573 return replaceInstUsesWith(Cmp,
3574 Builder.createIsFPClass(BCSrcOp, Mask));
3575 }
3576 }
3577 }
3578 }
3579
3580 const APInt *C;
3581 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3582 !SrcType->isIntOrIntVectorTy())
3583 return nullptr;
3584
3585 // If this is checking if all elements of a vector compare are set or not,
3586 // invert the casted vector equality compare and test if all compare
3587 // elements are clear or not. Compare against zero is generally easier for
3588 // analysis and codegen.
3589 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3590 // Example: are all elements equal? --> are zero elements not equal?
3591 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3592 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3593 if (Value *NotBCSrcOp =
3594 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3595 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3596 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3597 }
3598 }
3599
3600 // If this is checking if all elements of an extended vector are clear or not,
3601 // compare in a narrow type to eliminate the extend:
3602 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3603 Value *X;
3604 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3605 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3606 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3607 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3608 Value *NewCast = Builder.CreateBitCast(X, NewType);
3609 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3610 }
3611 }
3612
3613 // Folding: icmp <pred> iN X, C
3614 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3615 // and C is a splat of a K-bit pattern
3616 // and SC is a constant vector = <C', C', C', ..., C'>
3617 // Into:
3618 // %E = extractelement <M x iK> %vec, i32 C'
3619 // icmp <pred> iK %E, trunc(C)
3620 Value *Vec;
3621 ArrayRef<int> Mask;
3622 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3623 // Check whether every element of Mask is the same constant
3624 if (all_equal(Mask)) {
3625 auto *VecTy = cast<VectorType>(SrcType);
3626 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3627 if (C->isSplat(EltTy->getBitWidth())) {
3628 // Fold the icmp based on the value of C
3629 // If C is M copies of an iK sized bit pattern,
3630 // then:
3631 // => %E = extractelement <N x iK> %vec, i64 Elem
3632 // icmp <pred> iK %SplatVal, <pattern>
3633 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3634 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3635 return new ICmpInst(Pred, Extract, NewC);
3636 }
3637 }
3638 }
3639 return nullptr;
3640}
3641
3642/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3643/// where X is some kind of instruction.
3645 const APInt *C;
3646
3647 if (match(Cmp.getOperand(1), m_APInt(C))) {
3648 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3649 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3650 return I;
3651
3652 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3653 // For now, we only support constant integers while folding the
3654 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3655 // similar to the cases handled by binary ops above.
3656 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3657 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3658 return I;
3659
3660 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3661 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3662 return I;
3663
3664 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3666 return I;
3667
3668 {
3669 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3670 // fcmp olt/oge (fabs X), 2^ExpVal
3671 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3672 Value *X;
3673 if (match(Cmp.getOperand(0),
3676 ICmpInst::Predicate Pred = Cmp.getPredicate();
3677 APInt Exp;
3678 FCmpInst::Predicate NewPred;
3679 bool ValidPred = true;
3680
3681 switch (Pred) {
3682 case ICmpInst::ICMP_SLT:
3683 NewPred = FCmpInst::FCMP_OLT;
3684 Exp = *C - 1;
3685 break;
3686 case ICmpInst::ICMP_SGT:
3687 NewPred = FCmpInst::FCMP_OGE;
3688 Exp = *C;
3689 break;
3690 default:
3691 ValidPred = false;
3692 break;
3693 }
3694
3695 if (ValidPred) {
3696 const fltSemantics &Sem =
3697 X->getType()->getScalarType()->getFltSemantics();
3698 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3699
3700 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3701 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3702 int ExpVal = static_cast<int>(Exp.getSExtValue());
3703 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3705 Value *Fabs = Builder.CreateFAbs(X);
3706 return new FCmpInst(NewPred, Fabs,
3707 ConstantFP::get(X->getType(), CmpConst));
3708 }
3709 }
3710 }
3711 }
3712
3713 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3714 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3715 // TODO: This checks one-use, but that is not strictly necessary.
3716 Value *Cmp0 = Cmp.getOperand(0);
3717 Value *X, *Y;
3718 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3719 (match(Cmp0,
3721 m_Value(X), m_Value(Y)))) ||
3722 match(Cmp0,
3724 m_Value(X), m_Value(Y))))))
3725 return new ICmpInst(Cmp.getPredicate(), X, Y);
3726 }
3727
3728 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3730
3731 return nullptr;
3732}
3733
3734/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3735/// icmp eq/ne BO, C.
3737 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3738 // TODO: Some of these folds could work with arbitrary constants, but this
3739 // function is limited to scalar and vector splat constants.
3740 if (!Cmp.isEquality())
3741 return nullptr;
3742
3743 ICmpInst::Predicate Pred = Cmp.getPredicate();
3744 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3745 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3746 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3747
3748 switch (BO->getOpcode()) {
3749 case Instruction::SRem:
3750 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3751 if (C.isZero() && BO->hasOneUse()) {
3752 const APInt *BOC;
3753 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3754 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3755 return new ICmpInst(Pred, NewRem,
3757 }
3758 }
3759 break;
3760 case Instruction::Add: {
3761 // (A + C2) == C --> A == (C - C2)
3762 // (A + C2) != C --> A != (C - C2)
3763 // TODO: Remove the one-use limitation? See discussion in D58633.
3764 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3765 if (BO->hasOneUse())
3766 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3767 } else if (C.isZero()) {
3768 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3769 // efficiently invertible, or if the add has just this one use.
3770 if (Value *NegVal = dyn_castNegVal(BOp1))
3771 return new ICmpInst(Pred, BOp0, NegVal);
3772 if (Value *NegVal = dyn_castNegVal(BOp0))
3773 return new ICmpInst(Pred, NegVal, BOp1);
3774 if (BO->hasOneUse()) {
3775 // (add nuw A, B) != 0 -> (or A, B) != 0
3776 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3777 Value *Or = Builder.CreateOr(BOp0, BOp1);
3778 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3779 }
3780 Value *Neg = Builder.CreateNeg(BOp1);
3781 Neg->takeName(BO);
3782 return new ICmpInst(Pred, BOp0, Neg);
3783 }
3784 }
3785 break;
3786 }
3787 case Instruction::Xor:
3788 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3789 // For the xor case, we can xor two constants together, eliminating
3790 // the explicit xor.
3791 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3792 } else if (C.isZero()) {
3793 // Replace ((xor A, B) != 0) with (A != B)
3794 return new ICmpInst(Pred, BOp0, BOp1);
3795 }
3796 break;
3797 case Instruction::Or: {
3798 const APInt *BOC;
3799 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3800 // Comparing if all bits outside of a constant mask are set?
3801 // Replace (X | C) == -1 with (X & ~C) == ~C.
3802 // This removes the -1 constant.
3804 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3805 return new ICmpInst(Pred, And, NotBOC);
3806 }
3807 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3808 // -> (and cond, (icmp eq Other, 0))
3809 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3810 // -> (or cond, (icmp ne Other, 0))
3811 Value *Cond, *TV, *FV, *Other, *Sel;
3812 if (C.isZero() &&
3813 match(BO,
3816 m_Value(FV))),
3817 m_Value(Other)))) &&
3818 Cond->getType() == Cmp.getType()) {
3819 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3820 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3821 if (Pred == ICmpInst::ICMP_EQ
3822 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3823 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3824 Value *Cmp = Builder.CreateICmp(
3825 Pred, Other, Constant::getNullValue(Other->getType()));
3827 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3828 Cond);
3829 }
3830 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3831 // case we need to invert the select condition so we need to be careful to
3832 // avoid creating extra instructions.
3833 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3834 // -> (or (not cond), (icmp ne Other, 0))
3835 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3836 // -> (and (not cond), (icmp eq Other, 0))
3837 //
3838 // Only do this if the inner select has one use, in which case we are
3839 // replacing `select` with `(not cond)`. Otherwise, we will create more
3840 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3841 // cond was freely invertable, the select arms would have been inverted.
3842 if (Sel->hasOneUse() &&
3843 (Pred == ICmpInst::ICMP_EQ
3844 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3845 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3846 Value *NotCond = Builder.CreateNot(Cond);
3847 Value *Cmp = Builder.CreateICmp(
3848 Pred, Other, Constant::getNullValue(Other->getType()));
3850 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3851 NotCond);
3852 }
3853 }
3854 break;
3855 }
3856 case Instruction::UDiv:
3857 case Instruction::SDiv:
3858 if (BO->isExact()) {
3859 // div exact X, Y eq/ne 0 -> X eq/ne 0
3860 // div exact X, Y eq/ne 1 -> X eq/ne Y
3861 // div exact X, Y eq/ne C ->
3862 // if Y * C never-overflow && OneUse:
3863 // -> Y * C eq/ne X
3864 if (C.isZero())
3865 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3866 else if (C.isOne())
3867 return new ICmpInst(Pred, BOp0, BOp1);
3868 else if (BO->hasOneUse()) {
3870 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3871 Cmp.getOperand(1), BO);
3873 Value *YC =
3874 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3875 return new ICmpInst(Pred, YC, BOp0);
3876 }
3877 }
3878 }
3879 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3880 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3881 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3882 return new ICmpInst(NewPred, BOp1, BOp0);
3883 }
3884 break;
3885 default:
3886 break;
3887 }
3888 return nullptr;
3889}
3890
3892 const APInt &CRhs,
3893 InstCombiner::BuilderTy &Builder,
3894 const SimplifyQuery &Q) {
3895 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3896 "Non-ctpop intrin in ctpop fold");
3897 if (!CtpopLhs->hasOneUse())
3898 return nullptr;
3899
3900 // Power of 2 test:
3901 // isPow2OrZero : ctpop(X) u< 2
3902 // isPow2 : ctpop(X) == 1
3903 // NotPow2OrZero: ctpop(X) u> 1
3904 // NotPow2 : ctpop(X) != 1
3905 // If we know any bit of X can be folded to:
3906 // IsPow2 : X & (~Bit) == 0
3907 // NotPow2 : X & (~Bit) != 0
3908 const ICmpInst::Predicate Pred = I.getPredicate();
3909 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3910 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3911 Value *Op = CtpopLhs->getArgOperand(0);
3912 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CtxI, Q.DT);
3913 // No need to check for count > 1, that should be already constant folded.
3914 if (OpKnown.countMinPopulation() == 1) {
3915 Value *And = Builder.CreateAnd(
3916 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3917 return new ICmpInst(
3918 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3921 And, Constant::getNullValue(Op->getType()));
3922 }
3923 }
3924
3925 return nullptr;
3926}
3927
3928/// Fold an equality icmp with LLVM intrinsic and constant operand.
3930 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3931 Type *Ty = II->getType();
3932 unsigned BitWidth = C.getBitWidth();
3933 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3934
3935 switch (II->getIntrinsicID()) {
3936 case Intrinsic::abs:
3937 // abs(A) == 0 -> A == 0
3938 // abs(A) == INT_MIN -> A == INT_MIN
3939 if (C.isZero() || C.isMinSignedValue())
3940 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3941 break;
3942
3943 case Intrinsic::bswap:
3944 // bswap(A) == C -> A == bswap(C)
3945 return new ICmpInst(Pred, II->getArgOperand(0),
3946 ConstantInt::get(Ty, C.byteSwap()));
3947
3948 case Intrinsic::bitreverse:
3949 // bitreverse(A) == C -> A == bitreverse(C)
3950 return new ICmpInst(Pred, II->getArgOperand(0),
3951 ConstantInt::get(Ty, C.reverseBits()));
3952
3953 case Intrinsic::ctlz:
3954 case Intrinsic::cttz: {
3955 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3956 if (C == BitWidth)
3957 return new ICmpInst(Pred, II->getArgOperand(0),
3959
3960 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3961 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3962 // Limit to one use to ensure we don't increase instruction count.
3963 unsigned Num = C.getLimitedValue(BitWidth);
3964 if (Num != BitWidth && II->hasOneUse()) {
3965 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3966 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3967 : APInt::getHighBitsSet(BitWidth, Num + 1);
3968 APInt Mask2 = IsTrailing
3971 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3972 ConstantInt::get(Ty, Mask2));
3973 }
3974 break;
3975 }
3976
3977 case Intrinsic::ctpop: {
3978 // popcount(A) == 0 -> A == 0 and likewise for !=
3979 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3980 bool IsZero = C.isZero();
3981 if (IsZero || C == BitWidth)
3982 return new ICmpInst(Pred, II->getArgOperand(0),
3983 IsZero ? Constant::getNullValue(Ty)
3985
3986 break;
3987 }
3988
3989 case Intrinsic::fshl:
3990 case Intrinsic::fshr:
3991 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3992 const APInt *RotAmtC;
3993 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3994 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3995 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3996 return new ICmpInst(Pred, II->getArgOperand(0),
3997 II->getIntrinsicID() == Intrinsic::fshl
3998 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3999 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
4000 }
4001 break;
4002
4003 case Intrinsic::umax:
4004 case Intrinsic::uadd_sat: {
4005 // uadd.sat(a, b) == 0 -> (a | b) == 0
4006 // umax(a, b) == 0 -> (a | b) == 0
4007 if (C.isZero() && II->hasOneUse()) {
4008 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4009 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4010 }
4011 break;
4012 }
4013
4014 case Intrinsic::ssub_sat:
4015 // ssub.sat(a, b) == 0 -> a == b
4016 //
4017 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4018 // (because 1 saturates to 0). Just skip the optimization for i1.
4019 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4020 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4021 break;
4022 case Intrinsic::usub_sat: {
4023 // usub.sat(a, b) == 0 -> a <= b
4024 if (C.isZero()) {
4025 ICmpInst::Predicate NewPred =
4027 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4028 }
4029 break;
4030 }
4031 default:
4032 break;
4033 }
4034
4035 return nullptr;
4036}
4037
4038/// Fold an icmp with LLVM intrinsics
4039static Instruction *
4041 InstCombiner::BuilderTy &Builder) {
4042 assert(Cmp.isEquality());
4043
4044 ICmpInst::Predicate Pred = Cmp.getPredicate();
4045 Value *Op0 = Cmp.getOperand(0);
4046 Value *Op1 = Cmp.getOperand(1);
4047 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4048 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4049 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4050 return nullptr;
4051
4052 switch (IIOp0->getIntrinsicID()) {
4053 case Intrinsic::bswap:
4054 case Intrinsic::bitreverse:
4055 // If both operands are byte-swapped or bit-reversed, just compare the
4056 // original values.
4057 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4058 case Intrinsic::fshl:
4059 case Intrinsic::fshr: {
4060 // If both operands are rotated by same amount, just compare the
4061 // original values.
4062 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4063 break;
4064 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4065 break;
4066 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4067 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4068
4069 // rotate(X, AmtX) == rotate(Y, AmtY)
4070 // -> rotate(X, AmtX - AmtY) == Y
4071 // Do this if either both rotates have one use or if only one has one use
4072 // and AmtX/AmtY are constants.
4073 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4074 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4075 if (OneUses == 2 ||
4076 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4077 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4078
4079 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4080 // of two.
4081 if (isPowerOf2_32(BW)) {
4082 Value *SubAmt =
4083 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4084 Value *CombinedRotate = Builder.CreateIntrinsic(
4085 Op0->getType(), IIOp0->getIntrinsicID(),
4086 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4087 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4088 }
4089 }
4090 } break;
4091 default:
4092 break;
4093 }
4094
4095 return nullptr;
4096}
4097
4098/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4099/// where X is some kind of instruction and C is AllowPoison.
4100/// TODO: Move more folds which allow poison to this function.
4103 const APInt &C) {
4104 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4105 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4106 switch (II->getIntrinsicID()) {
4107 default:
4108 break;
4109 case Intrinsic::fshl:
4110 case Intrinsic::fshr:
4111 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4112 // (rot X, ?) == 0/-1 --> X == 0/-1
4113 if (C.isZero() || C.isAllOnes())
4114 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4115 }
4116 break;
4117 }
4118 }
4119
4120 return nullptr;
4121}
4122
4123/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4125 BinaryOperator *BO,
4126 const APInt &C) {
4127 switch (BO->getOpcode()) {
4128 case Instruction::Xor:
4129 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4130 return I;
4131 break;
4132 case Instruction::And:
4133 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4134 return I;
4135 break;
4136 case Instruction::Or:
4137 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4138 return I;
4139 break;
4140 case Instruction::Mul:
4141 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4142 return I;
4143 break;
4144 case Instruction::Shl:
4145 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4146 return I;
4147 break;
4148 case Instruction::LShr:
4149 case Instruction::AShr:
4150 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4151 return I;
4152 break;
4153 case Instruction::SRem:
4154 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4155 return I;
4156 break;
4157 case Instruction::UDiv:
4158 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4159 return I;
4160 [[fallthrough]];
4161 case Instruction::SDiv:
4162 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4163 return I;
4164 break;
4165 case Instruction::Sub:
4166 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4167 return I;
4168 break;
4169 case Instruction::Add:
4170 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4171 return I;
4172 break;
4173 default:
4174 break;
4175 }
4176
4177 // TODO: These folds could be refactored to be part of the above calls.
4179 return I;
4180
4181 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4182 // : C4), C5` pattern, by computing a truth table of the four constant
4183 // variants.
4185}
4186
4187static Instruction *
4189 const APInt &C,
4190 InstCombiner::BuilderTy &Builder) {
4191 // This transform may end up producing more than one instruction for the
4192 // intrinsic, so limit it to one user of the intrinsic.
4193 if (!II->hasOneUse())
4194 return nullptr;
4195
4196 // Let Y = [add/sub]_sat(X, C) pred C2
4197 // SatVal = The saturating value for the operation
4198 // WillWrap = Whether or not the operation will underflow / overflow
4199 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4200 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4201 //
4202 // When (SatVal pred C2) is true, then
4203 // Y = WillWrap ? true : ((X binop C) pred C2)
4204 // => Y = WillWrap || ((X binop C) pred C2)
4205 // else
4206 // Y = WillWrap ? false : ((X binop C) pred C2)
4207 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4208 // => Y = !WillWrap && ((X binop C) pred C2)
4209 Value *Op0 = II->getOperand(0);
4210 Value *Op1 = II->getOperand(1);
4211
4212 const APInt *COp1;
4213 // This transform only works when the intrinsic has an integral constant or
4214 // splat vector as the second operand.
4215 if (!match(Op1, m_APInt(COp1)))
4216 return nullptr;
4217
4218 APInt SatVal;
4219 switch (II->getIntrinsicID()) {
4220 default:
4222 "This function only works with usub_sat and uadd_sat for now!");
4223 case Intrinsic::uadd_sat:
4224 SatVal = APInt::getAllOnes(C.getBitWidth());
4225 break;
4226 case Intrinsic::usub_sat:
4227 SatVal = APInt::getZero(C.getBitWidth());
4228 break;
4229 }
4230
4231 // Check (SatVal pred C2)
4232 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4233
4234 // !WillWrap.
4236 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4237
4238 // WillWrap.
4239 if (SatValCheck)
4240 C1 = C1.inverse();
4241
4243 if (II->getBinaryOp() == Instruction::Add)
4244 C2 = C2.sub(*COp1);
4245 else
4246 C2 = C2.add(*COp1);
4247
4248 Instruction::BinaryOps CombiningOp =
4249 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4250
4251 std::optional<ConstantRange> Combination;
4252 if (CombiningOp == Instruction::BinaryOps::Or)
4253 Combination = C1.exactUnionWith(C2);
4254 else /* CombiningOp == Instruction::BinaryOps::And */
4255 Combination = C1.exactIntersectWith(C2);
4256
4257 if (!Combination)
4258 return nullptr;
4259
4260 CmpInst::Predicate EquivPred;
4261 APInt EquivInt;
4262 APInt EquivOffset;
4263
4264 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4265
4266 return new ICmpInst(
4267 EquivPred,
4268 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4269 ConstantInt::get(Op1->getType(), EquivInt));
4270}
4271
4272static Instruction *
4274 const APInt &C,
4275 InstCombiner::BuilderTy &Builder) {
4276 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4277 switch (Pred) {
4278 case ICmpInst::ICMP_EQ:
4279 case ICmpInst::ICMP_NE:
4280 if (C.isZero())
4281 NewPredicate = Pred;
4282 else if (C.isOne())
4283 NewPredicate =
4285 else if (C.isAllOnes())
4286 NewPredicate =
4288 break;
4289
4290 case ICmpInst::ICMP_SGT:
4291 if (C.isAllOnes())
4292 NewPredicate = ICmpInst::ICMP_UGE;
4293 else if (C.isZero())
4294 NewPredicate = ICmpInst::ICMP_UGT;
4295 break;
4296
4297 case ICmpInst::ICMP_SLT:
4298 if (C.isZero())
4299 NewPredicate = ICmpInst::ICMP_ULT;
4300 else if (C.isOne())
4301 NewPredicate = ICmpInst::ICMP_ULE;
4302 break;
4303
4304 case ICmpInst::ICMP_ULT:
4305 if (C.ugt(1))
4306 NewPredicate = ICmpInst::ICMP_UGE;
4307 break;
4308
4309 case ICmpInst::ICMP_UGT:
4310 if (!C.isZero() && !C.isAllOnes())
4311 NewPredicate = ICmpInst::ICMP_ULT;
4312 break;
4313
4314 default:
4315 break;
4316 }
4317
4318 if (!NewPredicate)
4319 return nullptr;
4320
4321 if (I->getIntrinsicID() == Intrinsic::scmp)
4322 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4323 Value *LHS = I->getOperand(0);
4324 Value *RHS = I->getOperand(1);
4325 return new ICmpInst(*NewPredicate, LHS, RHS);
4326}
4327
4328/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4331 const APInt &C) {
4332 ICmpInst::Predicate Pred = Cmp.getPredicate();
4333
4334 // Handle folds that apply for any kind of icmp.
4335 switch (II->getIntrinsicID()) {
4336 default:
4337 break;
4338 case Intrinsic::uadd_sat:
4339 case Intrinsic::usub_sat:
4340 if (auto *Folded = foldICmpUSubSatOrUAddSatWithConstant(
4341 Pred, cast<SaturatingInst>(II), C, Builder))
4342 return Folded;
4343 break;
4344 case Intrinsic::ctpop: {
4345 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4346 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4347 return R;
4348 } break;
4349 case Intrinsic::scmp:
4350 case Intrinsic::ucmp:
4351 if (auto *Folded = foldICmpOfCmpIntrinsicWithConstant(Pred, II, C, Builder))
4352 return Folded;
4353 break;
4354 }
4355
4356 if (Cmp.isEquality())
4357 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4358
4359 Type *Ty = II->getType();
4360 unsigned BitWidth = C.getBitWidth();
4361 switch (II->getIntrinsicID()) {
4362 case Intrinsic::ctpop: {
4363 // (ctpop X > BitWidth - 1) --> X == -1
4364 Value *X = II->getArgOperand(0);
4365 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4366 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4368 // (ctpop X < BitWidth) --> X != -1
4369 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4370 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4372 break;
4373 }
4374 case Intrinsic::ctlz: {
4375 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4376 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4377 unsigned Num = C.getLimitedValue();
4378 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4379 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4380 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4381 }
4382
4383 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4384 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4385 unsigned Num = C.getLimitedValue();
4387 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4388 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4389 }
4390 break;
4391 }
4392 case Intrinsic::cttz: {
4393 // Limit to one use to ensure we don't increase instruction count.
4394 if (!II->hasOneUse())
4395 return nullptr;
4396
4397 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4398 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4399 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4400 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4401 Builder.CreateAnd(II->getArgOperand(0), Mask),
4403 }
4404
4405 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4406 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4407 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4408 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4409 Builder.CreateAnd(II->getArgOperand(0), Mask),
4411 }
4412 break;
4413 }
4414 case Intrinsic::ssub_sat:
4415 // ssub.sat(a, b) spred 0 -> a spred b
4416 //
4417 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4418 // (because 1 saturates to 0). Just skip the optimization for i1.
4419 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4420 if (C.isZero())
4421 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4422 // X s<= 0 is cannonicalized to X s< 1
4423 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4424 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4425 II->getArgOperand(1));
4426 // X s>= 0 is cannonicalized to X s> -1
4427 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4428 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4429 II->getArgOperand(1));
4430 }
4431 break;
4432 case Intrinsic::abs: {
4433 if (!II->hasOneUse())
4434 return nullptr;
4435
4436 Value *X = II->getArgOperand(0);
4437
4438 // If C >= 0:
4439 // abs(X) u> C --> X + C u> 2 * C
4440 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4441 return new ICmpInst(ICmpInst::ICMP_UGT,
4442 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4443 ConstantInt::get(Ty, 2 * C));
4444 }
4445
4446 // If C >= 1:
4447 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4448 if (Pred == CmpInst::ICMP_ULT && C.sge(1))
4449 return new ICmpInst(ICmpInst::ICMP_ULE,
4450 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4451 ConstantInt::get(Ty, 2 * (C - 1)));
4452
4453 break;
4454 }
4455 default:
4456 break;
4457 }
4458
4459 return nullptr;
4460}
4461
4462/// Handle icmp with constant (but not simple integer constant) RHS.
4464 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4465 Constant *RHSC = dyn_cast<Constant>(Op1);
4467 if (!RHSC || !LHSI)
4468 return nullptr;
4469
4470 switch (LHSI->getOpcode()) {
4471 case Instruction::IntToPtr:
4472 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4473 if (isa<ConstantPointerNull>(RHSC)) {
4474 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4475 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4476 APInt NullPtrValue =
4477 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4478 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4479 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4480 }
4481 }
4482 break;
4483
4484 case Instruction::Load:
4485 // Try to optimize things like "A[i] > 4" to index computations.
4486 if (GetElementPtrInst *GEP =
4488 if (Instruction *Res =
4490 return Res;
4491 break;
4492 }
4493
4494 return nullptr;
4495}
4496
4498 Value *RHS, const ICmpInst &I) {
4499 // Try to fold the comparison into the select arms, which will cause the
4500 // select to be converted into a logical and/or.
4501 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4502 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4503 return Res;
4504 if (std::optional<bool> Impl = isImpliedCondition(
4505 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4506 return ConstantInt::get(I.getType(), *Impl);
4507 return nullptr;
4508 };
4509
4510 ConstantInt *CI = nullptr;
4511 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4512 if (Op1)
4513 CI = dyn_cast<ConstantInt>(Op1);
4514
4515 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4516 if (Op2)
4517 CI = dyn_cast<ConstantInt>(Op2);
4518
4519 auto Simplifies = [&](Value *Op, unsigned Idx) {
4520 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4521 const APInt *Dummy;
4522 return Op ||
4523 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4524 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4525 };
4526
4527 // We only want to perform this transformation if it will not lead to
4528 // additional code. This is true if either both sides of the select
4529 // fold to a constant (in which case the icmp is replaced with a select
4530 // which will usually simplify) or this is the only user of the
4531 // select (in which case we are trading a select+icmp for a simpler
4532 // select+icmp) or all uses of the select can be replaced based on
4533 // dominance information ("Global cases").
4534 bool Transform = false;
4535 if (Op1 && Op2)
4536 Transform = true;
4537 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4538 // Local case
4539 if (SI->hasOneUse())
4540 Transform = true;
4541 // Global cases
4542 else if (CI && !CI->isZero())
4543 // When Op1 is constant try replacing select with second operand.
4544 // Otherwise Op2 is constant and try replacing select with first
4545 // operand.
4546 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4547 }
4548 if (Transform) {
4549 if (!Op1)
4550 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4551 if (!Op2)
4552 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4553 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr, SI);
4554 }
4555
4556 // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
4557 // When the select condition compares X with a constant P and the select
4558 // arms are constants C1/C2, we can fold to a set membership test.
4559 // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
4560 // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
4561 if (ICmpInst::isEquality(Pred)) {
4562 CmpPredicate CondPred;
4563 const APInt *C1, *C2, *P;
4564 if (match(SI,
4565 m_OneUse(m_Select(m_ICmp(CondPred, m_Specific(RHS), m_APInt(P)),
4566 m_APInt(C1), m_APInt(C2))))) {
4567 bool C1SatisfiesCond = ICmpInst::compare(*C1, *P, CondPred);
4568 bool C2SatisfiesCond = ICmpInst::compare(*C2, *P, CondPred);
4569
4570 if (C1SatisfiesCond && !C2SatisfiesCond) {
4571 // X == select(cond, C1, C2) -> (X == C1) | (X == C2)
4572 // X != select(cond, C1, C2) -> (X != C1) & (X != C2)
4573 Value *Cmp1 = Builder.CreateICmp(Pred, RHS, SI->getTrueValue());
4574 Value *Cmp2 = Builder.CreateICmp(Pred, RHS, SI->getFalseValue());
4575 if (Pred == ICmpInst::ICMP_EQ)
4576 return BinaryOperator::CreateOr(Cmp1, Cmp2);
4577 return BinaryOperator::CreateAnd(Cmp1, Cmp2);
4578 }
4579 }
4580 }
4581
4582 return nullptr;
4583}
4584
4585// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4586static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4587 unsigned Depth = 0) {
4588 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4589 return true;
4590 if (V->getType()->getScalarSizeInBits() == 1)
4591 return true;
4593 return false;
4594 Value *X;
4596 if (!I)
4597 return false;
4598 switch (I->getOpcode()) {
4599 case Instruction::ZExt:
4600 // ZExt(Mask) is a Mask.
4601 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4602 case Instruction::SExt:
4603 // SExt(Mask) is a Mask.
4604 // SExt(~Mask) is a ~Mask.
4605 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4606 case Instruction::And:
4607 case Instruction::Or:
4608 // Mask0 | Mask1 is a Mask.
4609 // Mask0 & Mask1 is a Mask.
4610 // ~Mask0 | ~Mask1 is a ~Mask.
4611 // ~Mask0 & ~Mask1 is a ~Mask.
4612 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4613 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4614 case Instruction::Xor:
4615 if (match(V, m_Not(m_Value(X))))
4616 return isMaskOrZero(X, !Not, Q, Depth);
4617
4618 // (X ^ -X) is a ~Mask
4619 if (Not)
4620 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4621 // (X ^ (X - 1)) is a Mask
4622 else
4623 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4624 case Instruction::Select:
4625 // c ? Mask0 : Mask1 is a Mask.
4626 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4627 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4628 case Instruction::Shl:
4629 // (~Mask) << X is a ~Mask.
4630 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4631 case Instruction::LShr:
4632 // Mask >> X is a Mask.
4633 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4634 case Instruction::AShr:
4635 // Mask s>> X is a Mask.
4636 // ~Mask s>> X is a ~Mask.
4637 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4638 case Instruction::Add:
4639 // Pow2 - 1 is a Mask.
4640 if (!Not && match(I->getOperand(1), m_AllOnes()))
4641 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4642 Q.AC, Q.CtxI, Q.DT, Depth);
4643 break;
4644 case Instruction::Sub:
4645 // -Pow2 is a ~Mask.
4646 if (Not && match(I->getOperand(0), m_Zero()))
4647 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4648 Q.AC, Q.CtxI, Q.DT, Depth);
4649 break;
4650 case Instruction::Call: {
4651 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4652 switch (II->getIntrinsicID()) {
4653 // min/max(Mask0, Mask1) is a Mask.
4654 // min/max(~Mask0, ~Mask1) is a ~Mask.
4655 case Intrinsic::umax:
4656 case Intrinsic::smax:
4657 case Intrinsic::umin:
4658 case Intrinsic::smin:
4659 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4660 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4661
4662 // In the context of masks, bitreverse(Mask) == ~Mask
4663 case Intrinsic::bitreverse:
4664 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4665 default:
4666 break;
4667 }
4668 }
4669 break;
4670 }
4671 default:
4672 break;
4673 }
4674 return false;
4675}
4676
4677/// Some comparisons can be simplified.
4678/// In this case, we are looking for comparisons that look like
4679/// a check for a lossy truncation.
4680/// Folds:
4681/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4682/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4683/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4684/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4685/// Where Mask is some pattern that produces all-ones in low bits:
4686/// (-1 >> y)
4687/// ((-1 << y) >> y) <- non-canonical, has extra uses
4688/// ~(-1 << y)
4689/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4690/// The Mask can be a constant, too.
4691/// For some predicates, the operands are commutative.
4692/// For others, x can only be on a specific side.
4694 Value *Op1, const SimplifyQuery &Q,
4695 InstCombiner &IC) {
4696
4697 ICmpInst::Predicate DstPred;
4698 switch (Pred) {
4700 // x & Mask == x
4701 // x & ~Mask == 0
4702 // ~x | Mask == -1
4703 // -> x u<= Mask
4704 // x & ~Mask == ~Mask
4705 // -> ~Mask u<= x
4707 break;
4709 // x & Mask != x
4710 // x & ~Mask != 0
4711 // ~x | Mask != -1
4712 // -> x u> Mask
4713 // x & ~Mask != ~Mask
4714 // -> ~Mask u> x
4716 break;
4718 // x & Mask u< x
4719 // -> x u> Mask
4720 // x & ~Mask u< ~Mask
4721 // -> ~Mask u> x
4723 break;
4725 // x & Mask u>= x
4726 // -> x u<= Mask
4727 // x & ~Mask u>= ~Mask
4728 // -> ~Mask u<= x
4730 break;
4732 // x & Mask s< x [iff Mask s>= 0]
4733 // -> x s> Mask
4734 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4735 // -> ~Mask s> x
4737 break;
4739 // x & Mask s>= x [iff Mask s>= 0]
4740 // -> x s<= Mask
4741 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4742 // -> ~Mask s<= x
4744 break;
4745 default:
4746 // We don't support sgt,sle
4747 // ult/ugt are simplified to true/false respectively.
4748 return nullptr;
4749 }
4750
4751 Value *X, *M;
4752 // Put search code in lambda for early positive returns.
4753 auto IsLowBitMask = [&]() {
4754 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4755 X = Op1;
4756 // Look for: x & Mask pred x
4757 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4758 return !ICmpInst::isSigned(Pred) ||
4759 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4760 }
4761
4762 // Look for: x & ~Mask pred ~Mask
4763 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4764 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4765 }
4766 return false;
4767 }
4768 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4769 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4770
4771 auto Check = [&]() {
4772 // Look for: ~x | Mask == -1
4773 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4774 if (Value *NotX =
4775 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4776 X = NotX;
4777 return true;
4778 }
4779 }
4780 return false;
4781 };
4782 if (Check())
4783 return true;
4784 std::swap(X, M);
4785 return Check();
4786 }
4787 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4788 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4789 auto Check = [&]() {
4790 // Look for: x & ~Mask == 0
4791 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4792 if (Value *NotM =
4793 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4794 M = NotM;
4795 return true;
4796 }
4797 }
4798 return false;
4799 };
4800 if (Check())
4801 return true;
4802 std::swap(X, M);
4803 return Check();
4804 }
4805 return false;
4806 };
4807
4808 if (!IsLowBitMask())
4809 return nullptr;
4810
4811 return IC.Builder.CreateICmp(DstPred, X, M);
4812}
4813
4814/// Some comparisons can be simplified.
4815/// In this case, we are looking for comparisons that look like
4816/// a check for a lossy signed truncation.
4817/// Folds: (MaskedBits is a constant.)
4818/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4819/// Into:
4820/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4821/// Where KeptBits = bitwidth(%x) - MaskedBits
4822static Value *
4824 InstCombiner::BuilderTy &Builder) {
4825 CmpPredicate SrcPred;
4826 Value *X;
4827 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4828 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4829 if (!match(&I, m_c_ICmp(SrcPred,
4831 m_APInt(C1))),
4832 m_Deferred(X))))
4833 return nullptr;
4834
4835 // Potential handling of non-splats: for each element:
4836 // * if both are undef, replace with constant 0.
4837 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4838 // * if both are not undef, and are different, bailout.
4839 // * else, only one is undef, then pick the non-undef one.
4840
4841 // The shift amount must be equal.
4842 if (*C0 != *C1)
4843 return nullptr;
4844 const APInt &MaskedBits = *C0;
4845 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4846
4847 ICmpInst::Predicate DstPred;
4848 switch (SrcPred) {
4850 // ((%x << MaskedBits) a>> MaskedBits) == %x
4851 // =>
4852 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4854 break;
4856 // ((%x << MaskedBits) a>> MaskedBits) != %x
4857 // =>
4858 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4860 break;
4861 // FIXME: are more folds possible?
4862 default:
4863 return nullptr;
4864 }
4865
4866 auto *XType = X->getType();
4867 const unsigned XBitWidth = XType->getScalarSizeInBits();
4868 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4869 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4870
4871 // KeptBits = bitwidth(%x) - MaskedBits
4872 const APInt KeptBits = BitWidth - MaskedBits;
4873 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4874 // ICmpCst = (1 << KeptBits)
4875 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4876 assert(ICmpCst.isPowerOf2());
4877 // AddCst = (1 << (KeptBits-1))
4878 const APInt AddCst = ICmpCst.lshr(1);
4879 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4880
4881 // T0 = add %x, AddCst
4882 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4883 // T1 = T0 DstPred ICmpCst
4884 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4885
4886 return T1;
4887}
4888
4889// Given pattern:
4890// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4891// we should move shifts to the same hand of 'and', i.e. rewrite as
4892// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4893// We are only interested in opposite logical shifts here.
4894// One of the shifts can be truncated.
4895// If we can, we want to end up creating 'lshr' shift.
4896static Value *
4898 InstCombiner::BuilderTy &Builder) {
4899 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4900 !I.getOperand(0)->hasOneUse())
4901 return nullptr;
4902
4903 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4904
4905 // Look for an 'and' of two logical shifts, one of which may be truncated.
4906 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4907 Instruction *XShift, *MaybeTruncation, *YShift;
4908 if (!match(
4909 I.getOperand(0),
4910 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4912 m_AnyLogicalShift, m_Instruction(YShift))),
4913 m_Instruction(MaybeTruncation)))))
4914 return nullptr;
4915
4916 // We potentially looked past 'trunc', but only when matching YShift,
4917 // therefore YShift must have the widest type.
4918 Instruction *WidestShift = YShift;
4919 // Therefore XShift must have the shallowest type.
4920 // Or they both have identical types if there was no truncation.
4921 Instruction *NarrowestShift = XShift;
4922
4923 Type *WidestTy = WidestShift->getType();
4924 Type *NarrowestTy = NarrowestShift->getType();
4925 assert(NarrowestTy == I.getOperand(0)->getType() &&
4926 "We did not look past any shifts while matching XShift though.");
4927 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4928
4929 // If YShift is a 'lshr', swap the shifts around.
4930 if (match(YShift, m_LShr(m_Value(), m_Value())))
4931 std::swap(XShift, YShift);
4932
4933 // The shifts must be in opposite directions.
4934 auto XShiftOpcode = XShift->getOpcode();
4935 if (XShiftOpcode == YShift->getOpcode())
4936 return nullptr; // Do not care about same-direction shifts here.
4937
4938 Value *X, *XShAmt, *Y, *YShAmt;
4939 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4940 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4941
4942 // If one of the values being shifted is a constant, then we will end with
4943 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4944 // however, we will need to ensure that we won't increase instruction count.
4945 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4946 // At least one of the hands of the 'and' should be one-use shift.
4947 if (!match(I.getOperand(0),
4948 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4949 return nullptr;
4950 if (HadTrunc) {
4951 // Due to the 'trunc', we will need to widen X. For that either the old
4952 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4953 if (!MaybeTruncation->hasOneUse() &&
4954 !NarrowestShift->getOperand(1)->hasOneUse())
4955 return nullptr;
4956 }
4957 }
4958
4959 // We have two shift amounts from two different shifts. The types of those
4960 // shift amounts may not match. If that's the case let's bailout now.
4961 if (XShAmt->getType() != YShAmt->getType())
4962 return nullptr;
4963
4964 // As input, we have the following pattern:
4965 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4966 // We want to rewrite that as:
4967 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4968 // While we know that originally (Q+K) would not overflow
4969 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4970 // shift amounts. so it may now overflow in smaller bitwidth.
4971 // To ensure that does not happen, we need to ensure that the total maximal
4972 // shift amount is still representable in that smaller bit width.
4973 unsigned MaximalPossibleTotalShiftAmount =
4974 (WidestTy->getScalarSizeInBits() - 1) +
4975 (NarrowestTy->getScalarSizeInBits() - 1);
4976 APInt MaximalRepresentableShiftAmount =
4978 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
4979 return nullptr;
4980
4981 // Can we fold (XShAmt+YShAmt) ?
4982 auto *NewShAmt = dyn_cast_or_null<Constant>(
4983 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
4984 /*isNUW=*/false, SQ.getWithInstruction(&I)));
4985 if (!NewShAmt)
4986 return nullptr;
4987 if (NewShAmt->getType() != WidestTy) {
4988 NewShAmt =
4989 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
4990 if (!NewShAmt)
4991 return nullptr;
4992 }
4993 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
4994
4995 // Is the new shift amount smaller than the bit width?
4996 // FIXME: could also rely on ConstantRange.
4997 if (!match(NewShAmt,
4999 APInt(WidestBitWidth, WidestBitWidth))))
5000 return nullptr;
5001
5002 // An extra legality check is needed if we had trunc-of-lshr.
5003 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
5004 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5005 WidestShift]() {
5006 // It isn't obvious whether it's worth it to analyze non-constants here.
5007 // Also, let's basically give up on non-splat cases, pessimizing vectors.
5008 // If *any* of these preconditions matches we can perform the fold.
5009 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
5010 ? NewShAmt->getSplatValue()
5011 : NewShAmt;
5012 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
5013 if (NewShAmtSplat &&
5014 (NewShAmtSplat->isNullValue() ||
5015 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
5016 return true;
5017 // We consider *min* leading zeros so a single outlier
5018 // blocks the transform as opposed to allowing it.
5019 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
5021 unsigned MinLeadZero = Known.countMinLeadingZeros();
5022 // If the value being shifted has at most lowest bit set we can fold.
5023 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5024 if (MaxActiveBits <= 1)
5025 return true;
5026 // Precondition: NewShAmt u<= countLeadingZeros(C)
5027 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5028 return true;
5029 }
5030 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5032 unsigned MinLeadZero = Known.countMinLeadingZeros();
5033 // If the value being shifted has at most lowest bit set we can fold.
5034 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5035 if (MaxActiveBits <= 1)
5036 return true;
5037 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5038 if (NewShAmtSplat) {
5039 APInt AdjNewShAmt =
5040 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5041 if (AdjNewShAmt.ule(MinLeadZero))
5042 return true;
5043 }
5044 }
5045 return false; // Can't tell if it's ok.
5046 };
5047 if (!CanFold())
5048 return nullptr;
5049 }
5050
5051 // All good, we can do this fold.
5052 X = Builder.CreateZExt(X, WidestTy);
5053 Y = Builder.CreateZExt(Y, WidestTy);
5054 // The shift is the same that was for X.
5055 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5056 ? Builder.CreateLShr(X, NewShAmt)
5057 : Builder.CreateShl(X, NewShAmt);
5058 Value *T1 = Builder.CreateAnd(T0, Y);
5059 return Builder.CreateICmp(I.getPredicate(), T1,
5060 Constant::getNullValue(WidestTy));
5061}
5062
5063/// Fold
5064/// (-1 u/ x) u< y
5065/// ((x * y) ?/ x) != y
5066/// to
5067/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5068/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5069/// will mean that we are looking for the opposite answer.
5071 CmpPredicate Pred;
5072 Value *X, *Y;
5074 Instruction *Div;
5075 bool NeedNegation;
5076 // Look for: (-1 u/ x) u</u>= y
5077 if (!I.isEquality() &&
5078 match(&I, m_c_ICmp(Pred,
5080 m_Instruction(Div)),
5081 m_Value(Y)))) {
5082 Mul = nullptr;
5083
5084 // Are we checking that overflow does not happen, or does happen?
5085 switch (Pred) {
5087 NeedNegation = false;
5088 break; // OK
5090 NeedNegation = true;
5091 break; // OK
5092 default:
5093 return nullptr; // Wrong predicate.
5094 }
5095 } else // Look for: ((x * y) / x) !=/== y
5096 if (I.isEquality() &&
5097 match(&I, m_c_ICmp(Pred, m_Value(Y),
5100 m_Value(X)),
5102 m_Deferred(X))),
5103 m_Instruction(Div))))) {
5104 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5105 } else
5106 return nullptr;
5107
5109 // If the pattern included (x * y), we'll want to insert new instructions
5110 // right before that original multiplication so that we can replace it.
5111 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5112 if (MulHadOtherUses)
5113 Builder.SetInsertPoint(Mul);
5114
5115 Value *Call = Builder.CreateIntrinsic(
5116 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5117 : Intrinsic::smul_with_overflow,
5118 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5119
5120 // If the multiplication was used elsewhere, to ensure that we don't leave
5121 // "duplicate" instructions, replace uses of that original multiplication
5122 // with the multiplication result from the with.overflow intrinsic.
5123 if (MulHadOtherUses)
5124 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5125
5126 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5127 if (NeedNegation) // This technically increases instruction count.
5128 Res = Builder.CreateNot(Res, "mul.not.ov");
5129
5130 // If we replaced the mul, erase it. Do this after all uses of Builder,
5131 // as the mul is used as insertion point.
5132 if (MulHadOtherUses)
5134
5135 return Res;
5136}
5137
5139 InstCombiner::BuilderTy &Builder) {
5140 CmpPredicate Pred;
5141 Value *X;
5142 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5143
5144 if (ICmpInst::isSigned(Pred))
5145 Pred = ICmpInst::getSwappedPredicate(Pred);
5146 else if (ICmpInst::isUnsigned(Pred))
5147 Pred = ICmpInst::getSignedPredicate(Pred);
5148 // else for equality-comparisons just keep the predicate.
5149
5150 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5151 Constant::getNullValue(X->getType()), I.getName());
5152 }
5153
5154 // A value is not equal to its negation unless that value is 0 or
5155 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5156 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5157 ICmpInst::isEquality(Pred)) {
5158 Type *Ty = X->getType();
5159 uint32_t BitWidth = Ty->getScalarSizeInBits();
5160 Constant *MaxSignedVal =
5161 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5162 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5163 Constant *Zero = Constant::getNullValue(Ty);
5164 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5165 }
5166
5167 return nullptr;
5168}
5169
5171 InstCombinerImpl &IC) {
5172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5173 // Normalize and operand as operand 0.
5174 CmpInst::Predicate Pred = I.getPredicate();
5175 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5176 std::swap(Op0, Op1);
5177 Pred = ICmpInst::getSwappedPredicate(Pred);
5178 }
5179
5180 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5181 return nullptr;
5182
5183 // (icmp (X & Y) u< X --> (X & Y) != X
5184 if (Pred == ICmpInst::ICMP_ULT)
5185 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5186
5187 // (icmp (X & Y) u>= X --> (X & Y) == X
5188 if (Pred == ICmpInst::ICMP_UGE)
5189 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5190
5191 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5192 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5193 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5194 // so don't do this fold.
5195 if (!match(Op1, m_ImmConstant()))
5196 if (auto *NotOp1 =
5197 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5198 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5199 Constant::getAllOnesValue(Op1->getType()));
5200 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5201 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5202 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5203 Constant::getNullValue(Op1->getType()));
5204 }
5205
5206 if (!ICmpInst::isSigned(Pred))
5207 return nullptr;
5208
5209 KnownBits KnownY = IC.computeKnownBits(A, &I);
5210 // (X & NegY) spred X --> (X & NegY) upred X
5211 if (KnownY.isNegative())
5212 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5213
5214 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5215 return nullptr;
5216
5217 if (KnownY.isNonNegative())
5218 // (X & PosY) s<= X --> X s>= 0
5219 // (X & PosY) s> X --> X s< 0
5220 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5221 Constant::getNullValue(Op1->getType()));
5222
5224 // (NegX & Y) s<= NegX --> Y s< 0
5225 // (NegX & Y) s> NegX --> Y s>= 0
5227 Constant::getNullValue(A->getType()));
5228
5229 return nullptr;
5230}
5231
5233 InstCombinerImpl &IC) {
5234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5235
5236 // Normalize or operand as operand 0.
5237 CmpInst::Predicate Pred = I.getPredicate();
5238 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5239 std::swap(Op0, Op1);
5240 Pred = ICmpInst::getSwappedPredicate(Pred);
5241 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5242 return nullptr;
5243 }
5244
5245 // icmp (X | Y) u<= X --> (X | Y) == X
5246 if (Pred == ICmpInst::ICMP_ULE)
5247 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5248
5249 // icmp (X | Y) u> X --> (X | Y) != X
5250 if (Pred == ICmpInst::ICMP_UGT)
5251 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5252
5253 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5254 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5255 if (Value *NotOp1 = IC.getFreelyInverted(
5256 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5257 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5258 Constant::getNullValue(Op1->getType()));
5259 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5260 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5261 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5262 Constant::getAllOnesValue(Op1->getType()));
5263 }
5264 return nullptr;
5265}
5266
5268 InstCombinerImpl &IC) {
5269 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5270 // Normalize xor operand as operand 0.
5271 CmpInst::Predicate Pred = I.getPredicate();
5272 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5273 std::swap(Op0, Op1);
5274 Pred = ICmpInst::getSwappedPredicate(Pred);
5275 }
5276 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5277 return nullptr;
5278
5279 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5280 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5281 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5282 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5284 if (PredOut != Pred && isKnownNonZero(A, Q))
5285 return new ICmpInst(PredOut, Op0, Op1);
5286
5287 // These transform work when A is negative.
5288 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5289 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5290 if (match(A, m_Negative())) {
5291 CmpInst::Predicate NewPred;
5292 switch (ICmpInst::getStrictPredicate(Pred)) {
5293 default:
5294 return nullptr;
5295 case ICmpInst::ICMP_SLT:
5296 case ICmpInst::ICMP_UGT:
5297 NewPred = ICmpInst::ICMP_SLT;
5298 break;
5299 case ICmpInst::ICMP_SGT:
5300 case ICmpInst::ICMP_ULT:
5301 NewPred = ICmpInst::ICMP_SGE;
5302 break;
5303 }
5304 Constant *Const = Constant::getNullValue(Op0->getType());
5305 return new ICmpInst(NewPred, Op0, Const);
5306 }
5307
5308 return nullptr;
5309}
5310
5311/// Return true if X is a multiple of C.
5312/// TODO: Handle non-power-of-2 factors.
5313static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5314 if (C.isOne())
5315 return true;
5316
5317 if (!C.isPowerOf2())
5318 return false;
5319
5320 return MaskedValueIsZero(X, C - 1, Q);
5321}
5322
5323/// Try to fold icmp (binop), X or icmp X, (binop).
5324/// TODO: A large part of this logic is duplicated in InstSimplify's
5325/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5326/// duplication.
5328 const SimplifyQuery &SQ) {
5329 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5331
5332 // Special logic for binary operators.
5335 if (!BO0 && !BO1)
5336 return nullptr;
5337
5338 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5339 return NewICmp;
5340
5341 const CmpInst::Predicate Pred = I.getPredicate();
5342
5343 // (X urem Y) == X --> X u< Y
5344 // (X urem Y) != X --> X u>= Y
5345 Value *Dividend, *Divisor;
5346 if (I.isEquality() &&
5347 match(&I, m_c_ICmp(m_URem(m_Value(Dividend), m_Value(Divisor)),
5348 m_Deferred(Dividend)))) {
5349 CmpInst::Predicate NewPred =
5351 return new ICmpInst(NewPred, Dividend, Divisor);
5352 }
5353
5354 Value *X;
5355
5356 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5357 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5358 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5359 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5360 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5361 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5362 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5363 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5364 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5365
5366 {
5367 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5368 Constant *C;
5369 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5370 m_ImmConstant(C)))) &&
5371 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5373 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5374 }
5375 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5376 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5377 m_ImmConstant(C)))) &&
5378 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5380 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5381 }
5382 }
5383
5384 // (icmp eq/ne (X, -P2), INT_MIN)
5385 // -> (icmp slt/sge X, INT_MIN + P2)
5386 if (ICmpInst::isEquality(Pred) && BO0 &&
5387 match(I.getOperand(1), m_SignMask()) &&
5389 // Will Constant fold.
5390 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5391 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5393 BO0->getOperand(0), NewC);
5394 }
5395
5396 {
5397 // Similar to above: an unsigned overflow comparison may use offset + mask:
5398 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5399 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5400 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5401 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5402 BinaryOperator *BO;
5403 const APInt *C;
5404 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5405 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5407 CmpInst::Predicate NewPred =
5409 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5410 return new ICmpInst(NewPred, Op1, Zero);
5411 }
5412
5413 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5414 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5416 CmpInst::Predicate NewPred =
5418 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5419 return new ICmpInst(NewPred, Op0, Zero);
5420 }
5421 }
5422
5423 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5424 bool Op0HasNUW = false, Op1HasNUW = false;
5425 bool Op0HasNSW = false, Op1HasNSW = false;
5426 // Analyze the case when either Op0 or Op1 is an add instruction.
5427 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5428 auto hasNoWrapProblem = [](const BinaryOperator &BO, CmpInst::Predicate Pred,
5429 bool &HasNSW, bool &HasNUW) -> bool {
5431 HasNUW = BO.hasNoUnsignedWrap();
5432 HasNSW = BO.hasNoSignedWrap();
5433 return ICmpInst::isEquality(Pred) ||
5434 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5435 (CmpInst::isSigned(Pred) && HasNSW);
5436 } else if (BO.getOpcode() == Instruction::Or) {
5437 // The invariant here is that we are handling m_AddLike instructions,
5438 // which can only be a or disjoint, which is equivalent to an add nuw nsw.
5439 HasNUW = true;
5440 HasNSW = true;
5441 return true;
5442 } else {
5443 return false;
5444 }
5445 };
5446 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5447
5448 if (BO0) {
5449 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5450 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5451 }
5452 if (BO1) {
5453 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5454 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5455 }
5456
5457 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5458 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5459 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5460 return new ICmpInst(Pred, A == Op1 ? B : A,
5461 Constant::getNullValue(Op1->getType()));
5462
5463 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5464 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5465 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5466 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5467 C == Op0 ? D : C);
5468
5469 // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
5470 if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
5471 NoOp1WrapProblem) {
5472 // Determine Y and Z in the form icmp (X+Y), (X+Z).
5473 Value *Y, *Z;
5474 if (A == C) {
5475 // C + B == C + D -> B == D
5476 Y = B;
5477 Z = D;
5478 } else if (A == D) {
5479 // D + B == C + D -> B == C
5480 Y = B;
5481 Z = C;
5482 } else if (B == C) {
5483 // A + C == C + D -> A == D
5484 Y = A;
5485 Z = D;
5486 } else {
5487 assert(B == D);
5488 // A + D == C + D -> A == C
5489 Y = A;
5490 Z = C;
5491 }
5492 return new ICmpInst(Pred, Y, Z);
5493 }
5494
5495 if (ICmpInst::isRelational(Pred)) {
5496 // Return if both X and Y is divisible by Z/-Z.
5497 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5498 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5499 bool IsNegative) -> bool {
5500 const APInt *OffsetC;
5501 if (!match(Z, m_APInt(OffsetC)))
5502 return false;
5503
5504 // Fast path for Z == 1/-1.
5505 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5506 return true;
5507
5508 APInt C = *OffsetC;
5509 if (IsNegative)
5510 C.negate();
5511 // Note: -INT_MIN is also negative.
5512 if (!C.isStrictlyPositive())
5513 return false;
5514
5515 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5516 };
5517
5518 // The subtraction-related identities (A -nuw B) shown below require that
5519 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5520 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5521 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5522 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5523 // requires proving A <u B, for which the nowrap precondition can never be
5524 // satisfied. These are therefore skipped.
5525 //
5526 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5527 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5528 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5529 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5530
5531 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5532 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5533 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5534 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5535 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5536 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5537 bool IsNegative = ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred);
5538 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5539 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5540 ShareCommonDivisor(A, Op1, B, IsNegative))
5542 Op1);
5543
5544 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5545 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5546 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5547 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5548 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5549 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5550 if (C && NoOp1WrapProblem &&
5551 ShareCommonDivisor(Op0, C, D,
5552 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5554 C);
5555 }
5556
5557 // if C1 has greater magnitude than C2:
5558 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5559 // s.t. C3 = C1 - C2
5560 //
5561 // if C2 has greater magnitude than C1:
5562 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5563 // s.t. C3 = C2 - C1
5564 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5565 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5566 const APInt *AP1, *AP2;
5567 // TODO: Support non-uniform vectors.
5568 // TODO: Allow poison passthrough if B or D's element is poison.
5569 if (match(B, m_APIntAllowPoison(AP1)) &&
5570 match(D, m_APIntAllowPoison(AP2)) &&
5571 AP1->isNegative() == AP2->isNegative()) {
5572 APInt AP1Abs = AP1->abs();
5573 APInt AP2Abs = AP2->abs();
5574 if (AP1Abs.uge(AP2Abs)) {
5575 APInt Diff = *AP1 - *AP2;
5576 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5577 Value *NewAdd = Builder.CreateAdd(
5578 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5579 return new ICmpInst(Pred, NewAdd, C);
5580 } else {
5581 APInt Diff = *AP2 - *AP1;
5582 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5583 Value *NewAdd = Builder.CreateAdd(
5584 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5585 return new ICmpInst(Pred, A, NewAdd);
5586 }
5587 }
5588 Constant *Cst1, *Cst2;
5589 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5590 ICmpInst::isEquality(Pred)) {
5591 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5592 Value *NewAdd = Builder.CreateAdd(C, Diff);
5593 return new ICmpInst(Pred, A, NewAdd);
5594 }
5595 }
5596
5597 // Analyze the case when either Op0 or Op1 is a sub instruction.
5598 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5599 A = nullptr;
5600 B = nullptr;
5601 C = nullptr;
5602 D = nullptr;
5603 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5604 A = BO0->getOperand(0);
5605 B = BO0->getOperand(1);
5606 }
5607 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5608 C = BO1->getOperand(0);
5609 D = BO1->getOperand(1);
5610 }
5611
5612 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5613 if (A == Op1 && NoOp0WrapProblem)
5614 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5615 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5616 if (C == Op0 && NoOp1WrapProblem)
5617 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5618
5619 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5620 // (A - B) u>/u<= A --> B u>/u<= A
5621 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5622 return new ICmpInst(Pred, B, A);
5623 // C u</u>= (C - D) --> C u</u>= D
5624 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5625 return new ICmpInst(Pred, C, D);
5626 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5627 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5628 isKnownNonZero(B, Q))
5630 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5631 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5632 isKnownNonZero(D, Q))
5634
5635 // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
5636 if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
5637 return new ICmpInst(Pred, A, C);
5638
5639 // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
5640 if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
5641 return new ICmpInst(Pred, D, B);
5642
5643 // icmp (0-X) < cst --> x > -cst
5644 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5645 Value *X;
5646 if (match(BO0, m_Neg(m_Value(X))))
5647 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5648 if (RHSC->isNotMinSignedValue())
5649 return new ICmpInst(I.getSwappedPredicate(), X,
5650 ConstantExpr::getNeg(RHSC));
5651 }
5652
5653 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5654 return R;
5655 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5656 return R;
5657
5658 {
5659 // Try to remove shared multiplier from comparison:
5660 // X * Z pred Y * Z
5661 Value *X, *Y, *Z;
5662 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5663 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5664 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5665 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5666 if (ICmpInst::isSigned(Pred)) {
5667 if (Op0HasNSW && Op1HasNSW) {
5668 KnownBits ZKnown = computeKnownBits(Z, &I);
5669 if (ZKnown.isStrictlyPositive())
5670 return new ICmpInst(Pred, X, Y);
5671 if (ZKnown.isNegative())
5672 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), X, Y);
5674 SQ.getWithInstruction(&I));
5675 if (LessThan && match(LessThan, m_One()))
5676 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5677 Constant::getNullValue(Z->getType()));
5678 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5679 SQ.getWithInstruction(&I));
5680 if (GreaterThan && match(GreaterThan, m_One()))
5681 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5682 }
5683 } else {
5684 bool NonZero;
5685 if (ICmpInst::isEquality(Pred)) {
5686 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5687 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5688 isKnownNonEqual(X, Y, SQ))
5689 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5690
5691 KnownBits ZKnown = computeKnownBits(Z, &I);
5692 // if Z % 2 != 0
5693 // X * Z eq/ne Y * Z -> X eq/ne Y
5694 if (ZKnown.countMaxTrailingZeros() == 0)
5695 return new ICmpInst(Pred, X, Y);
5696 NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5697 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5698 // X * Z eq/ne Y * Z -> X eq/ne Y
5699 if (NonZero && BO0 && BO1 && Op0HasNSW && Op1HasNSW)
5700 return new ICmpInst(Pred, X, Y);
5701 } else
5702 NonZero = isKnownNonZero(Z, Q);
5703
5704 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5705 // X * Z u{lt/le/gt/ge}/eq/ne Y * Z -> X u{lt/le/gt/ge}/eq/ne Y
5706 if (NonZero && BO0 && BO1 && Op0HasNUW && Op1HasNUW)
5707 return new ICmpInst(Pred, X, Y);
5708 }
5709 }
5710 }
5711
5712 BinaryOperator *SRem = nullptr;
5713 // icmp (srem X, Y), Y
5714 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5715 SRem = BO0;
5716 // icmp Y, (srem X, Y)
5717 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5718 Op0 == BO1->getOperand(1))
5719 SRem = BO1;
5720 if (SRem) {
5721 // We don't check hasOneUse to avoid increasing register pressure because
5722 // the value we use is the same value this instruction was already using.
5723 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5724 default:
5725 break;
5726 case ICmpInst::ICMP_EQ:
5727 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5728 case ICmpInst::ICMP_NE:
5729 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5730 case ICmpInst::ICMP_SGT:
5731 case ICmpInst::ICMP_SGE:
5732 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5734 case ICmpInst::ICMP_SLT:
5735 case ICmpInst::ICMP_SLE:
5736 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5738 }
5739 }
5740
5741 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5742 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5743 BO0->getOperand(1) == BO1->getOperand(1)) {
5744 switch (BO0->getOpcode()) {
5745 default:
5746 break;
5747 case Instruction::Add:
5748 case Instruction::Sub:
5749 case Instruction::Xor: {
5750 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5751 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5752
5753 const APInt *C;
5754 if (match(BO0->getOperand(1), m_APInt(C))) {
5755 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5756 if (C->isSignMask()) {
5757 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5758 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5759 }
5760
5761 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5762 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5763 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5764 NewPred = I.getSwappedPredicate(NewPred);
5765 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5766 }
5767 }
5768 break;
5769 }
5770 case Instruction::Mul: {
5771 if (!I.isEquality())
5772 break;
5773
5774 const APInt *C;
5775 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5776 !C->isOne()) {
5777 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5778 // Mask = -1 >> count-trailing-zeros(C).
5779 if (unsigned TZs = C->countr_zero()) {
5780 Constant *Mask = ConstantInt::get(
5781 BO0->getType(),
5782 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5783 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5784 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5785 return new ICmpInst(Pred, And1, And2);
5786 }
5787 }
5788 break;
5789 }
5790 case Instruction::UDiv:
5791 case Instruction::LShr:
5792 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5793 break;
5794 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5795
5796 case Instruction::SDiv:
5797 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5798 !BO0->isExact() || !BO1->isExact())
5799 break;
5800 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5801
5802 case Instruction::AShr:
5803 if (!BO0->isExact() || !BO1->isExact())
5804 break;
5805 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5806
5807 case Instruction::Shl: {
5808 bool NUW = Op0HasNUW && Op1HasNUW;
5809 bool NSW = Op0HasNSW && Op1HasNSW;
5810 if (!NUW && !NSW)
5811 break;
5812 if (!NSW && I.isSigned())
5813 break;
5814 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5815 }
5816 }
5817 }
5818
5819 if (BO0) {
5820 // Transform A & (L - 1) `ult` L --> L != 0
5821 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5822 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5823
5824 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5825 auto *Zero = Constant::getNullValue(BO0->getType());
5826 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5827 }
5828 }
5829
5830 // For unsigned predicates / eq / ne:
5831 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5832 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5833 if (!ICmpInst::isSigned(Pred)) {
5834 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5835 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5836 Constant::getNullValue(Op1->getType()));
5837 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5838 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5839 Constant::getNullValue(Op0->getType()), Op0);
5840 }
5841
5843 return replaceInstUsesWith(I, V);
5844
5845 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5846 return R;
5847
5849 return replaceInstUsesWith(I, V);
5850
5852 return replaceInstUsesWith(I, V);
5853
5854 return nullptr;
5855}
5856
5857/// Fold icmp Pred min|max(X, Y), Z.
5860 Value *Z, CmpPredicate Pred) {
5861 Value *X = MinMax->getLHS();
5862 Value *Y = MinMax->getRHS();
5863 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5864 return nullptr;
5865 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5866 // Revert the transform signed pred -> unsigned pred
5867 // TODO: We can flip the signedness of predicate if both operands of icmp
5868 // are negative.
5869 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5870 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5872 } else
5873 return nullptr;
5874 }
5875 SimplifyQuery Q = SQ.getWithInstruction(&I);
5876 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
5877 if (!Val)
5878 return std::nullopt;
5879 if (match(Val, m_One()))
5880 return true;
5881 if (match(Val, m_Zero()))
5882 return false;
5883 return std::nullopt;
5884 };
5885 // Remove samesign here since it is illegal to keep it when we speculatively
5886 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
5887 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
5888 // -46, -32)`. `X` is allowed to be non-negative here.
5889 Pred = Pred.dropSameSign();
5890 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
5891 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
5892 if (!CmpXZ.has_value() && !CmpYZ.has_value())
5893 return nullptr;
5894 if (!CmpXZ.has_value()) {
5895 std::swap(X, Y);
5896 std::swap(CmpXZ, CmpYZ);
5897 }
5898
5899 auto FoldIntoCmpYZ = [&]() -> Instruction * {
5900 if (CmpYZ.has_value())
5901 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
5902 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
5903 };
5904
5905 switch (Pred) {
5906 case ICmpInst::ICMP_EQ:
5907 case ICmpInst::ICMP_NE: {
5908 // If X == Z:
5909 // Expr Result
5910 // min(X, Y) == Z X <= Y
5911 // max(X, Y) == Z X >= Y
5912 // min(X, Y) != Z X > Y
5913 // max(X, Y) != Z X < Y
5914 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
5915 ICmpInst::Predicate NewPred =
5916 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
5917 if (Pred == ICmpInst::ICMP_NE)
5918 NewPred = ICmpInst::getInversePredicate(NewPred);
5919 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
5920 }
5921 // Otherwise (X != Z):
5922 ICmpInst::Predicate NewPred = MinMax->getPredicate();
5923 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5924 if (!MinMaxCmpXZ.has_value()) {
5925 std::swap(X, Y);
5926 std::swap(CmpXZ, CmpYZ);
5927 // Re-check pre-condition X != Z
5928 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
5929 break;
5930 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
5931 }
5932 if (!MinMaxCmpXZ.has_value())
5933 break;
5934 if (*MinMaxCmpXZ) {
5935 // Expr Fact Result
5936 // min(X, Y) == Z X < Z false
5937 // max(X, Y) == Z X > Z false
5938 // min(X, Y) != Z X < Z true
5939 // max(X, Y) != Z X > Z true
5940 return replaceInstUsesWith(
5941 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
5942 } else {
5943 // Expr Fact Result
5944 // min(X, Y) == Z X > Z Y == Z
5945 // max(X, Y) == Z X < Z Y == Z
5946 // min(X, Y) != Z X > Z Y != Z
5947 // max(X, Y) != Z X < Z Y != Z
5948 return FoldIntoCmpYZ();
5949 }
5950 break;
5951 }
5952 case ICmpInst::ICMP_SLT:
5953 case ICmpInst::ICMP_ULT:
5954 case ICmpInst::ICMP_SLE:
5955 case ICmpInst::ICMP_ULE:
5956 case ICmpInst::ICMP_SGT:
5957 case ICmpInst::ICMP_UGT:
5958 case ICmpInst::ICMP_SGE:
5959 case ICmpInst::ICMP_UGE: {
5960 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
5961 if (*CmpXZ) {
5962 if (IsSame) {
5963 // Expr Fact Result
5964 // min(X, Y) < Z X < Z true
5965 // min(X, Y) <= Z X <= Z true
5966 // max(X, Y) > Z X > Z true
5967 // max(X, Y) >= Z X >= Z true
5968 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5969 } else {
5970 // Expr Fact Result
5971 // max(X, Y) < Z X < Z Y < Z
5972 // max(X, Y) <= Z X <= Z Y <= Z
5973 // min(X, Y) > Z X > Z Y > Z
5974 // min(X, Y) >= Z X >= Z Y >= Z
5975 return FoldIntoCmpYZ();
5976 }
5977 } else {
5978 if (IsSame) {
5979 // Expr Fact Result
5980 // min(X, Y) < Z X >= Z Y < Z
5981 // min(X, Y) <= Z X > Z Y <= Z
5982 // max(X, Y) > Z X <= Z Y > Z
5983 // max(X, Y) >= Z X < Z Y >= Z
5984 return FoldIntoCmpYZ();
5985 } else {
5986 // Expr Fact Result
5987 // max(X, Y) < Z X >= Z false
5988 // max(X, Y) <= Z X > Z false
5989 // min(X, Y) > Z X <= Z false
5990 // min(X, Y) >= Z X < Z false
5991 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5992 }
5993 }
5994 break;
5995 }
5996 default:
5997 break;
5998 }
5999
6000 return nullptr;
6001}
6002
6003/// Match and fold patterns like:
6004/// icmp eq/ne X, min(max(X, Lo), Hi)
6005/// which represents a range check and can be represented as a ConstantRange.
6006///
6007/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
6008/// (X - Lo) u< (Hi + 1 - Lo)
6009/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
6010/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
6012 MinMaxIntrinsic *Min) {
6013 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
6014 return nullptr;
6015
6016 const APInt *Lo = nullptr, *Hi = nullptr;
6017 if (Min->isSigned()) {
6018 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
6019 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
6020 return nullptr;
6021 } else {
6022 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
6023 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
6024 return nullptr;
6025 }
6026
6029 APInt C, Offset;
6030 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6031 CR.getEquivalentICmp(Pred, C, Offset);
6032 else
6033 CR.inverse().getEquivalentICmp(Pred, C, Offset);
6034
6035 if (!Offset.isZero())
6036 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
6037
6038 return replaceInstUsesWith(
6039 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
6040}
6041
6042// Canonicalize checking for a power-of-2-or-zero value:
6044 InstCombiner::BuilderTy &Builder) {
6045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6046 const CmpInst::Predicate Pred = I.getPredicate();
6047 Value *A = nullptr;
6048 bool CheckIs;
6049 if (I.isEquality()) {
6050 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6051 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6052 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6053 m_Deferred(A)))) ||
6054 !match(Op1, m_ZeroInt()))
6055 A = nullptr;
6056
6057 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6058 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6059 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6060 A = Op1;
6061 else if (match(Op1,
6063 A = Op0;
6064
6065 CheckIs = Pred == ICmpInst::ICMP_EQ;
6066 } else if (ICmpInst::isUnsigned(Pred)) {
6067 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6068 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6069
6070 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6072 m_Specific(Op1))))) {
6073 A = Op1;
6074 CheckIs = Pred == ICmpInst::ICMP_UGE;
6075 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6077 m_Specific(Op0))))) {
6078 A = Op0;
6079 CheckIs = Pred == ICmpInst::ICMP_ULE;
6080 }
6081 }
6082
6083 if (A) {
6084 Type *Ty = A->getType();
6085 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6086 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6087 ConstantInt::get(Ty, 2))
6088 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6089 ConstantInt::get(Ty, 1));
6090 }
6091
6092 return nullptr;
6093}
6094
6095/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6096using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6098 bool AllowRecursion) {
6100 if (!Inst || !Inst->hasOneUse())
6101 return;
6102
6103 switch (Inst->getOpcode()) {
6104 case Instruction::Add:
6105 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6106 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6107 break;
6108 case Instruction::Sub:
6109 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6110 break;
6111 case Instruction::Xor:
6112 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6113 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6114 break;
6115 case Instruction::Shl:
6116 if (Inst->hasNoSignedWrap())
6117 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6118 if (Inst->hasNoUnsignedWrap())
6119 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6120 break;
6121 case Instruction::Select:
6122 if (AllowRecursion) {
6123 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6124 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6125 }
6126 break;
6127 default:
6128 break;
6129 }
6130}
6131
6133
6138
6140 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6141 }
6143 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6144 }
6145 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6147 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6148 }
6149 bool isValid() const { return Kind != OffsetKind::Invalid; }
6151 switch (Kind) {
6153 llvm_unreachable("Invalid offset result");
6154 case OffsetKind::Value:
6155 return V0;
6156 case OffsetKind::Select:
6157 return Builder.CreateSelect(V0, V1, V2, "", MDFrom);
6158 }
6159 llvm_unreachable("Unknown OffsetKind enum");
6160 }
6161};
6162
6163/// Offset both sides of an equality icmp to see if we can save some
6164/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6165/// Note: This operation should not introduce poison.
6167 InstCombiner::BuilderTy &Builder,
6168 const SimplifyQuery &SQ) {
6169 assert(I.isEquality() && "Expected an equality icmp");
6170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6171 if (!Op0->getType()->isIntOrIntVectorTy())
6172 return nullptr;
6173
6174 SmallVector<OffsetOp, 4> OffsetOps;
6175 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6176 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6177
6178 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6179 switch (BinOpc) {
6180 // V = shl nsw X, RHS => X = ashr V, RHS
6181 case Instruction::AShr: {
6182 const APInt *CV, *CRHS;
6183 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6184 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6186 return nullptr;
6187 break;
6188 }
6189 // V = shl nuw X, RHS => X = lshr V, RHS
6190 case Instruction::LShr: {
6191 const APInt *CV, *CRHS;
6192 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6193 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6195 return nullptr;
6196 break;
6197 }
6198 default:
6199 break;
6200 }
6201
6202 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6203 if (!Simplified)
6204 return nullptr;
6205 // Reject constant expressions as they don't simplify things.
6206 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6207 return nullptr;
6208 // Check if the transformation introduces poison.
6209 return impliesPoison(RHS, V) ? Simplified : nullptr;
6210 };
6211
6212 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6213 Value *RHS) -> OffsetResult {
6214 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6215 if (!Sel->hasOneUse())
6216 return OffsetResult::invalid();
6217 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6218 if (!TrueVal)
6219 return OffsetResult::invalid();
6220 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6221 if (!FalseVal)
6222 return OffsetResult::invalid();
6223 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6224 }
6225 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6226 return OffsetResult::value(Simplified);
6227 return OffsetResult::invalid();
6228 };
6229
6230 for (auto [BinOp, RHS] : OffsetOps) {
6231 auto BinOpc = static_cast<unsigned>(BinOp);
6232
6233 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6234 if (!Op0Result.isValid())
6235 continue;
6236 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6237 if (!Op1Result.isValid())
6238 continue;
6239
6240 Value *NewLHS = Op0Result.materialize(Builder);
6241 Value *NewRHS = Op1Result.materialize(Builder);
6242 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6243 }
6244
6245 return nullptr;
6246}
6247
6249 if (!I.isEquality())
6250 return nullptr;
6251
6252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6253 const CmpInst::Predicate Pred = I.getPredicate();
6254 Value *A, *B, *C, *D;
6255 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6256 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6257 Value *OtherVal = A == Op1 ? B : A;
6258 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6259 }
6260
6261 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6262 // A^c1 == C^c2 --> A == C^(c1^c2)
6263 ConstantInt *C1, *C2;
6264 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6265 Op1->hasOneUse()) {
6266 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6267 Value *Xor = Builder.CreateXor(C, NC);
6268 return new ICmpInst(Pred, A, Xor);
6269 }
6270
6271 // A^B == A^D -> B == D
6272 if (A == C)
6273 return new ICmpInst(Pred, B, D);
6274 if (A == D)
6275 return new ICmpInst(Pred, B, C);
6276 if (B == C)
6277 return new ICmpInst(Pred, A, D);
6278 if (B == D)
6279 return new ICmpInst(Pred, A, C);
6280 }
6281 }
6282
6283 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6284 // A == (A^B) -> B == 0
6285 Value *OtherVal = A == Op0 ? B : A;
6286 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6287 }
6288
6289 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6290 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6291 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6292 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6293
6294 if (A == C) {
6295 X = B;
6296 Y = D;
6297 Z = A;
6298 } else if (A == D) {
6299 X = B;
6300 Y = C;
6301 Z = A;
6302 } else if (B == C) {
6303 X = A;
6304 Y = D;
6305 Z = B;
6306 } else if (B == D) {
6307 X = A;
6308 Y = C;
6309 Z = B;
6310 }
6311
6312 if (X) {
6313 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6314 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6315 // instructions.
6316 const APInt *C0, *C1;
6317 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6318 (*C0 ^ *C1).isNegatedPowerOf2();
6319
6320 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6321 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6322 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6323 int UseCnt =
6324 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6325 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6326 if (XorIsNegP2 || UseCnt >= 2) {
6327 // Build (X^Y) & Z
6328 Op1 = Builder.CreateXor(X, Y);
6329 Op1 = Builder.CreateAnd(Op1, Z);
6330 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6331 }
6332 }
6333 }
6334
6335 {
6336 // Similar to above, but specialized for constant because invert is needed:
6337 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6338 Value *X, *Y;
6339 Constant *C;
6340 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6341 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6342 Value *Xor = Builder.CreateXor(X, Y);
6343 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6344 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6345 }
6346 }
6347
6348 if (match(Op1, m_ZExt(m_Value(A))) &&
6349 (Op0->hasOneUse() || Op1->hasOneUse())) {
6350 // (B & (Pow2C-1)) == zext A --> A == trunc B
6351 // (B & (Pow2C-1)) != zext A --> A != trunc B
6352 const APInt *MaskC;
6353 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6354 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6355 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6356 }
6357
6358 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6359 // For lshr and ashr pairs.
6360 const APInt *AP1, *AP2;
6361 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6362 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6363 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6364 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6365 if (*AP1 != *AP2)
6366 return nullptr;
6367 unsigned TypeBits = AP1->getBitWidth();
6368 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6369 if (ShAmt < TypeBits && ShAmt != 0) {
6370 ICmpInst::Predicate NewPred =
6372 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6373 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6374 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6375 }
6376 }
6377
6378 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6379 ConstantInt *Cst1;
6380 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6381 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6382 unsigned TypeBits = Cst1->getBitWidth();
6383 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6384 if (ShAmt < TypeBits && ShAmt != 0) {
6385 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6386 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6387 Value *And =
6388 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6389 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6390 }
6391 }
6392
6393 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6394 // "icmp (and X, mask), cst"
6395 uint64_t ShAmt = 0;
6396 if (Op0->hasOneUse() &&
6397 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6398 match(Op1, m_ConstantInt(Cst1)) &&
6399 // Only do this when A has multiple uses. This is most important to do
6400 // when it exposes other optimizations.
6401 !A->hasOneUse()) {
6402 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6403
6404 if (ShAmt < ASize) {
6405 APInt MaskV =
6407 MaskV <<= ShAmt;
6408
6409 APInt CmpV = Cst1->getValue().zext(ASize);
6410 CmpV <<= ShAmt;
6411
6412 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6413 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6414 }
6415 }
6416
6418 return ICmp;
6419
6420 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6421 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6422 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6423 // few steps of instcombine.
6424 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6425 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6427 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6428 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6430 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6431 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6433 Add, ConstantInt::get(A->getType(), C.shl(1)));
6434 }
6435
6436 // Canonicalize:
6437 // Assume B_Pow2 != 0
6438 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6439 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6440 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6441 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6442 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6444
6445 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6446 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6447 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6448 ConstantInt::getNullValue(Op1->getType()));
6449
6450 // Canonicalize:
6451 // icmp eq/ne X, OneUse(rotate-right(X))
6452 // -> icmp eq/ne X, rotate-left(X)
6453 // We generally try to convert rotate-right -> rotate-left, this just
6454 // canonicalizes another case.
6455 if (match(&I, m_c_ICmp(m_Value(A),
6457 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6458 return new ICmpInst(
6459 Pred, A,
6460 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6461
6462 // Canonicalize:
6463 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6464 Constant *Cst;
6467 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6468
6469 {
6470 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6471 auto m_Matcher =
6474 m_Sub(m_Value(B), m_Deferred(A)));
6475 std::optional<bool> IsZero = std::nullopt;
6476 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6477 m_Deferred(A))))
6478 IsZero = false;
6479 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6480 else if (match(&I,
6481 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6482 IsZero = true;
6483
6484 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6485 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6486 // -> (icmp eq/ne (and X, P2), 0)
6487 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6488 // -> (icmp eq/ne (and X, P2), P2)
6489 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6490 *IsZero ? A
6491 : ConstantInt::getNullValue(A->getType()));
6492 }
6493
6494 if (auto *Res = foldICmpEqualityWithOffset(
6495 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6496 return Res;
6497
6498 return nullptr;
6499}
6500
6502 ICmpInst::Predicate Pred = ICmp.getPredicate();
6503 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6504
6505 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6506 // The trunc masks high bits while the compare may effectively mask low bits.
6507 Value *X;
6508 const APInt *C;
6509 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6510 return nullptr;
6511
6512 // This matches patterns corresponding to tests of the signbit as well as:
6513 // (trunc X) pred C2 --> (X & Mask) == C
6514 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6515 /*AllowNonZeroC=*/true)) {
6516 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6517 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6518 return new ICmpInst(Res->Pred, And, C);
6519 }
6520
6521 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6522 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6523 if (II->getIntrinsicID() == Intrinsic::cttz ||
6524 II->getIntrinsicID() == Intrinsic::ctlz) {
6525 unsigned MaxRet = SrcBits;
6526 // If the "is_zero_poison" argument is set, then we know at least
6527 // one bit is set in the input, so the result is always at least one
6528 // less than the full bitwidth of that input.
6529 if (match(II->getArgOperand(1), m_One()))
6530 MaxRet--;
6531
6532 // Make sure the destination is wide enough to hold the largest output of
6533 // the intrinsic.
6534 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6535 if (Instruction *I =
6536 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6537 return I;
6538 }
6539 }
6540
6541 return nullptr;
6542}
6543
6545 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6546 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6547 Value *X;
6548 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6549 return nullptr;
6550
6551 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6552 bool IsSignedCmp = ICmp.isSigned();
6553
6554 // icmp Pred (ext X), (ext Y)
6555 Value *Y;
6556 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6557 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6558 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6559
6560 if (IsZext0 != IsZext1) {
6561 // If X and Y and both i1
6562 // (icmp eq/ne (zext X) (sext Y))
6563 // eq -> (icmp eq (or X, Y), 0)
6564 // ne -> (icmp ne (or X, Y), 0)
6565 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6566 Y->getType()->isIntOrIntVectorTy(1))
6567 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6568 Constant::getNullValue(X->getType()));
6569
6570 // If we have mismatched casts and zext has the nneg flag, we can
6571 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6572
6573 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6574 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6575
6576 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6577 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6578
6579 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6580 IsSignedExt = true;
6581 else
6582 return nullptr;
6583 }
6584
6585 // Not an extension from the same type?
6586 Type *XTy = X->getType(), *YTy = Y->getType();
6587 if (XTy != YTy) {
6588 // One of the casts must have one use because we are creating a new cast.
6589 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6590 return nullptr;
6591 // Extend the narrower operand to the type of the wider operand.
6592 CastInst::CastOps CastOpcode =
6593 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6594 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6595 X = Builder.CreateCast(CastOpcode, X, YTy);
6596 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6597 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6598 else
6599 return nullptr;
6600 }
6601
6602 // (zext X) == (zext Y) --> X == Y
6603 // (sext X) == (sext Y) --> X == Y
6604 if (ICmp.isEquality())
6605 return new ICmpInst(ICmp.getPredicate(), X, Y);
6606
6607 // A signed comparison of sign extended values simplifies into a
6608 // signed comparison.
6609 if (IsSignedCmp && IsSignedExt)
6610 return new ICmpInst(ICmp.getPredicate(), X, Y);
6611
6612 // The other three cases all fold into an unsigned comparison.
6613 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6614 }
6615
6616 // Below here, we are only folding a compare with constant.
6617 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6618 if (!C)
6619 return nullptr;
6620
6621 // If a lossless truncate is possible...
6622 Type *SrcTy = CastOp0->getSrcTy();
6623 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6624 if (Res) {
6625 if (ICmp.isEquality())
6626 return new ICmpInst(ICmp.getPredicate(), X, Res);
6627
6628 // A signed comparison of sign extended values simplifies into a
6629 // signed comparison.
6630 if (IsSignedExt && IsSignedCmp)
6631 return new ICmpInst(ICmp.getPredicate(), X, Res);
6632
6633 // The other three cases all fold into an unsigned comparison.
6634 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6635 }
6636
6637 // The re-extended constant changed, partly changed (in the case of a vector),
6638 // or could not be determined to be equal (in the case of a constant
6639 // expression), so the constant cannot be represented in the shorter type.
6640 // All the cases that fold to true or false will have already been handled
6641 // by simplifyICmpInst, so only deal with the tricky case.
6642 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6643 return nullptr;
6644
6645 // Is source op positive?
6646 // icmp ult (sext X), C --> icmp sgt X, -1
6647 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6649
6650 // Is source op negative?
6651 // icmp ugt (sext X), C --> icmp slt X, 0
6652 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6654}
6655
6656/// Handle icmp (cast x), (cast or constant).
6658 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6659 // icmp compares only pointer's value.
6660 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6661 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6662 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6663 if (SimplifiedOp0 || SimplifiedOp1)
6664 return new ICmpInst(ICmp.getPredicate(),
6665 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6666 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6667
6668 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6669 Value *Op1 = ICmp.getOperand(1);
6670 if (!CastOp0)
6671 return nullptr;
6672 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6673 return nullptr;
6674
6675 Value *Op0Src = CastOp0->getOperand(0);
6676 Type *SrcTy = CastOp0->getSrcTy();
6677 Type *DestTy = CastOp0->getDestTy();
6678
6679 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6680 // integer type is the same size as the pointer type.
6681 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6682 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6683 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6684 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6685 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6686 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6687 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6688 };
6689 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6690 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6691 Value *NewOp1 = nullptr;
6692 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6693 NewOp1 = PtrToIntOp1->getOperand(0);
6694 HasPtrToInt = true;
6695 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6696 NewOp1 = PtrToAddrOp1->getOperand(0);
6697 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6698 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6699 }
6700
6701 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6702 // check PtrWidth.
6703 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6704 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6705 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6706 }
6707
6708 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6709 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6710 CompatibleSizes(DestTy, SrcTy)) {
6711 Value *NewOp1 = nullptr;
6712 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6713 Value *IntSrc = IntToPtrOp1->getOperand(0);
6714 if (IntSrc->getType() == Op0Src->getType())
6715 NewOp1 = IntToPtrOp1->getOperand(0);
6716 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6717 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6718 }
6719
6720 if (NewOp1)
6721 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6722 }
6723
6724 if (Instruction *R = foldICmpWithTrunc(ICmp))
6725 return R;
6726
6727 return foldICmpWithZextOrSext(ICmp);
6728}
6729
6731 bool IsSigned) {
6732 switch (BinaryOp) {
6733 default:
6734 llvm_unreachable("Unsupported binary op");
6735 case Instruction::Add:
6736 case Instruction::Sub:
6737 return match(RHS, m_Zero());
6738 case Instruction::Mul:
6739 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6740 match(RHS, m_One());
6741 }
6742}
6743
6746 bool IsSigned, Value *LHS, Value *RHS,
6747 Instruction *CtxI) const {
6748 switch (BinaryOp) {
6749 default:
6750 llvm_unreachable("Unsupported binary op");
6751 case Instruction::Add:
6752 if (IsSigned)
6753 return computeOverflowForSignedAdd(LHS, RHS, CtxI);
6754 else
6755 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI);
6756 case Instruction::Sub:
6757 if (IsSigned)
6758 return computeOverflowForSignedSub(LHS, RHS, CtxI);
6759 else
6760 return computeOverflowForUnsignedSub(LHS, RHS, CtxI);
6761 case Instruction::Mul:
6762 if (IsSigned)
6763 return computeOverflowForSignedMul(LHS, RHS, CtxI);
6764 else
6765 return computeOverflowForUnsignedMul(LHS, RHS, CtxI);
6766 }
6767}
6768
6769bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6770 bool IsSigned, Value *LHS,
6771 Value *RHS, Instruction &OrigI,
6772 Value *&Result,
6773 Constant *&Overflow) {
6774 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6775 std::swap(LHS, RHS);
6776
6777 // If the overflow check was an add followed by a compare, the insertion point
6778 // may be pointing to the compare. We want to insert the new instructions
6779 // before the add in case there are uses of the add between the add and the
6780 // compare.
6781 Builder.SetInsertPoint(&OrigI);
6782
6783 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6784 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6785 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6786
6787 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6788 Result = LHS;
6789 Overflow = ConstantInt::getFalse(OverflowTy);
6790 return true;
6791 }
6792
6793 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6795 return false;
6798 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6799 Result->takeName(&OrigI);
6800 Overflow = ConstantInt::getTrue(OverflowTy);
6801 return true;
6803 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6804 Result->takeName(&OrigI);
6805 Overflow = ConstantInt::getFalse(OverflowTy);
6806 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6807 if (IsSigned)
6808 Inst->setHasNoSignedWrap();
6809 else
6810 Inst->setHasNoUnsignedWrap();
6811 }
6812 return true;
6813 }
6814
6815 llvm_unreachable("Unexpected overflow result");
6816}
6817
6818/// Recognize and process idiom involving test for unsigned
6819/// overflow.
6820///
6821/// The caller has matched a pattern of the form:
6822/// I = cmp u (add(zext A, zext B), V
6823/// I = cmp u (mul(zext A, zext B), V
6824/// The function checks if this is a test for overflow and if so replaces
6825/// addition/multiplication with call to the umul intrinsic or the canonical
6826/// form of uadd overflow.
6827///
6828/// \param I Compare instruction.
6829/// \param Val Result of add/mul instruction. It is one of the arguments of
6830/// the compare instruction. Must be of integer type.
6831/// \param OtherVal The other argument of compare instruction.
6832/// \returns Instruction which must replace the compare instruction, NULL if no
6833/// replacement required.
6835 const APInt *OtherVal,
6836 InstCombinerImpl &IC) {
6837 // Don't bother doing this transformation for pointers, don't do it for
6838 // vectors.
6839 if (!isa<IntegerType>(Val->getType()))
6840 return nullptr;
6841
6842 auto *Instr = cast<Instruction>(Val);
6843 unsigned Opcode = Instr->getOpcode();
6844 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6845
6846 auto *LHS = cast<ZExtInst>(Instr->getOperand(0)),
6847 *RHS = cast<ZExtInst>(Instr->getOperand(1));
6848 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6849
6850 // Calculate type and width of the result produced by add/mul.with.overflow.
6851 Type *TyA = A->getType(), *TyB = B->getType();
6852 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6853 WidthB = TyB->getPrimitiveSizeInBits();
6854 unsigned ResultWidth;
6855 Type *ResultType;
6856 if (WidthB > WidthA) {
6857 ResultWidth = WidthB;
6858 ResultType = TyB;
6859 } else {
6860 ResultWidth = WidthA;
6861 ResultType = TyA;
6862 }
6863
6864 // In order to replace the original result with a narrower one, all uses must
6865 // ignore upper bits of the result. The number of used low bits must be not
6866 // greater than the width of add or mul.with.overflow.
6867 if (Val->hasNUsesOrMore(2))
6868 for (User *U : Val->users()) {
6869 if (U == &I)
6870 continue;
6871 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6872 // Check if truncation ignores bits above ResultWidth.
6873 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6874 if (TruncWidth > ResultWidth)
6875 return nullptr;
6876 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6877 // Check if AND ignores bits above ResultWidth.
6878 if (BO->getOpcode() != Instruction::And)
6879 return nullptr;
6880 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6881 const APInt &CVal = CI->getValue();
6882 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
6883 return nullptr;
6884 } else {
6885 // In this case we could have the operand of the binary operation
6886 // being defined in another block, and performing the replacement
6887 // could break the dominance relation.
6888 return nullptr;
6889 }
6890 } else {
6891 // Other uses prohibit this transformation.
6892 return nullptr;
6893 }
6894 }
6895
6896 // Recognize patterns
6897 switch (I.getPredicate()) {
6898 case ICmpInst::ICMP_UGT: {
6899 // Recognize pattern:
6900 // val = add/mul(zext A, zext B)
6901 // cmp ugt val, max
6902 APInt MaxVal = APInt::getMaxValue(ResultWidth);
6903 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
6904 if (MaxVal.eq(*OtherVal))
6905 break; // Recognized
6906 return nullptr;
6907 }
6908
6909 case ICmpInst::ICMP_ULT: {
6910 // Recognize pattern:
6911 // val = add/mul(zext A, zext B)
6912 // cmp ult val, max + 1
6913 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), ResultWidth);
6914 if (MaxVal.eq(*OtherVal))
6915 break; // Recognized
6916 return nullptr;
6917 }
6918
6919 default:
6920 return nullptr;
6921 }
6922
6923 InstCombiner::BuilderTy &Builder = IC.Builder;
6924 Builder.SetInsertPoint(Instr);
6925
6926 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
6927 Value *ResultA = A, *ResultB = B;
6928 if (WidthA < ResultWidth)
6929 ResultA = Builder.CreateZExt(A, ResultType);
6930 if (WidthB < ResultWidth)
6931 ResultB = Builder.CreateZExt(B, ResultType);
6932
6933 Value *ArithResult;
6934 Value *OverflowCheck;
6935
6936 if (Opcode == Instruction::Add) {
6937 // Canonical add overflow check: add + compare
6938 ArithResult = Builder.CreateAdd(ResultA, ResultB, "add");
6939 // Overflow if result < either operand (for unsigned add)
6940 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6941 OverflowCheck =
6942 Builder.CreateICmpUGE(ArithResult, ResultA, "not.add.overflow");
6943 else
6944 OverflowCheck =
6945 Builder.CreateICmpULT(ArithResult, ResultA, "add.overflow");
6946 } else {
6947 // For multiplication, the intrinsic is actually the canonical form
6948 Value *Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
6949 ResultType, {ResultA, ResultB},
6950 /*FMFSource=*/nullptr, "umul");
6951 ArithResult = Builder.CreateExtractValue(Call, 0, "umul.value");
6952 OverflowCheck = Builder.CreateExtractValue(Call, 1, "umul.overflow");
6953 if (I.getPredicate() == ICmpInst::ICMP_ULT)
6954 OverflowCheck = Builder.CreateNot(OverflowCheck);
6955 }
6956
6957 IC.addToWorklist(Instr);
6958
6959 // Replace uses of the original add/mul result with the new arithmetic result
6960 if (Val->hasNUsesOrMore(2)) {
6961 for (User *U : make_early_inc_range(Val->users())) {
6962 if (U == &I)
6963 continue;
6964 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6965 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
6966 IC.replaceInstUsesWith(*TI, ArithResult);
6967 else
6968 TI->setOperand(0, ArithResult);
6969 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
6970 assert(BO->getOpcode() == Instruction::And);
6971 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
6972 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
6973 APInt ShortMask = CI->getValue().trunc(ResultWidth);
6974 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
6975 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
6976 IC.replaceInstUsesWith(*BO, Zext);
6977 } else {
6978 llvm_unreachable("Unexpected Binary operation");
6979 }
6981 }
6982 }
6983
6984 return IC.replaceInstUsesWith(I, OverflowCheck);
6985}
6986
6987/// When performing a comparison against a constant, it is possible that not all
6988/// the bits in the LHS are demanded. This helper method computes the mask that
6989/// IS demanded.
6991 const APInt *RHS;
6992 if (!match(I.getOperand(1), m_APInt(RHS)))
6994
6995 // If this is a normal comparison, it demands all bits. If it is a sign bit
6996 // comparison, it only demands the sign bit.
6997 bool UnusedBit;
6998 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
7000
7001 switch (I.getPredicate()) {
7002 // For a UGT comparison, we don't care about any bits that
7003 // correspond to the trailing ones of the comparand. The value of these
7004 // bits doesn't impact the outcome of the comparison, because any value
7005 // greater than the RHS must differ in a bit higher than these due to carry.
7006 case ICmpInst::ICMP_UGT:
7007 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
7008
7009 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
7010 // Any value less than the RHS must differ in a higher bit because of carries.
7011 case ICmpInst::ICMP_ULT:
7012 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
7013
7014 default:
7016 }
7017}
7018
7019/// Check that one use is in the same block as the definition and all
7020/// other uses are in blocks dominated by a given block.
7021///
7022/// \param DI Definition
7023/// \param UI Use
7024/// \param DB Block that must dominate all uses of \p DI outside
7025/// the parent block
7026/// \return true when \p UI is the only use of \p DI in the parent block
7027/// and all other uses of \p DI are in blocks dominated by \p DB.
7028///
7030 const Instruction *UI,
7031 const BasicBlock *DB) const {
7032 assert(DI && UI && "Instruction not defined\n");
7033 // Ignore incomplete definitions.
7034 if (!DI->getParent())
7035 return false;
7036 // DI and UI must be in the same block.
7037 if (DI->getParent() != UI->getParent())
7038 return false;
7039 // Protect from self-referencing blocks.
7040 if (DI->getParent() == DB)
7041 return false;
7042 for (const User *U : DI->users()) {
7043 auto *Usr = cast<Instruction>(U);
7044 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
7045 return false;
7046 }
7047 return true;
7048}
7049
7050/// Return true when the instruction sequence within a block is select-cmp-br.
7052 const BasicBlock *BB = SI->getParent();
7053 if (!BB)
7054 return false;
7056 if (!BI)
7057 return false;
7058 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7059 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7060 return false;
7061 return true;
7062}
7063
7064/// True when a select result is replaced by one of its operands
7065/// in select-icmp sequence. This will eventually result in the elimination
7066/// of the select.
7067///
7068/// \param SI Select instruction
7069/// \param Icmp Compare instruction
7070/// \param SIOpd Operand that replaces the select
7071///
7072/// Notes:
7073/// - The replacement is global and requires dominator information
7074/// - The caller is responsible for the actual replacement
7075///
7076/// Example:
7077///
7078/// entry:
7079/// %4 = select i1 %3, %C* %0, %C* null
7080/// %5 = icmp eq %C* %4, null
7081/// br i1 %5, label %9, label %7
7082/// ...
7083/// ; <label>:7 ; preds = %entry
7084/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7085/// ...
7086///
7087/// can be transformed to
7088///
7089/// %5 = icmp eq %C* %0, null
7090/// %6 = select i1 %3, i1 %5, i1 true
7091/// br i1 %6, label %9, label %7
7092/// ...
7093/// ; <label>:7 ; preds = %entry
7094/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7095///
7096/// Similar when the first operand of the select is a constant or/and
7097/// the compare is for not equal rather than equal.
7098///
7099/// NOTE: The function is only called when the select and compare constants
7100/// are equal, the optimization can work only for EQ predicates. This is not a
7101/// major restriction since a NE compare should be 'normalized' to an equal
7102/// compare, which usually happens in the combiner and test case
7103/// select-cmp-br.ll checks for it.
7105 const ICmpInst *Icmp,
7106 const unsigned SIOpd) {
7107 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7109 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7110 // The check for the single predecessor is not the best that can be
7111 // done. But it protects efficiently against cases like when SI's
7112 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7113 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7114 // replaced can be reached on either path. So the uniqueness check
7115 // guarantees that the path all uses of SI (outside SI's parent) are on
7116 // is disjoint from all other paths out of SI. But that information
7117 // is more expensive to compute, and the trade-off here is in favor
7118 // of compile-time. It should also be noticed that we check for a single
7119 // predecessor and not only uniqueness. This to handle the situation when
7120 // Succ and Succ1 points to the same basic block.
7121 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7122 NumSel++;
7123 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7124 return true;
7125 }
7126 }
7127 return false;
7128}
7129
7130/// Try to fold the comparison based on range information we can get by checking
7131/// whether bits are known to be zero or one in the inputs.
7133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7134 Type *Ty = Op0->getType();
7135 ICmpInst::Predicate Pred = I.getPredicate();
7136
7137 // Get scalar or pointer size.
7138 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7139 ? Ty->getScalarSizeInBits()
7140 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7141
7142 if (!BitWidth)
7143 return nullptr;
7144
7145 KnownBits Op0Known(BitWidth);
7146 KnownBits Op1Known(BitWidth);
7147
7148 {
7149 // Don't use dominating conditions when folding icmp using known bits. This
7150 // may convert signed into unsigned predicates in ways that other passes
7151 // (especially IndVarSimplify) may not be able to reliably undo.
7152 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7154 Op0Known, Q))
7155 return &I;
7156
7157 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7158 return &I;
7159 }
7160
7161 // If an unsigned samesign comparison is not poison, both operands have the
7162 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7163 // values so the existing range folds can use that constraint.
7164 if (I.hasSameSign() && I.isUnsigned()) {
7165 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7166 if (To.isNegative() || To.isNonNegative())
7167 return;
7168 if (From.isNegative())
7169 To.makeNegative();
7170 else if (From.isNonNegative())
7171 To.makeNonNegative();
7172 };
7173 PropagateSignBit(Op0Known, Op1Known);
7174 PropagateSignBit(Op1Known, Op0Known);
7175 }
7176
7177 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7178 return new ICmpInst(
7179 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7180 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7181 return new ICmpInst(
7182 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7183
7184 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7185 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7186
7187 // Given the known and unknown bits, compute a range that the LHS could be
7188 // in. Compute the Min, Max and RHS values based on the known bits. For the
7189 // EQ and NE we use unsigned values.
7190 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7191 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7192 if (I.isSigned()) {
7193 Op0Min = Op0Known.getSignedMinValue();
7194 Op0Max = Op0Known.getSignedMaxValue();
7195 Op1Min = Op1Known.getSignedMinValue();
7196 Op1Max = Op1Known.getSignedMaxValue();
7197 } else {
7198 Op0Min = Op0Known.getMinValue();
7199 Op0Max = Op0Known.getMaxValue();
7200 Op1Min = Op1Known.getMinValue();
7201 Op1Max = Op1Known.getMaxValue();
7202 }
7203
7204 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7205 // min/max canonical compare with some other compare. That could lead to
7206 // conflict with select canonicalization and infinite looping.
7207 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7208 auto isMinMaxCmp = [&](Instruction &Cmp) {
7209 if (!Cmp.hasOneUse())
7210 return false;
7211 Value *A, *B;
7212 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7214 return false;
7215 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7216 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7217 };
7218 if (!isMinMaxCmp(I)) {
7219 switch (Pred) {
7220 default:
7221 break;
7222 case ICmpInst::ICMP_ULT: {
7223 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7224 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7225 const APInt *CmpC;
7226 if (match(Op1, m_APInt(CmpC))) {
7227 // A <u C -> A == C-1 if min(A)+1 == C
7228 if (*CmpC == Op0Min + 1)
7229 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7230 ConstantInt::get(Op1->getType(), *CmpC - 1));
7231 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7232 // exceeds the log2 of C.
7233 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7234 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7235 Constant::getNullValue(Op1->getType()));
7236 }
7237 break;
7238 }
7239 case ICmpInst::ICMP_UGT: {
7240 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7241 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7242 const APInt *CmpC;
7243 if (match(Op1, m_APInt(CmpC))) {
7244 // A >u C -> A == C+1 if max(a)-1 == C
7245 if (*CmpC == Op0Max - 1)
7246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7247 ConstantInt::get(Op1->getType(), *CmpC + 1));
7248 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7249 // exceeds the log2 of C.
7250 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7251 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7252 Constant::getNullValue(Op1->getType()));
7253 }
7254 break;
7255 }
7256 case ICmpInst::ICMP_SLT: {
7257 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7258 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7259 const APInt *CmpC;
7260 if (match(Op1, m_APInt(CmpC))) {
7261 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7262 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7263 ConstantInt::get(Op1->getType(), *CmpC - 1));
7264 }
7265 break;
7266 }
7267 case ICmpInst::ICMP_SGT: {
7268 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7269 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7270 const APInt *CmpC;
7271 if (match(Op1, m_APInt(CmpC))) {
7272 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7273 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7274 ConstantInt::get(Op1->getType(), *CmpC + 1));
7275 }
7276 break;
7277 }
7278 }
7279 }
7280
7281 // Based on the range information we know about the LHS, see if we can
7282 // simplify this comparison. For example, (x&4) < 8 is always true.
7283 switch (Pred) {
7284 default:
7285 break;
7286 case ICmpInst::ICMP_EQ:
7287 case ICmpInst::ICMP_NE: {
7288 // If all bits are known zero except for one, then we know at most one bit
7289 // is set. If the comparison is against zero, then this is a check to see if
7290 // *that* bit is set.
7291 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7292 if (Op1Known.isZero()) {
7293 // If the LHS is an AND with the same constant, look through it.
7294 Value *LHS = nullptr;
7295 const APInt *LHSC;
7296 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7297 *LHSC != Op0KnownZeroInverted)
7298 LHS = Op0;
7299
7300 Value *X;
7301 const APInt *C1;
7302 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7303 Type *XTy = X->getType();
7304 unsigned Log2C1 = C1->countr_zero();
7305 APInt C2 = Op0KnownZeroInverted;
7306 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7307 if (C2Pow2.isPowerOf2()) {
7308 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7309 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7310 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7311 unsigned Log2C2 = C2Pow2.countr_zero();
7312 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7313 auto NewPred =
7315 return new ICmpInst(NewPred, X, CmpC);
7316 }
7317 }
7318 }
7319
7320 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7321 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7322 (Op0Known & Op1Known) == Op0Known)
7323 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7324 ConstantInt::getNullValue(Op1->getType()));
7325 break;
7326 }
7327 case ICmpInst::ICMP_SGE:
7328 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7329 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7330 break;
7331 case ICmpInst::ICMP_SLE:
7332 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7333 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7334 break;
7335 case ICmpInst::ICMP_UGE:
7336 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7337 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7338 break;
7339 case ICmpInst::ICMP_ULE:
7340 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7341 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7342 break;
7343 }
7344
7345 // Turn a signed comparison into an unsigned one if both operands are known to
7346 // have the same sign. Set samesign if possible (except for equality
7347 // predicates).
7348 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7349 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7350 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7351 I.setPredicate(I.getUnsignedPredicate());
7352 I.setSameSign();
7353 return &I;
7354 }
7355
7356 return nullptr;
7357}
7358
7359/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7360/// then try to reduce patterns based on that limit.
7362 Value *X, *Y;
7363 CmpPredicate Pred;
7364
7365 // X must be 0 and bool must be true for "ULT":
7366 // X <u (zext i1 Y) --> (X == 0) & Y
7367 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7368 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7369 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7370
7371 // X must be 0 or bool must be true for "ULE":
7372 // X <=u (sext i1 Y) --> (X == 0) | Y
7373 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7374 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7375 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7376
7377 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7378 CmpPredicate Pred1, Pred2;
7379 const APInt *C;
7380 Instruction *ExtI;
7381 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7384 m_APInt(C)))))) &&
7385 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7386 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7387 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7388 auto CreateRangeCheck = [&] {
7389 Value *CmpV1 =
7390 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7391 Value *CmpV2 = Builder.CreateICmp(
7392 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7394 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7395 CmpV1, CmpV2);
7396 };
7397 if (C->isZero()) {
7398 if (Pred2 == ICmpInst::ICMP_EQ) {
7399 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7400 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7401 return replaceInstUsesWith(
7402 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7403 } else if (!IsSExt || HasOneUse) {
7404 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7405 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7406 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7407 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7408 return CreateRangeCheck();
7409 }
7410 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7411 if (Pred2 == ICmpInst::ICMP_NE) {
7412 // icmp eq X, (zext (icmp ne X, 1)) --> false
7413 // icmp ne X, (zext (icmp ne X, 1)) --> true
7414 // icmp eq X, (sext (icmp ne X, -1)) --> false
7415 // icmp ne X, (sext (icmp ne X, -1)) --> true
7416 return replaceInstUsesWith(
7417 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7418 } else if (!IsSExt || HasOneUse) {
7419 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7420 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7421 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7422 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7423 return CreateRangeCheck();
7424 }
7425 } else {
7426 // when C != 0 && C != 1:
7427 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7428 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7429 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7430 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7431 // when C != 0 && C != -1:
7432 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7433 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7434 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7435 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7436 return ICmpInst::Create(
7437 Instruction::ICmp, Pred1, X,
7438 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7439 ? (IsSExt ? -1 : 1)
7440 : 0));
7441 }
7442 }
7443
7444 return nullptr;
7445}
7446
7447/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7448/// it into the appropriate icmp lt or icmp gt instruction. This transform
7449/// allows them to be folded in visitICmpInst.
7451 CmpPredicate Pred = I.getCmpPredicate();
7452 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7454 return nullptr;
7455
7456 Value *Op0 = I.getOperand(0);
7457 Value *Op1 = I.getOperand(1);
7458 auto *Op1C = dyn_cast<Constant>(Op1);
7459 if (!Op1C)
7460 return nullptr;
7461
7462 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7463 if (!FlippedStrictness)
7464 return nullptr;
7465
7466 auto *NewCmp =
7467 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7468 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7469 return NewCmp;
7470}
7471
7472/// If we have a comparison with a non-canonical predicate, if we can update
7473/// all the users, invert the predicate and adjust all the users.
7475 // Is the predicate already canonical?
7476 CmpInst::Predicate Pred = I.getPredicate();
7478 return nullptr;
7479
7480 // Can all users be adjusted to predicate inversion?
7481 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7482 return nullptr;
7483
7484 // Ok, we can canonicalize comparison!
7485 // Let's first invert the comparison's predicate.
7486 I.setPredicate(CmpInst::getInversePredicate(Pred));
7487 I.setName(I.getName() + ".not");
7488
7489 // And, adapt users.
7491
7492 return &I;
7493}
7494
7495/// Integer compare with boolean values can always be turned into bitwise ops.
7497 InstCombiner::BuilderTy &Builder) {
7498 Value *A = I.getOperand(0), *B = I.getOperand(1);
7499 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7500
7501 // A boolean compared to true/false can be simplified to Op0/true/false in
7502 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7503 // Cases not handled by InstSimplify are always 'not' of Op0.
7504 if (match(B, m_Zero())) {
7505 switch (I.getPredicate()) {
7506 case CmpInst::ICMP_EQ: // A == 0 -> !A
7507 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7508 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7510 default:
7511 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7512 }
7513 } else if (match(B, m_One())) {
7514 switch (I.getPredicate()) {
7515 case CmpInst::ICMP_NE: // A != 1 -> !A
7516 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7517 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7519 default:
7520 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7521 }
7522 }
7523
7524 switch (I.getPredicate()) {
7525 default:
7526 llvm_unreachable("Invalid icmp instruction!");
7527 case ICmpInst::ICMP_EQ:
7528 // icmp eq i1 A, B -> ~(A ^ B)
7529 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7530
7531 case ICmpInst::ICMP_NE:
7532 // icmp ne i1 A, B -> A ^ B
7533 return BinaryOperator::CreateXor(A, B);
7534
7535 case ICmpInst::ICMP_UGT:
7536 // icmp ugt -> icmp ult
7537 std::swap(A, B);
7538 [[fallthrough]];
7539 case ICmpInst::ICMP_ULT:
7540 // icmp ult i1 A, B -> ~A & B
7541 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7542
7543 case ICmpInst::ICMP_SGT:
7544 // icmp sgt -> icmp slt
7545 std::swap(A, B);
7546 [[fallthrough]];
7547 case ICmpInst::ICMP_SLT:
7548 // icmp slt i1 A, B -> A & ~B
7549 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7550
7551 case ICmpInst::ICMP_UGE:
7552 // icmp uge -> icmp ule
7553 std::swap(A, B);
7554 [[fallthrough]];
7555 case ICmpInst::ICMP_ULE:
7556 // icmp ule i1 A, B -> ~A | B
7557 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7558
7559 case ICmpInst::ICMP_SGE:
7560 // icmp sge -> icmp sle
7561 std::swap(A, B);
7562 [[fallthrough]];
7563 case ICmpInst::ICMP_SLE:
7564 // icmp sle i1 A, B -> A | ~B
7565 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7566 }
7567}
7568
7569// Transform pattern like:
7570// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7571// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7572// Into:
7573// (X l>> Y) != 0
7574// (X l>> Y) == 0
7576 InstCombiner::BuilderTy &Builder) {
7577 CmpPredicate Pred, NewPred;
7578 Value *X, *Y;
7579 if (match(&Cmp,
7580 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7581 switch (Pred) {
7582 case ICmpInst::ICMP_ULE:
7583 NewPred = ICmpInst::ICMP_NE;
7584 break;
7585 case ICmpInst::ICMP_UGT:
7586 NewPred = ICmpInst::ICMP_EQ;
7587 break;
7588 default:
7589 return nullptr;
7590 }
7591 } else if (match(&Cmp, m_c_ICmp(Pred,
7594 m_Add(m_Shl(m_One(), m_Value(Y)),
7595 m_AllOnes()))),
7596 m_Value(X)))) {
7597 // The variant with 'add' is not canonical, (the variant with 'not' is)
7598 // we only get it because it has extra uses, and can't be canonicalized,
7599
7600 switch (Pred) {
7601 case ICmpInst::ICMP_ULT:
7602 NewPred = ICmpInst::ICMP_NE;
7603 break;
7604 case ICmpInst::ICMP_UGE:
7605 NewPred = ICmpInst::ICMP_EQ;
7606 break;
7607 default:
7608 return nullptr;
7609 }
7610 } else
7611 return nullptr;
7612
7613 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7614 Constant *Zero = Constant::getNullValue(NewX->getType());
7615 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7616}
7617
7619 InstCombiner::BuilderTy &Builder) {
7620 const CmpInst::Predicate Pred = Cmp.getPredicate();
7621 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7622 Value *V1, *V2;
7623
7624 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7625 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7626 if (auto *I = dyn_cast<Instruction>(V))
7627 I->copyIRFlags(&Cmp);
7628 Module *M = Cmp.getModule();
7630 M, Intrinsic::vector_reverse, V->getType());
7631 return CallInst::Create(F, V);
7632 };
7633
7634 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7635 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7636 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7637 (LHS->hasOneUse() || RHS->hasOneUse()))
7638 return createCmpReverse(Pred, V1, V2);
7639
7640 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7641 if (LHS->hasOneUse() && isSplatValue(RHS))
7642 return createCmpReverse(Pred, V1, RHS);
7643 }
7644 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7645 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7646 return createCmpReverse(Pred, LHS, V2);
7647
7648 ArrayRef<int> M;
7649 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7650 return nullptr;
7651
7652 // If both arguments of the cmp are shuffles that use the same mask and
7653 // shuffle within a single vector, move the shuffle after the cmp:
7654 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7655 Type *V1Ty = V1->getType();
7656 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7657 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7658 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7659 return new ShuffleVectorInst(NewCmp, M);
7660 }
7661
7662 // Try to canonicalize compare with splatted operand and splat constant.
7663 // TODO: We could generalize this for more than splats. See/use the code in
7664 // InstCombiner::foldVectorBinop().
7665 Constant *C;
7666 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7667 return nullptr;
7668
7669 // Length-changing splats are ok, so adjust the constants as needed:
7670 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7671 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7672 int MaskSplatIndex;
7673 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7674 // We allow poison in matching, but this transform removes it for safety.
7675 // Demanded elements analysis should be able to recover some/all of that.
7676 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7677 ScalarC);
7678 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7679 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7680 return new ShuffleVectorInst(NewCmp, NewM);
7681 }
7682
7683 return nullptr;
7684}
7685
7686// extract(uadd.with.overflow(A, B), 0) ult A
7687// -> extract(uadd.with.overflow(A, B), 1)
7689 CmpInst::Predicate Pred = I.getPredicate();
7690 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7691
7692 Value *UAddOv;
7693 Value *A, *B;
7694 auto UAddOvResultPat = m_ExtractValue<0>(
7696 if (match(Op0, UAddOvResultPat) &&
7697 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7698 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7699 (match(A, m_One()) || match(B, m_One()))) ||
7700 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7701 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7702 // extract(uadd.with.overflow(A, B), 0) < A
7703 // extract(uadd.with.overflow(A, 1), 0) == 0
7704 // extract(uadd.with.overflow(A, -1), 0) != -1
7705 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7706 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7707 (Op0 == A || Op0 == B))
7708 // A > extract(uadd.with.overflow(A, B), 0)
7709 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7710 else
7711 return nullptr;
7712
7713 return ExtractValueInst::Create(UAddOv, 1);
7714}
7715
7717 if (!I.getOperand(0)->getType()->isPointerTy() ||
7719 I.getParent()->getParent(),
7720 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7721 return nullptr;
7722 }
7723 Value *Ptr;
7724 if (match(I.getOperand(0),
7726 match(I.getOperand(1), m_Zero())) {
7727 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(), Ptr,
7728 I.getOperand(1));
7729 }
7730 return nullptr;
7731}
7732
7734 IRBuilderBase &Builder) {
7735 if (!ICmpInst::isEquality(I.getPredicate()))
7736 return nullptr;
7737
7738 // The caller puts constants after non-constants.
7739 Value *Op = I.getOperand(0);
7740 Value *Const = I.getOperand(1);
7741
7742 // For Cond an equality condition, fold
7743 //
7744 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7745 // icmp (eq|ne) Op, (Zero|AllOnes)
7746 //
7747 // with a bitcast.
7748 Value *Vec;
7749 if ((match(Const, m_ZeroInt()) &&
7751 m_Value(Vec))))) ||
7752 (match(Const, m_AllOnes()) &&
7754 m_Value(Vec)))))) {
7755 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7756 if (!VecTy)
7757 return nullptr;
7758 Type *VecEltTy = VecTy->getElementType();
7759 unsigned ScalarBW =
7760 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7761 if (!DL.fitsInLegalInteger(ScalarBW))
7762 return nullptr;
7763 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7764 Value *NewConst = match(Const, m_ZeroInt())
7765 ? ConstantInt::get(ScalarTy, 0)
7766 : ConstantInt::getAllOnesValue(ScalarTy);
7767 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7768 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7769 }
7770 return nullptr;
7771}
7772
7773/// This function folds patterns produced by lowering of reduce idioms, such as
7774/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7775/// attempts to generate fewer number of scalar comparisons instead of vector
7776/// comparisons when possible.
7778 InstCombiner::BuilderTy &Builder,
7779 const DataLayout &DL) {
7780 if (I.getType()->isVectorTy())
7781 return nullptr;
7782 CmpPredicate OuterPred, InnerPred;
7783 Value *LHS, *RHS;
7784
7785 // Match lowering of @llvm.vector.reduce.and. Turn
7786 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7787 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7788 /// %res = icmp <pred> i8 %scalar_ne, 0
7789 ///
7790 /// into
7791 ///
7792 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7793 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7794 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7795 ///
7796 /// for <pred> in {ne, eq}.
7797 if (!match(&I, m_ICmp(OuterPred,
7799 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7800 m_Zero())))
7801 return nullptr;
7802 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7803 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7804 return nullptr;
7805 unsigned NumBits =
7806 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7807 // TODO: Relax this to "not wider than max legal integer type"?
7808 if (!DL.isLegalInteger(NumBits))
7809 return nullptr;
7810
7811 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7812 auto *ScalarTy = Builder.getIntNTy(NumBits);
7813 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7814 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7815 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7816 I.getName());
7817 }
7818
7819 return nullptr;
7820}
7821
7822// This helper will be called with icmp operands in both orders.
7824 Value *Op0, Value *Op1,
7825 ICmpInst &CtxI) {
7826 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7827 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7828 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CtxI))
7829 return NI;
7830
7831 if (auto *SI = dyn_cast<SelectInst>(Op0))
7832 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CtxI))
7833 return NI;
7834
7835 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7836 if (Instruction *Res = foldICmpWithMinMax(CtxI, MinMax, Op1, Pred))
7837 return Res;
7838
7839 if (Instruction *Res = foldICmpWithClamp(CtxI, Op1, MinMax))
7840 return Res;
7841 }
7842
7843 {
7844 Value *X;
7845 const APInt *C;
7846 // icmp X+Cst, X
7847 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7848 return foldICmpAddOpConst(X, *C, Pred);
7849 }
7850
7851 // abs(X) >= X --> true
7852 // abs(X) u<= X --> true
7853 // abs(X) < X --> false
7854 // abs(X) u> X --> false
7855 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7856 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7857 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7858 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7859 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7860 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7861 {
7862 Value *X;
7863 Constant *C;
7865 match(Op1, m_Specific(X))) {
7866 Value *NullValue = Constant::getNullValue(X->getType());
7867 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7868 const APInt SMin =
7869 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7870 bool IsIntMinPosion = C->isAllOnesValue();
7871 switch (Pred) {
7872 case CmpInst::ICMP_ULE:
7873 case CmpInst::ICMP_SGE:
7874 return replaceInstUsesWith(CtxI, ConstantInt::getTrue(CtxI.getType()));
7875 case CmpInst::ICMP_UGT:
7876 case CmpInst::ICMP_SLT:
7878 case CmpInst::ICMP_UGE:
7879 case CmpInst::ICMP_SLE:
7880 case CmpInst::ICMP_EQ: {
7881 return replaceInstUsesWith(
7882 CtxI, IsIntMinPosion
7883 ? Builder.CreateICmpSGT(X, AllOnesValue)
7884 : Builder.CreateICmpULT(
7885 X, ConstantInt::get(X->getType(), SMin + 1)));
7886 }
7887 case CmpInst::ICMP_ULT:
7888 case CmpInst::ICMP_SGT:
7889 case CmpInst::ICMP_NE: {
7890 return replaceInstUsesWith(
7891 CtxI, IsIntMinPosion
7892 ? Builder.CreateICmpSLT(X, NullValue)
7893 : Builder.CreateICmpUGT(
7894 X, ConstantInt::get(X->getType(), SMin)));
7895 }
7896 default:
7897 llvm_unreachable("Invalid predicate!");
7898 }
7899 }
7900 }
7901
7902 {
7903 // For a nonzero constant C:
7904 // usub.sat(X, C) == X --> X == 0
7905 // usub.sat(X, C) != X --> X != 0
7906 // usub.sat(X, C) < X --> X != 0
7908 m_NonZeroInt())) &&
7909 (CmpInst::isEquality(Pred) || Pred == ICmpInst::ICMP_ULT)) {
7910 ICmpInst::Predicate NewPred =
7911 CmpInst::isEquality(Pred) ? Pred.dropSameSign() : ICmpInst::ICMP_NE;
7912 return new ICmpInst(NewPred, Op1, Constant::getNullValue(Op1->getType()));
7913 }
7914 }
7915
7916 const SimplifyQuery Q = SQ.getWithInstruction(&CtxI);
7917 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
7918 return replaceInstUsesWith(CtxI, V);
7919
7920 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
7921 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
7922 {
7923 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7924 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7926 }
7927
7928 if (!ICmpInst::isUnsigned(Pred) &&
7929 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
7930 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7932 }
7933 }
7934
7935 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
7936 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
7937 {
7938 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7939 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7941 }
7942
7943 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
7944 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
7945 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
7947 }
7948 }
7949
7950 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
7951 // -> icmp X, (add nsw/nuw Y, K >> L)
7952 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
7953 Value *X;
7954 uint64_t ShAmt;
7955 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7956 !CtxI.isSigned()) {
7957 if (ShAmt >= X->getType()->getScalarSizeInBits())
7958 return nullptr;
7959 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7960 ShiftSemantics::Unsigned, &CtxI)) {
7961 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7963 return new ICmpInst(Pred, X, NewOp1);
7964 }
7965 }
7966
7967 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
7968 !CtxI.isUnsigned()) {
7969 if (ShAmt >= X->getType()->getScalarSizeInBits())
7970 return nullptr;
7971 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
7972 ShiftSemantics::Signed, &CtxI)) {
7973 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
7975 return new ICmpInst(Pred, X, NewOp1);
7976 }
7977 }
7978 return nullptr;
7979}
7980
7982 bool Changed = false;
7983 const SimplifyQuery Q = SQ.getWithInstruction(&I);
7984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7985 unsigned Op0Cplxity = getComplexity(Op0);
7986 unsigned Op1Cplxity = getComplexity(Op1);
7987
7988 /// Orders the operands of the compare so that they are listed from most
7989 /// complex to least complex. This puts constants before unary operators,
7990 /// before binary operators.
7991 if (Op0Cplxity < Op1Cplxity) {
7992 I.swapOperands();
7993 std::swap(Op0, Op1);
7994 Changed = true;
7995 }
7996
7997 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
7998 return replaceInstUsesWith(I, V);
7999
8000 // Comparing -val or val with non-zero is the same as just comparing val
8001 // ie, abs(val) != 0 -> val != 0
8002 if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
8003 Value *Cond, *SelectTrue, *SelectFalse;
8004 if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
8005 m_Value(SelectFalse)))) {
8006 if (Value *V = dyn_castNegVal(SelectTrue)) {
8007 if (V == SelectFalse)
8008 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
8009 } else if (Value *V = dyn_castNegVal(SelectFalse)) {
8010 if (V == SelectTrue)
8011 return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
8012 }
8013 }
8014 }
8015
8017 return Res;
8018
8019 if (Op0->getType()->isIntOrIntVectorTy(1))
8021 return Res;
8022
8024 return Res;
8025
8027 return Res;
8028
8030 return Res;
8031
8033 return Res;
8034
8036 return Res;
8037
8039 return Res;
8040
8042 return Res;
8043
8044 // Test if the ICmpInst instruction is used exclusively by a select as
8045 // part of a minimum or maximum operation. If so, refrain from doing
8046 // any other folding. This helps out other analyses which understand
8047 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8048 // and CodeGen. And in this case, at least one of the comparison
8049 // operands has at least one user besides the compare (the select),
8050 // which would often largely negate the benefit of folding anyway.
8051 //
8052 // Do the same for the other patterns recognized by matchSelectPattern.
8053 if (I.hasOneUse())
8054 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8055 Value *A, *B;
8057 if (SPR.Flavor != SPF_UNKNOWN)
8058 return nullptr;
8059 }
8060
8061 // Do this after checking for min/max to prevent infinite looping.
8062 if (Instruction *Res = foldICmpWithZero(I))
8063 return Res;
8064
8065 Value *X;
8066 const APInt *C;
8067 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8068 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8069 match(Op1, m_Not(m_Specific(X)))) {
8070 if (C->isNonNegative())
8071 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8072 Constant::getNullValue(X->getType()));
8073 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8074 ConstantInt::get(X->getType(), ~*C));
8075 }
8076
8077 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8078 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8079 match(Op1, m_Not(m_Specific(X)))) {
8080 if (C->isNonNegative())
8081 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8082 Constant::getAllOnesValue(X->getType()));
8083 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8084 ConstantInt::get(X->getType(), ~*C));
8085 }
8086
8087 // FIXME: We only do this after checking for min/max to prevent infinite
8088 // looping caused by a reverse canonicalization of these patterns for min/max.
8089 // FIXME: The organization of folds is a mess. These would naturally go into
8090 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8091 // down here after the min/max restriction.
8092 ICmpInst::Predicate Pred = I.getPredicate();
8093 if (match(Op1, m_APInt(C))) {
8094 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8095 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8096 Constant *Zero = Constant::getNullValue(Op0->getType());
8097 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8098 }
8099
8100 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8101 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8103 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8104 }
8105 }
8106
8107 // The folds in here may rely on wrapping flags and special constants, so
8108 // they can break up min/max idioms in some cases but not seemingly similar
8109 // patterns.
8110 // FIXME: It may be possible to enhance select folding to make this
8111 // unnecessary. It may also be moot if we canonicalize to min/max
8112 // intrinsics.
8113 if (Instruction *Res = foldICmpBinOp(I, Q))
8114 return Res;
8115
8117 return Res;
8118
8119 // Try to match comparison as a sign bit test. Intentionally do this after
8120 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8121 if (Instruction *New = foldSignBitTest(I))
8122 return New;
8123
8124 if (auto *PN = dyn_cast<PHINode>(Op0))
8125 if (Instruction *NV = foldOpIntoPhi(I, PN))
8126 return NV;
8127 if (auto *PN = dyn_cast<PHINode>(Op1))
8128 if (Instruction *NV = foldOpIntoPhi(I, PN))
8129 return NV;
8130
8132 return Res;
8133
8134 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8135 return Res;
8136 if (Instruction *Res =
8137 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8138 return Res;
8139
8140 if (I.isCommutative()) {
8141 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8142 replaceOperand(I, 0, Pair->first);
8143 replaceOperand(I, 1, Pair->second);
8144 return &I;
8145 }
8146 }
8147
8148 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8149 // when all select arms are constants, via truth table.
8151 return R;
8152
8153 // In case of a comparison with two select instructions having the same
8154 // condition, check whether one of the resulting branches can be simplified.
8155 // If so, just compare the other branch and select the appropriate result.
8156 // For example:
8157 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8158 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8159 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8160 // The icmp will result false for the false value of selects and the result
8161 // will depend upon the comparison of true values of selects if %cmp is
8162 // true. Thus, transform this into:
8163 // %cmp = icmp slt i32 %y, %z
8164 // %sel = select i1 %cond, i1 %cmp, i1 false
8165 // This handles similar cases to transform.
8166 {
8167 Value *Cond, *A, *B, *C, *D;
8168 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8170 (Op0->hasOneUse() || Op1->hasOneUse())) {
8171 // Check whether comparison of TrueValues can be simplified
8172 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8173 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8174 return SelectInst::Create(Cond, Res, NewICMP, /*NameStr=*/"",
8175 /*InsertBefore=*/nullptr,
8176 cast<Instruction>(Op0));
8177 }
8178 // Check whether comparison of FalseValues can be simplified
8179 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8180 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8181 return SelectInst::Create(Cond, NewICMP, Res, /*NameStr=*/"",
8182 /*InsertBefore=*/nullptr,
8183 cast<Instruction>(Op0));
8184 }
8185 }
8186 }
8187
8188 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8189 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8190 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8191 {
8192 Value *A, *B;
8193 CmpPredicate CmpPred;
8194 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8196 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8197 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8198 bool I0NUW = I0->hasNoUnsignedWrap();
8199 bool I1NUW = I1->hasNoUnsignedWrap();
8200 bool I0NSW = I0->hasNoSignedWrap();
8201 bool I1NSW = I1->hasNoSignedWrap();
8202 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8203 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8204 (ICmpInst::isEquality(Pred) &&
8205 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8206 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8207 ConstantInt::get(Op0->getType(), 0));
8208 }
8209 }
8210 }
8211
8212 // Try to optimize equality comparisons against alloca-based pointers.
8213 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8214 assert(Op1->getType()->isPointerTy() &&
8215 "Comparing pointer with non-pointer?");
8216 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8217 if (foldAllocaCmp(Alloca))
8218 return nullptr;
8219 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8220 if (foldAllocaCmp(Alloca))
8221 return nullptr;
8222 }
8223
8224 if (Instruction *Res = foldICmpBitCast(I))
8225 return Res;
8226
8227 // TODO: Hoist this above the min/max bailout.
8229 return R;
8230
8231 {
8232 Value *X, *Y;
8233 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8234 // and (X & ~Y) != 0 --> (X & Y) == 0
8235 // if A is a power of 2.
8236 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8237 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8238 I.isEquality())
8239 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8240 Op1);
8241
8242 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8243 if (Op0->getType()->isIntOrIntVectorTy()) {
8244 bool ConsumesOp0, ConsumesOp1;
8245 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8246 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8247 (ConsumesOp0 || ConsumesOp1)) {
8248 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8249 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8250 assert(InvOp0 && InvOp1 &&
8251 "Mismatch between isFreeToInvert and getFreelyInverted");
8252 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8253 }
8254 }
8255
8256 Instruction *AddI = nullptr;
8258 m_Instruction(AddI))) &&
8259 isa<IntegerType>(X->getType())) {
8260 Value *Result;
8261 Constant *Overflow;
8262 // m_UAddWithOverflow can match patterns that do not include an explicit
8263 // "add" instruction, so check the opcode of the matched op.
8264 if (AddI->getOpcode() == Instruction::Add &&
8265 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8266 Result, Overflow)) {
8267 replaceInstUsesWith(*AddI, Result);
8268 eraseInstFromFunction(*AddI);
8269 return replaceInstUsesWith(I, Overflow);
8270 }
8271 }
8272
8273 // (zext X) + (zext Y) --> add + overflow check.
8274 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8275 if ((match(Op0, m_NUWAdd(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) ||
8276 match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y))))) &&
8277 match(Op1, m_APInt(C))) {
8278 if (Instruction *R = processUZExtIdiom(I, Op0, C, *this))
8279 return R;
8280 }
8281
8282 // Signbit test folds
8283 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8284 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8285 Instruction *ExtI;
8286 if ((I.isUnsigned() || I.isEquality()) &&
8287 match(Op1,
8289 Y->getType()->getScalarSizeInBits() == 1 &&
8290 (Op0->hasOneUse() || Op1->hasOneUse())) {
8291 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8292 Instruction *ShiftI;
8293 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8295 OpWidth - 1))))) {
8296 unsigned ExtOpc = ExtI->getOpcode();
8297 unsigned ShiftOpc = ShiftI->getOpcode();
8298 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8299 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8300 Value *SLTZero =
8301 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8302 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8303 return replaceInstUsesWith(I, Cmp);
8304 }
8305 }
8306 }
8307 }
8308
8309 if (Instruction *Res = foldICmpEquality(I))
8310 return Res;
8311
8313 return Res;
8314
8315 if (Instruction *Res = foldICmpOfUAddOv(I))
8316 return Res;
8317
8319 return Res;
8320
8321 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8322 // an i1 which indicates whether or not we successfully did the swap.
8323 //
8324 // Replace comparisons between the old value and the expected value with the
8325 // indicator that 'cmpxchg' returns.
8326 //
8327 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8328 // spuriously fail. In those cases, the old value may equal the expected
8329 // value but it is possible for the swap to not occur.
8330 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8331 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8332 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8333 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8334 !ACXI->isWeak())
8335 return ExtractValueInst::Create(ACXI, 1);
8336
8338 return Res;
8339
8340 if (I.getType()->isVectorTy())
8341 if (Instruction *Res = foldVectorCmp(I, Builder))
8342 return Res;
8343
8345 return Res;
8346
8348 return Res;
8349
8350 {
8351 Value *A;
8352 const APInt *C1, *C2;
8353 ICmpInst::Predicate Pred = I.getPredicate();
8354 if (ICmpInst::isEquality(Pred)) {
8355 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8356 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8357 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8358 match(Op1, m_APInt(C2))) {
8359 Type *InputTy = A->getType();
8360 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8361 // c2 must be non-negative at the bitwidth of a.
8362 if (C2->getActiveBits() < InputBitWidth) {
8363 APInt TruncC1 = C1->trunc(InputBitWidth);
8364 // Check if there are 1s in C1 high bits of size InputBitWidth.
8365 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8366 TruncC1.setBit(InputBitWidth - 1);
8367 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8368 return new ICmpInst(
8369 Pred, AndInst,
8370 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8371 }
8372 }
8373 }
8374 }
8375
8376 return Changed ? &I : nullptr;
8377}
8378
8379/// Fold fcmp ([us]itofp x, cst) if possible.
8381 Instruction *LHSI,
8382 Constant *RHSC) {
8383 const APFloat *RHS;
8384 if (!match(RHSC, m_APFloat(RHS)))
8385 return nullptr;
8386
8387 // Get the width of the mantissa. We don't want to hack on conversions that
8388 // might lose information from the integer, e.g. "i64 -> float"
8389 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8390 if (MantissaWidth == -1)
8391 return nullptr; // Unknown.
8392
8393 Type *IntTy = LHSI->getOperand(0)->getType();
8394 unsigned IntWidth = IntTy->getScalarSizeInBits();
8395 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8396
8397 if (I.isEquality()) {
8398 FCmpInst::Predicate P = I.getPredicate();
8399 bool IsExact = false;
8400 APSInt RHSCvt(IntWidth, LHSUnsigned);
8401 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8402
8403 // If the floating point constant isn't an integer value, we know if we will
8404 // ever compare equal / not equal to it.
8405 if (!IsExact) {
8406 // TODO: Can never be -0.0 and other non-representable values
8407 APFloat RHSRoundInt(*RHS);
8409 if (*RHS != RHSRoundInt) {
8411 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8412
8414 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8415 }
8416 }
8417
8418 // TODO: If the constant is exactly representable, is it always OK to do
8419 // equality compares as integer?
8420 }
8421
8422 // Check to see that the input is converted from an integer type that is small
8423 // enough that preserves all bits. TODO: check here for "known" sign bits.
8424 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8425
8426 // Following test does NOT adjust IntWidth downwards for signed inputs,
8427 // because the most negative value still requires all the mantissa bits
8428 // to distinguish it from one less than that value.
8429 if ((int)IntWidth > MantissaWidth) {
8430 // Conversion would lose accuracy. Check if loss can impact comparison.
8431 int Exp = ilogb(*RHS);
8432 if (Exp == APFloat::IEK_Inf) {
8433 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8434 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8435 // Conversion could create infinity.
8436 return nullptr;
8437 } else {
8438 // Note that if RHS is zero or NaN, then Exp is negative
8439 // and first condition is trivially false.
8440 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8441 // Conversion could affect comparison.
8442 return nullptr;
8443 }
8444 }
8445
8446 // Otherwise, we can potentially simplify the comparison. We know that it
8447 // will always come through as an integer value and we know the constant is
8448 // not a NAN (it would have been previously simplified).
8449 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8450
8452 switch (I.getPredicate()) {
8453 default:
8454 llvm_unreachable("Unexpected predicate!");
8455 case FCmpInst::FCMP_UEQ:
8456 case FCmpInst::FCMP_OEQ:
8457 Pred = ICmpInst::ICMP_EQ;
8458 break;
8459 case FCmpInst::FCMP_UGT:
8460 case FCmpInst::FCMP_OGT:
8461 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8462 break;
8463 case FCmpInst::FCMP_UGE:
8464 case FCmpInst::FCMP_OGE:
8465 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8466 break;
8467 case FCmpInst::FCMP_ULT:
8468 case FCmpInst::FCMP_OLT:
8469 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8470 break;
8471 case FCmpInst::FCMP_ULE:
8472 case FCmpInst::FCMP_OLE:
8473 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8474 break;
8475 case FCmpInst::FCMP_UNE:
8476 case FCmpInst::FCMP_ONE:
8477 Pred = ICmpInst::ICMP_NE;
8478 break;
8479 case FCmpInst::FCMP_ORD:
8480 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8481 case FCmpInst::FCMP_UNO:
8482 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8483 }
8484
8485 // Now we know that the APFloat is a normal number, zero or inf.
8486
8487 // See if the FP constant is too large for the integer. For example,
8488 // comparing an i8 to 300.0.
8489 if (!LHSUnsigned) {
8490 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8491 // and large values.
8492 APFloat SMax(RHS->getSemantics());
8493 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8495 if (SMax < *RHS) { // smax < 13123.0
8496 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8497 Pred == ICmpInst::ICMP_SLE)
8498 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8499 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8500 }
8501 } else {
8502 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8503 // +INF and large values.
8504 APFloat UMax(RHS->getSemantics());
8505 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8507 if (UMax < *RHS) { // umax < 13123.0
8508 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8509 Pred == ICmpInst::ICMP_ULE)
8510 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8511 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8512 }
8513 }
8514
8515 if (!LHSUnsigned) {
8516 // See if the RHS value is < SignedMin.
8517 APFloat SMin(RHS->getSemantics());
8518 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8520 if (SMin > *RHS) { // smin > 12312.0
8521 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8522 Pred == ICmpInst::ICMP_SGE)
8523 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8524 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8525 }
8526 } else {
8527 // See if the RHS value is < UnsignedMin.
8528 APFloat UMin(RHS->getSemantics());
8529 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8531 if (UMin > *RHS) { // umin > 12312.0
8532 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8533 Pred == ICmpInst::ICMP_UGE)
8534 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8535 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8536 }
8537 }
8538
8539 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8540 // [0, UMAX], but it may still be fractional. Check whether this is the case
8541 // using the IsExact flag.
8542 // Don't do this for zero, because -0.0 is not fractional.
8543 APSInt RHSInt(IntWidth, LHSUnsigned);
8544 bool IsExact;
8545 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8546 if (!RHS->isZero()) {
8547 if (!IsExact) {
8548 // If we had a comparison against a fractional value, we have to adjust
8549 // the compare predicate and sometimes the value. RHSC is rounded towards
8550 // zero at this point.
8551 switch (Pred) {
8552 default:
8553 llvm_unreachable("Unexpected integer comparison!");
8554 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8555 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8556 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8557 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8558 case ICmpInst::ICMP_ULE:
8559 // (float)int <= 4.4 --> int <= 4
8560 // (float)int <= -4.4 --> false
8561 if (RHS->isNegative())
8562 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8563 break;
8564 case ICmpInst::ICMP_SLE:
8565 // (float)int <= 4.4 --> int <= 4
8566 // (float)int <= -4.4 --> int < -4
8567 if (RHS->isNegative())
8568 Pred = ICmpInst::ICMP_SLT;
8569 break;
8570 case ICmpInst::ICMP_ULT:
8571 // (float)int < -4.4 --> false
8572 // (float)int < 4.4 --> int <= 4
8573 if (RHS->isNegative())
8574 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8575 Pred = ICmpInst::ICMP_ULE;
8576 break;
8577 case ICmpInst::ICMP_SLT:
8578 // (float)int < -4.4 --> int < -4
8579 // (float)int < 4.4 --> int <= 4
8580 if (!RHS->isNegative())
8581 Pred = ICmpInst::ICMP_SLE;
8582 break;
8583 case ICmpInst::ICMP_UGT:
8584 // (float)int > 4.4 --> int > 4
8585 // (float)int > -4.4 --> true
8586 if (RHS->isNegative())
8587 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8588 break;
8589 case ICmpInst::ICMP_SGT:
8590 // (float)int > 4.4 --> int > 4
8591 // (float)int > -4.4 --> int >= -4
8592 if (RHS->isNegative())
8593 Pred = ICmpInst::ICMP_SGE;
8594 break;
8595 case ICmpInst::ICMP_UGE:
8596 // (float)int >= -4.4 --> true
8597 // (float)int >= 4.4 --> int > 4
8598 if (RHS->isNegative())
8599 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8600 Pred = ICmpInst::ICMP_UGT;
8601 break;
8602 case ICmpInst::ICMP_SGE:
8603 // (float)int >= -4.4 --> int >= -4
8604 // (float)int >= 4.4 --> int > 4
8605 if (!RHS->isNegative())
8606 Pred = ICmpInst::ICMP_SGT;
8607 break;
8608 }
8609 }
8610 }
8611
8612 // Lower this FP comparison into an appropriate integer version of the
8613 // comparison.
8614 return new ICmpInst(Pred, LHSI->getOperand(0),
8615 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8616}
8617
8618/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8619/// where all true/false values are constants that allow the compare to be
8620/// constant-folded for every combination of C1 and C2.
8621/// We compute a 4-entry truth table and use createLogicFromTable to
8622/// synthesize a boolean expression of C1 and C2.
8624 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8625 Value *C1, *C2;
8626 Constant *TV1, *FV1, *TV2, *FV2;
8627
8628 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8629 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8630 return nullptr;
8631
8632 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8633 return nullptr;
8634
8635 unsigned Pred = I.getPredicate();
8636 const DataLayout &DL = I.getDataLayout();
8637
8638 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8639 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8640 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8641 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8642
8643 if (!Res00 || !Res01 || !Res10 || !Res11)
8644 return nullptr;
8645
8646 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8647 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8648 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8649 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8650 return nullptr;
8651
8652 std::bitset<4> Table;
8653 if (!Res00->isNullValue())
8654 Table.set(0);
8655 if (!Res01->isNullValue())
8656 Table.set(1);
8657 if (!Res10->isNullValue())
8658 Table.set(2);
8659 if (!Res11->isNullValue())
8660 Table.set(3);
8661
8662 Value *Res = createLogicFromTable(Table, C1, C2, Builder,
8663 Op0->hasOneUse() && Op1->hasOneUse());
8664 if (!Res)
8665 return nullptr;
8666 return replaceInstUsesWith(I, Res);
8667}
8668
8669/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8671 Constant *RHSC) {
8672 // When C is not 0.0 and infinities are not allowed:
8673 // (C / X) < 0.0 is a sign-bit test of X
8674 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8675 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8676 //
8677 // Proof:
8678 // Multiply (C / X) < 0.0 by X * X / C.
8679 // - X is non zero, if it is the flag 'ninf' is violated.
8680 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8681 // the predicate. C is also non zero by definition.
8682 //
8683 // Thus X * X / C is non zero and the transformation is valid. [qed]
8684
8685 FCmpInst::Predicate Pred = I.getPredicate();
8686
8687 // Check that predicates are valid.
8688 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8689 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8690 return nullptr;
8691
8692 // Check that RHS operand is zero.
8693 if (!match(RHSC, m_AnyZeroFP()))
8694 return nullptr;
8695
8696 // Check fastmath flags ('ninf').
8697 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8698 return nullptr;
8699
8700 // Check the properties of the dividend. It must not be zero to avoid a
8701 // division by zero (see Proof).
8702 const APFloat *C;
8703 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8704 return nullptr;
8705
8706 if (C->isZero())
8707 return nullptr;
8708
8709 // Get swapped predicate if necessary.
8710 if (C->isNegative())
8711 Pred = I.getSwappedPredicate();
8712
8713 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8714}
8715
8716// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8717// Patterns include:
8718// fptrunc(x) < C --> x < ext(C)
8719// fptrunc(x) <= C --> x <= ext(C)
8720// fptrunc(x) > C --> x > ext(C)
8721// fptrunc(x) >= C --> x >= ext(C)
8722// fptrunc(x) ord/uno C --> x ord/uno 0
8723// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8724// due to precision loss.
8726 const Constant &C) {
8727 FCmpInst::Predicate Pred = I.getPredicate();
8728 Type *DestType = FPTrunc.getOperand(0)->getType();
8729
8730 const APFloat *CValue;
8731 // TODO: support vec
8732 if (!match(&C, m_APFloat(CValue)))
8733 return nullptr;
8734
8735 // Handle ord/uno
8736 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8737 assert(!CValue->isNaN() &&
8738 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8739 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8740 ConstantFP::getZero(DestType), "", &I);
8741 }
8742
8743 // Handle <, >, <=, >=
8744 bool RoundDown = false;
8745
8746 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8747 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8748 RoundDown = true;
8749 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8750 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8751 RoundDown = false;
8752 else
8753 return nullptr;
8754
8755 if (CValue->isNaN() || CValue->isInfinity())
8756 return nullptr;
8757
8758 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8759 bool LosesInfo;
8760 APFloat Dest = Src;
8761 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8762 return Dest;
8763 };
8764
8765 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8766 APFloat NextValue = Value;
8767 NextValue.next(RoundDown);
8768 return NextValue;
8769 };
8770
8771 APFloat NextCValue = NextValue(*CValue, RoundDown);
8772
8773 const fltSemantics &DestFltSema =
8774 DestType->getScalarType()->getFltSemantics();
8775
8776 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8777 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8778
8779 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8780 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8781 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8782 // value of 'CValue'.
8783 if (NextCValue.isInfinity()) {
8784 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8785 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8786
8787 ExtNextCValue = ExtCValue + Bias;
8788 }
8789
8790 APFloat ExtMidValue =
8791 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8792
8793 const fltSemantics &SrcFltSema =
8794 C.getType()->getScalarType()->getFltSemantics();
8795
8796 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8797 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8798 if (MidValue != *CValue)
8799 ExtMidValue.next(!RoundDown);
8800
8801 // Check whether 'ExtMidValue' is a valid result since the assumption on
8802 // imaged 'NextCValue' might not hold for new float types.
8803 // ppc_fp128 can't pass here when converting from max float because of
8804 // APFloat implementation.
8805 if (NextCValue.isInfinity()) {
8806 // ExtMidValue --- narrowed ---> Finite
8807 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8808 return nullptr;
8809
8810 // NextExtMidValue --- narrowed ---> Infinity
8811 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8812 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8813 return nullptr;
8814 }
8815
8816 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8817 ConstantFP::get(DestType, ExtMidValue), "", &I);
8818}
8819
8820/// Optimize fabs(X) compared with zero.
8822 Value *X;
8823 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8824 return nullptr;
8825
8826 const APFloat *C;
8827 if (!match(I.getOperand(1), m_APFloat(C)))
8828 return nullptr;
8829
8830 if (!C->isPosZero()) {
8831 if (!C->isSmallestNormalized())
8832 return nullptr;
8833
8834 const Function *F = I.getFunction();
8835 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8836 if (Mode.Input == DenormalMode::PreserveSign ||
8838
8839 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8840 Constant *Zero = ConstantFP::getZero(X->getType());
8841 return new FCmpInst(P, X, Zero, "", I);
8842 };
8843
8844 switch (I.getPredicate()) {
8845 case FCmpInst::FCMP_OLT:
8846 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8847 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8848 case FCmpInst::FCMP_UGE:
8849 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8850 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8851 case FCmpInst::FCMP_OGE:
8852 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8853 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8854 case FCmpInst::FCMP_ULT:
8855 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8856 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8857 default:
8858 break;
8859 }
8860 }
8861
8862 return nullptr;
8863 }
8864
8865 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8866 I->setPredicate(P);
8867 return IC.replaceOperand(*I, 0, X);
8868 };
8869
8870 switch (I.getPredicate()) {
8871 case FCmpInst::FCMP_UGE:
8872 case FCmpInst::FCMP_OLT:
8873 // fabs(X) >= 0.0 --> true
8874 // fabs(X) < 0.0 --> false
8875 llvm_unreachable("fcmp should have simplified");
8876
8877 case FCmpInst::FCMP_OGT:
8878 // fabs(X) > 0.0 --> X != 0.0
8879 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
8880
8881 case FCmpInst::FCMP_UGT:
8882 // fabs(X) u> 0.0 --> X u!= 0.0
8883 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
8884
8885 case FCmpInst::FCMP_OLE:
8886 // fabs(X) <= 0.0 --> X == 0.0
8887 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
8888
8889 case FCmpInst::FCMP_ULE:
8890 // fabs(X) u<= 0.0 --> X u== 0.0
8891 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
8892
8893 case FCmpInst::FCMP_OGE:
8894 // fabs(X) >= 0.0 --> !isnan(X)
8895 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8896 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
8897
8898 case FCmpInst::FCMP_ULT:
8899 // fabs(X) u< 0.0 --> isnan(X)
8900 assert(!I.hasNoNaNs() && "fcmp should have simplified");
8901 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
8902
8903 case FCmpInst::FCMP_OEQ:
8904 case FCmpInst::FCMP_UEQ:
8905 case FCmpInst::FCMP_ONE:
8906 case FCmpInst::FCMP_UNE:
8907 case FCmpInst::FCMP_ORD:
8908 case FCmpInst::FCMP_UNO:
8909 // Look through the fabs() because it doesn't change anything but the sign.
8910 // fabs(X) == 0.0 --> X == 0.0,
8911 // fabs(X) != 0.0 --> X != 0.0
8912 // isnan(fabs(X)) --> isnan(X)
8913 // !isnan(fabs(X) --> !isnan(X)
8914 return replacePredAndOp0(&I, I.getPredicate(), X);
8915
8916 default:
8917 return nullptr;
8918 }
8919}
8920
8921/// Optimize sqrt(X) compared with zero.
8923 Value *X;
8924 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
8925 return nullptr;
8926
8927 if (!match(I.getOperand(1), m_PosZeroFP()))
8928 return nullptr;
8929
8930 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
8931 I.setPredicate(P);
8932 return IC.replaceOperand(I, 0, X);
8933 };
8934
8935 // Clear ninf flag if sqrt doesn't have it.
8936 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
8937 I.setHasNoInfs(false);
8938
8939 switch (I.getPredicate()) {
8940 case FCmpInst::FCMP_OLT:
8941 case FCmpInst::FCMP_UGE:
8942 // sqrt(X) < 0.0 --> false
8943 // sqrt(X) u>= 0.0 --> true
8944 llvm_unreachable("fcmp should have simplified");
8945 case FCmpInst::FCMP_ULT:
8946 case FCmpInst::FCMP_ULE:
8947 case FCmpInst::FCMP_OGT:
8948 case FCmpInst::FCMP_OGE:
8949 case FCmpInst::FCMP_OEQ:
8950 case FCmpInst::FCMP_UNE:
8951 // sqrt(X) u< 0.0 --> X u< 0.0
8952 // sqrt(X) u<= 0.0 --> X u<= 0.0
8953 // sqrt(X) > 0.0 --> X > 0.0
8954 // sqrt(X) >= 0.0 --> X >= 0.0
8955 // sqrt(X) == 0.0 --> X == 0.0
8956 // sqrt(X) u!= 0.0 --> X u!= 0.0
8957 return IC.replaceOperand(I, 0, X);
8958
8959 case FCmpInst::FCMP_OLE:
8960 // sqrt(X) <= 0.0 --> X == 0.0
8961 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
8962 case FCmpInst::FCMP_UGT:
8963 // sqrt(X) u> 0.0 --> X u!= 0.0
8964 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
8965 case FCmpInst::FCMP_UEQ:
8966 // sqrt(X) u== 0.0 --> X u<= 0.0
8967 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
8968 case FCmpInst::FCMP_ONE:
8969 // sqrt(X) != 0.0 --> X > 0.0
8970 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
8971 case FCmpInst::FCMP_ORD:
8972 // !isnan(sqrt(X)) --> X >= 0.0
8973 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
8974 case FCmpInst::FCMP_UNO:
8975 // isnan(sqrt(X)) --> X u< 0.0
8976 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
8977 default:
8978 llvm_unreachable("Unexpected predicate!");
8979 }
8980}
8981
8983 CmpInst::Predicate Pred = I.getPredicate();
8984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8985
8986 // Canonicalize fneg as Op1.
8987 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
8988 std::swap(Op0, Op1);
8989 Pred = I.getSwappedPredicate();
8990 }
8991
8992 if (!match(Op1, m_FNeg(m_Specific(Op0))))
8993 return nullptr;
8994
8995 // Replace the negated operand with 0.0:
8996 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
8997 Constant *Zero = ConstantFP::getZero(Op0->getType());
8998 return new FCmpInst(Pred, Op0, Zero, "", &I);
8999}
9000
9002 Constant *RHSC, InstCombinerImpl &CI) {
9003 const CmpInst::Predicate Pred = I.getPredicate();
9004 Value *X = LHSI->getOperand(0);
9005 Value *Y = LHSI->getOperand(1);
9006 switch (Pred) {
9007 default:
9008 break;
9009 case FCmpInst::FCMP_UGT:
9010 case FCmpInst::FCMP_ULT:
9011 case FCmpInst::FCMP_UNE:
9012 case FCmpInst::FCMP_OEQ:
9013 case FCmpInst::FCMP_OGE:
9014 case FCmpInst::FCMP_OLE:
9015 // The optimization is not valid if X and Y are infinities of the same
9016 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
9017 // flag then we can assume we do not have that case. Otherwise we might be
9018 // able to prove that either X or Y is not infinity.
9019 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
9023 break;
9024
9025 [[fallthrough]];
9026 case FCmpInst::FCMP_OGT:
9027 case FCmpInst::FCMP_OLT:
9028 case FCmpInst::FCMP_ONE:
9029 case FCmpInst::FCMP_UEQ:
9030 case FCmpInst::FCMP_UGE:
9031 case FCmpInst::FCMP_ULE:
9032 // fcmp pred (x - y), 0 --> fcmp pred x, y
9033 if (match(RHSC, m_AnyZeroFP()) &&
9034 I.getFunction()->getDenormalMode(
9035 LHSI->getType()->getScalarType()->getFltSemantics()) ==
9037 CI.replaceOperand(I, 0, X);
9038 CI.replaceOperand(I, 1, Y);
9039 I.setHasNoInfs(LHSI->hasNoInfs());
9040 if (LHSI->hasNoNaNs())
9041 I.setHasNoNaNs(true);
9042 return &I;
9043 }
9044 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9045 // where C and Y can't be arbitrary floating-point values.
9046 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9047 // to `1.0f`, so the source compare is false while the rewritten compare is
9048 // true.
9049 // We need to make sure (C - Y) never rounds back to C
9050 const APFloat *C;
9051 Value *IntSrc;
9052 if (match(RHSC, m_APFloat(C)) &&
9053 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
9054 C->isNormal()) {
9055 // Requirements on C and Y:
9056 // 1. C is finite, nonzero, normal.
9057 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9058 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9059 // must be integer-valued with an absolute value of at least 1;
9060 // as long as the step size near C does not exceed 1,
9061 // C - Y cannot be rounded back to C when Y != 0.
9062 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9063 // 0, 0` for ordered and unordered predicates as long as C is finite and
9064 // nonzero.
9065 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9066 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
9067 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
9068 I.setPredicate(I.getSwappedPredicate());
9069 CI.replaceOperand(I, 0, Y);
9070 CI.replaceOperand(I, 1, ZeroC);
9071 return &I;
9072 }
9073 }
9074 break;
9075 }
9076
9077 return nullptr;
9078}
9079
9080/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9081/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9082/// float when the uitofp casts are exact and C is in the valid range.
9083///
9084/// Since exact uitofp means distinct integers map to distinct floats, the only
9085/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9086/// There are no values in the open interval (0, 1), so:
9087/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9088// fabs(..) >= C where C >= 1.0 -> a != b
9089///
9090/// The same logic applies to sitofp.
9092 Value *FAbsArg;
9093 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
9094 return nullptr;
9095
9096 const APFloat *C;
9097 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
9098 return nullptr;
9099
9100 FCmpInst::Predicate Pred = I.getPredicate();
9101 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9102 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9103 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9104 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9105 if (!IsStrictLt && !IsStrictGt && !IsGe)
9106 return nullptr;
9107
9108 APFloat One = APFloat::getOne(C->getSemantics());
9109 APFloat::cmpResult Cmp = C->compare(One);
9110
9111 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9112 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9113 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9114 return nullptr;
9115 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9116 return nullptr;
9117 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9118 return nullptr;
9119 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9120 return nullptr;
9121
9122 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9123 Value *A, *B;
9124 bool IsSigned;
9125 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
9126 IsSigned = false;
9127 } else if (match(FAbsArg,
9129 IsSigned = true;
9130 } else {
9131 return nullptr;
9132 }
9133
9134 // A and B must have the same integer type
9135 if (A->getType() != B->getType())
9136 return nullptr;
9137
9138 Type *FPTy = FAbsArg->getType();
9139 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
9140 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
9141 return nullptr;
9142 ICmpInst::Predicate ResultPred =
9143 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9144 return new ICmpInst(ResultPred, A, B);
9145}
9146
9148 InstCombinerImpl &IC) {
9149 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9150 Type *OpType = LHS->getType();
9151 CmpInst::Predicate Pred = I.getPredicate();
9152
9155
9156 if (!FloorX && !CeilX) {
9159 std::swap(LHS, RHS);
9160 Pred = I.getSwappedPredicate();
9161 }
9162 }
9163
9164 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9165 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9166 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9167 // where pred is oeq, one, ord, ueq, une, uno.
9168 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
9169 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9170 }
9171
9172 switch (Pred) {
9173 case FCmpInst::FCMP_OLE:
9174 // fcmp ole floor(x), x => fcmp ord x, 0
9175 if (FloorX)
9177 "", &I);
9178 break;
9179 case FCmpInst::FCMP_OGT:
9180 // fcmp ogt floor(x), x => false
9181 if (FloorX)
9182 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9183 break;
9184 case FCmpInst::FCMP_OGE:
9185 // fcmp oge ceil(x), x => fcmp ord x, 0
9186 if (CeilX)
9188 "", &I);
9189 break;
9190 case FCmpInst::FCMP_OLT:
9191 // fcmp olt ceil(x), x => false
9192 if (CeilX)
9193 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9194 break;
9195 case FCmpInst::FCMP_ULE:
9196 // fcmp ule floor(x), x => true
9197 if (FloorX)
9198 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9199 break;
9200 case FCmpInst::FCMP_UGT:
9201 // fcmp ugt floor(x), x => fcmp uno x, 0
9202 if (FloorX)
9204 "", &I);
9205 break;
9206 case FCmpInst::FCMP_UGE:
9207 // fcmp uge ceil(x), x => true
9208 if (CeilX)
9209 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9210 break;
9211 case FCmpInst::FCMP_ULT:
9212 // fcmp ult ceil(x), x => fcmp uno x, 0
9213 if (CeilX)
9215 "", &I);
9216 break;
9217 default:
9218 break;
9219 }
9220
9221 return nullptr;
9222}
9223
9224/// Returns true if a select that implements a min/max is redundant and
9225/// select result can be replaced with its non-constant operand, e.g.,
9226/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9227/// where C is the FP constant equal to the minimum integer value
9228/// representable by A.
9230 Value *B) {
9231 const APFloat *APF;
9232 if (!match(B, m_APFloat(APF)))
9233 return false;
9234
9235 auto *I = dyn_cast<Instruction>(A);
9236 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9237 I->getOpcode() == Instruction::UIToFP))
9238 return false;
9239
9240 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9241 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9242 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9243 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9244 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9245 APSInt ConvertedInt(BitWidth, IsUnsigned);
9246 bool IsExact;
9248 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9249 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9250}
9251
9253 bool Changed = false;
9254
9255 /// Orders the operands of the compare so that they are listed from most
9256 /// complex to least complex. This puts constants before unary operators,
9257 /// before binary operators.
9258 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9259 I.swapOperands();
9260 Changed = true;
9261 }
9262
9263 const CmpInst::Predicate Pred = I.getPredicate();
9264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9265 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9266 SQ.getWithInstruction(&I)))
9267 return replaceInstUsesWith(I, V);
9268
9269 // Simplify 'fcmp pred X, X'
9270 Type *OpType = Op0->getType();
9271 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9272 if (Op0 == Op1) {
9273 switch (Pred) {
9274 default:
9275 break;
9276 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9277 case FCmpInst::FCMP_ULT: // True if unordered or less than
9278 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9279 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9280 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9281 I.setPredicate(FCmpInst::FCMP_UNO);
9282 I.setOperand(1, Constant::getNullValue(OpType));
9283 return &I;
9284
9285 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9286 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9287 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9288 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9289 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9290 I.setPredicate(FCmpInst::FCMP_ORD);
9291 I.setOperand(1, Constant::getNullValue(OpType));
9292 return &I;
9293 }
9294 }
9295
9296 if (I.isCommutative()) {
9297 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9298 replaceOperand(I, 0, Pair->first);
9299 replaceOperand(I, 1, Pair->second);
9300 return &I;
9301 }
9302 }
9303
9304 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9305 // then canonicalize the operand to 0.0.
9306 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9307 if (!match(Op0, m_PosZeroFP()) &&
9308 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9309 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9310
9311 if (!match(Op1, m_PosZeroFP()) &&
9312 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9313 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9314 }
9315
9316 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9317 Value *X, *Y;
9318 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
9319 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9320
9322 return R;
9323
9324 // Test if the FCmpInst instruction is used exclusively by a select as
9325 // part of a minimum or maximum operation. If so, refrain from doing
9326 // any other folding. This helps out other analyses which understand
9327 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9328 // and CodeGen. And in this case, at least one of the comparison
9329 // operands has at least one user besides the compare (the select),
9330 // which would often largely negate the benefit of folding anyway.
9331 if (I.hasOneUse())
9332 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9333 Value *A, *B;
9335 bool IsRedundantMinMaxClamp =
9336 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9338 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9339 return nullptr;
9340 }
9341
9342 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9343 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9344 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9345 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9346
9347 // Canonicalize:
9348 // fcmp olt X, +inf -> fcmp one X, +inf
9349 // fcmp ole X, +inf -> fcmp ord X, 0
9350 // fcmp ogt X, +inf -> false
9351 // fcmp oge X, +inf -> fcmp oeq X, +inf
9352 // fcmp ult X, +inf -> fcmp une X, +inf
9353 // fcmp ule X, +inf -> true
9354 // fcmp ugt X, +inf -> fcmp uno X, 0
9355 // fcmp uge X, +inf -> fcmp ueq X, +inf
9356 // fcmp olt X, -inf -> false
9357 // fcmp ole X, -inf -> fcmp oeq X, -inf
9358 // fcmp ogt X, -inf -> fcmp one X, -inf
9359 // fcmp oge X, -inf -> fcmp ord X, 0
9360 // fcmp ult X, -inf -> fcmp uno X, 0
9361 // fcmp ule X, -inf -> fcmp ueq X, -inf
9362 // fcmp ugt X, -inf -> fcmp une X, -inf
9363 // fcmp uge X, -inf -> true
9364 const APFloat *C;
9365 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9366 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9367 default:
9368 break;
9369 case FCmpInst::FCMP_ORD:
9370 case FCmpInst::FCMP_UNO:
9373 case FCmpInst::FCMP_OGT:
9374 case FCmpInst::FCMP_ULE:
9375 llvm_unreachable("Should be simplified by InstSimplify");
9376 case FCmpInst::FCMP_OLT:
9377 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9378 case FCmpInst::FCMP_OLE:
9379 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9380 "", &I);
9381 case FCmpInst::FCMP_OGE:
9382 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9383 case FCmpInst::FCMP_ULT:
9384 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9385 case FCmpInst::FCMP_UGT:
9386 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9387 "", &I);
9388 case FCmpInst::FCMP_UGE:
9389 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9390 }
9391 }
9392
9393 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9394 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9395 if (match(Op1, m_PosZeroFP()) &&
9397 X->getType()->isIntOrIntVectorTy() &&
9398 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9399 .inputsMayBeZero()) {
9401 if (Pred == FCmpInst::FCMP_OEQ)
9402 IntPred = ICmpInst::ICMP_EQ;
9403 else if (Pred == FCmpInst::FCMP_UNE)
9404 IntPred = ICmpInst::ICMP_NE;
9405
9406 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9407 Type *IntTy = X->getType();
9408 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9409 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9410 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9411 }
9412 }
9413
9414 // Handle fcmp with instruction LHS and constant RHS.
9415 Instruction *LHSI;
9416 Constant *RHSC;
9417 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9418 switch (LHSI->getOpcode()) {
9419 case Instruction::Select:
9420 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9421 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9423 return replaceOperand(I, 0, X);
9425 return NV;
9426 break;
9427 case Instruction::FSub:
9428 if (LHSI->hasOneUse())
9429 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9430 return NV;
9431 break;
9432 case Instruction::PHI:
9433 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9434 return NV;
9435 break;
9436 case Instruction::SIToFP:
9437 case Instruction::UIToFP:
9438 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9439 return NV;
9440 break;
9441 case Instruction::FDiv:
9442 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9443 return NV;
9444 break;
9445 case Instruction::Load:
9446 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
9447 if (Instruction *Res =
9449 return Res;
9450 break;
9451 case Instruction::FPTrunc:
9452 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9453 return NV;
9454 break;
9455 }
9456 }
9457
9458 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9459 return R;
9460
9461 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9462 return R;
9463
9464 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9465 return R;
9466
9467 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9468 return R;
9469
9471 return R;
9472
9473 if (match(Op0, m_FNeg(m_Value(X)))) {
9474 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9475 Constant *C;
9476 if (match(Op1, m_Constant(C)))
9477 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9478 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9479 }
9480
9481 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9482 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9483 return new FCmpInst(Pred, X, Op1, "", &I);
9484
9485 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9486 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9487 return new FCmpInst(Pred, Op0, Y, "", &I);
9488
9489 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9490 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9491 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9492 X->getType() == Y->getType())
9493 return new FCmpInst(Pred, X, Y, "", &I);
9494
9495 if (match(Op0, m_FPExt(m_Value(X)))) {
9496 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9497 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9498 return new FCmpInst(Pred, X, Y, "", &I);
9499
9500 const APFloat *C;
9501 if (match(Op1, m_APFloat(C))) {
9502 const fltSemantics &FPSem =
9503 X->getType()->getScalarType()->getFltSemantics();
9504 bool Lossy;
9505 APFloat TruncC = *C;
9507
9508 if (Lossy) {
9509 // X can't possibly equal the higher-precision constant, so reduce any
9510 // equality comparison.
9511 // TODO: Other predicates can be handled via getFCmpCode().
9512 switch (Pred) {
9513 case FCmpInst::FCMP_OEQ:
9514 // X is ordered and equal to an impossible constant --> false
9515 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9516 case FCmpInst::FCMP_ONE:
9517 // X is ordered and not equal to an impossible constant --> ordered
9518 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9519 ConstantFP::getZero(X->getType()));
9520 case FCmpInst::FCMP_UEQ:
9521 // X is unordered or equal to an impossible constant --> unordered
9522 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9523 ConstantFP::getZero(X->getType()));
9524 case FCmpInst::FCMP_UNE:
9525 // X is unordered or not equal to an impossible constant --> true
9526 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9527 default:
9528 break;
9529 }
9530 }
9531
9532 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9533 // Avoid lossy conversions and denormals.
9534 // Zero is a special case that's OK to convert.
9535 APFloat Fabs = TruncC;
9536 Fabs.clearSign();
9537 if (!Lossy &&
9538 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9539 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9540 return new FCmpInst(Pred, X, NewC, "", &I);
9541 }
9542 }
9543 }
9544
9545 // Convert a sign-bit test of an FP value into a cast and integer compare.
9546 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9547 // TODO: Handle non-zero compare constants.
9548 // TODO: Handle other predicates.
9550 m_Value(X)))) &&
9551 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9552 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9553 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9554 IntType = VectorType::get(IntType, VecTy->getElementCount());
9555
9556 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9557 if (Pred == FCmpInst::FCMP_OLT) {
9558 Value *IntX = Builder.CreateBitCast(X, IntType);
9559 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9560 ConstantInt::getNullValue(IntType));
9561 }
9562 }
9563
9564 {
9565 Value *CanonLHS = nullptr;
9567 // (canonicalize(x) == x) => (x == x)
9568 if (CanonLHS == Op1)
9569 return new FCmpInst(Pred, Op1, Op1, "", &I);
9570
9571 Value *CanonRHS = nullptr;
9573 // (x == canonicalize(x)) => (x == x)
9574 if (CanonRHS == Op0)
9575 return new FCmpInst(Pred, Op0, Op0, "", &I);
9576
9577 // (canonicalize(x) == canonicalize(y)) => (x == y)
9578 if (CanonLHS && CanonRHS)
9579 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9580 }
9581
9582 if (I.getType()->isVectorTy())
9583 if (Instruction *Res = foldVectorCmp(I, Builder))
9584 return Res;
9585
9586 return Changed ? &I : nullptr;
9587}
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:540
#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:333
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:6034
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:5963
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:230
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:445
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:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
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:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
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:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
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:1083
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:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1635
unsigned logBase2() const
Definition APInt.h:1781
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:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
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:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
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
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
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
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
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
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:773
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
iterator end()
Definition DenseMap.h:702
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:1557
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:179
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2484
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1579
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:471
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:2901
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.
OverflowResult computeOverflow(Instruction::BinaryOps BinaryOp, bool IsSigned, Value *LHS, Value *RHS, Instruction *CtxI) const
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 * 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,...
const InstCombineCLOptions & CLOpts
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 * foldICmpCommutative(CmpPredicate Pred, Value *Op0, Value *Op1, ICmpInst &CtxI)
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)
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.
SimplifyQuery SQ
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
LLVM_ABI bool canBeCastedExactlyIntToFP(Value *V, Type *FPTy, bool IsSigned, const Instruction *CtxI=nullptr) const
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
static unsigned getComplexity(Value *V)
Assign a complexity or rank value to LLVM Values.
unsigned ComputeMaxSignificantBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero=false, const Instruction *CtxI=nullptr, unsigned Depth=0)
TargetLibraryInfo & TLI
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const Instruction *CtxI) 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
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 ?
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CtxI) const
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const Instruction *CtxI, bool IsNSW=false) const
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const Instruction *CtxI) const
DominatorTree & DT
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const Instruction *CtxI) const
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
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.
iterator_range< user_iterator > users()
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:338
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:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
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:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
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:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
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:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
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:712
iterator_range< use_iterator > uses()
Definition Value.h:382
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.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
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:846
@ 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.
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:1755
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,...
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 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 isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=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.
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 Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
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.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
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:972
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 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:1769
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.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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:2035
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:2182
@ Continue
Definition DWP.h:26
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:224
GEPNoWrapFlags Flags
Definition Loads.h:229
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 DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const Instruction * CtxI
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
Capture information for a specific Use.