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/APInt.h"
16#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/Loads.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/InstrTypes.h"
31#include "llvm/IR/Instruction.h"
37#include <bitset>
38
39using namespace llvm;
40using namespace PatternMatch;
41
42#define DEBUG_TYPE "instcombine"
43
44// How many times is a select replaced by one of its operands?
45STATISTIC(NumSel, "Number of select opts");
46
47/// Compute Result = In1+In2, returning true if the result overflowed for this
48/// type.
49static bool addWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
50 bool IsSigned = false) {
51 bool Overflow;
52 if (IsSigned)
53 Result = In1.sadd_ov(In2, Overflow);
54 else
55 Result = In1.uadd_ov(In2, Overflow);
56
57 return Overflow;
58}
59
60/// Compute Result = In1-In2, returning true if the result overflowed for this
61/// type.
62static bool subWithOverflow(APInt &Result, const APInt &In1, const APInt &In2,
63 bool IsSigned = false) {
64 bool Overflow;
65 if (IsSigned)
66 Result = In1.ssub_ov(In2, Overflow);
67 else
68 Result = In1.usub_ov(In2, Overflow);
69
70 return Overflow;
71}
72
73/// Given an icmp instruction, return true if any use of this comparison is a
74/// branch on sign bit comparison.
75static bool hasBranchUse(ICmpInst &I) {
76 for (auto *U : I.users())
77 if (isa<CondBrInst>(U))
78 return true;
79 return false;
80}
81
82/// Returns true if the exploded icmp can be expressed as a signed comparison
83/// to zero and updates the predicate accordingly.
84/// The signedness of the comparison is preserved.
85/// TODO: Refactor with decomposeBitTestICmp()?
86static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
88 return false;
89
90 if (C.isZero())
92
93 if (C.isOne()) {
94 if (Pred == ICmpInst::ICMP_SLT) {
96 return true;
97 }
98 } else if (C.isAllOnes()) {
99 if (Pred == ICmpInst::ICMP_SGT) {
101 return true;
102 }
103 }
104
105 return false;
106}
107
108/// Try to fold
109/// cmp pred (load (gep GV, ...)), cmpcst
110/// where GV is a global variable with a constant initializer. Try to simplify
111/// this into some simple computation that does not need the load. For example
112/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
113///
114/// If AndCst is non-null, then the loaded value is masked with that constant
115/// before doing the comparison. This handles cases like "A[i]&4 == 0".
116///
117/// We allow multi-use cases in this fold, even though it can increase
118/// instruction count, because it appears to be mostly beneficial in practice.
119/// Even if there are multiple uses, they can often be sunk into the block
120/// guarded by the icmp.
122 LoadInst *LI, CmpPredicate Pred, Constant *RHSC, Instruction &CtxI,
123 ConstantInt *AndCst) {
124 std::optional<ConstGlobalLoad> GlobalLoad = ConstGlobalLoad::fromLoadInst(LI);
125 if (!GlobalLoad)
126 return nullptr;
127
128 // Don't blow up on huge arrays.
129 const uint64_t ArrayElementCount = GlobalLoad->getElementCount();
130 if (ArrayElementCount > CLOpts.maxarray_size)
131 return nullptr;
132
133 enum { Overdefined = -3, Undefined = -2 };
134
135 // Variables for our state machines.
136
137 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
138 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
139 // and 87 is the second (and last) index. FirstTrueElement is -2 when
140 // undefined, otherwise set to the first true element. SecondTrueElement is
141 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
142 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
143
144 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
145 // form "i != 47 & i != 87". Same state transitions as for true elements.
146 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
147
148 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
149 /// define a state machine that triggers for ranges of values that the index
150 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
151 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
152 /// index in the range (inclusive). We use -2 for undefined here because we
153 /// use relative comparisons and don't want 0-1 to match -1.
154 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
155
156 // MagicBitvector - This is a magic bitvector where we set a bit if the
157 // comparison is true for element 'i'. If there are 64 elements or less in
158 // the array, this will fully represent all the comparison results.
159 uint64_t MagicBitvector = 0;
160
161 // Scan the array and see if one of our patterns matches.
162 for (uint64_t i = 0; i < ArrayElementCount; i += 1) {
163 Constant *Elt = GlobalLoad->getElementAt(i);
164 if (!Elt)
165 return nullptr;
166
167 // If the element is masked, handle it.
168 if (AndCst) {
169 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
170 if (!Elt)
171 return nullptr;
172 }
173
174 // Find out if the comparison would be true or false for the i'th element.
175 Constant *C = ConstantFoldCompareInstOperands(Pred, Elt, RHSC, DL, &TLI);
176 if (!C)
177 return nullptr;
178
179 // If the result is undef for this element, ignore it.
180 if (isa<UndefValue>(C)) {
181 // Extend range state machines to cover this element in case there is an
182 // undef in the middle of the range.
183 if (TrueRangeEnd == (int)i - 1)
184 TrueRangeEnd = i;
185 if (FalseRangeEnd == (int)i - 1)
186 FalseRangeEnd = i;
187 continue;
188 }
189
190 // If we can't compute the result for any of the elements, we have to give
191 // up evaluating the entire conditional.
192 if (!isa<ConstantInt>(C))
193 return nullptr;
194
195 // Otherwise, we know if the comparison is true or false for this element,
196 // update our state machines.
197 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
198
199 // State machine for single/double/range index comparison.
200 if (IsTrueForElt) {
201 // Update the TrueElement state machine.
202 if (FirstTrueElement == Undefined)
203 FirstTrueElement = TrueRangeEnd = i; // First true element.
204 else {
205 // Update double-compare state machine.
206 if (SecondTrueElement == Undefined)
207 SecondTrueElement = i;
208 else
209 SecondTrueElement = Overdefined;
210
211 // Update range state machine.
212 if (TrueRangeEnd == (int)i - 1)
213 TrueRangeEnd = i;
214 else
215 TrueRangeEnd = Overdefined;
216 }
217 } else {
218 // Update the FalseElement state machine.
219 if (FirstFalseElement == Undefined)
220 FirstFalseElement = FalseRangeEnd = i; // First false element.
221 else {
222 // Update double-compare state machine.
223 if (SecondFalseElement == Undefined)
224 SecondFalseElement = i;
225 else
226 SecondFalseElement = Overdefined;
227
228 // Update range state machine.
229 if (FalseRangeEnd == (int)i - 1)
230 FalseRangeEnd = i;
231 else
232 FalseRangeEnd = Overdefined;
233 }
234 }
235
236 // If this element is in range, update our magic bitvector.
237 if (i < 64 && IsTrueForElt)
238 MagicBitvector |= 1ULL << i;
239
240 // If all of our states become overdefined and we need more than 64 bits in
241 // the bit vector, bail out.
242 if (i >= 64 && SecondTrueElement == Overdefined &&
243 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
244 FalseRangeEnd == Overdefined)
245 return nullptr;
246 }
247
248 // Now that we've scanned the entire array, emit our new comparison(s). We
249 // order the state machines in complexity of the generated code.
250
251 // If the comparison is only true for one or two elements, emit direct
252 // comparisons.
253 if (SecondTrueElement != Overdefined) {
254 Value *Idx = GlobalLoad->buildCanonicalIndex(Builder);
255 // None true -> false.
256 if (FirstTrueElement == Undefined)
257 return replaceInstUsesWith(CtxI, Builder.getFalse());
258
259 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
260
261 // True for one element -> 'i == 47'.
262 if (SecondTrueElement == Undefined)
263 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
264
265 // True for two elements -> 'i == 47 | i == 72'.
266 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
267 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
268 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
269 return BinaryOperator::CreateOr(C1, C2);
270 }
271
272 // If the comparison is only false for one or two elements, emit direct
273 // comparisons.
274 if (SecondFalseElement != Overdefined) {
275 Value *Idx = GlobalLoad->buildCanonicalIndex(Builder);
276 // None false -> true.
277 if (FirstFalseElement == Undefined)
278 return replaceInstUsesWith(CtxI, Builder.getTrue());
279
280 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
281
282 // False for one element -> 'i != 47'.
283 if (SecondFalseElement == Undefined)
284 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
285
286 // False for two elements -> 'i != 47 & i != 72'.
287 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
288 Value *SecondFalseIdx =
289 ConstantInt::get(Idx->getType(), SecondFalseElement);
290 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
291 return BinaryOperator::CreateAnd(C1, C2);
292 }
293
294 // If the comparison can be replaced with a range comparison for the elements
295 // where it is true, emit the range check.
296 if (TrueRangeEnd != Overdefined) {
297 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
298 Value *Idx = GlobalLoad->buildCanonicalIndex(Builder);
299
300 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
301 if (FirstTrueElement) {
302 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
303 Idx = Builder.CreateAdd(Idx, Offs);
304 }
305
306 Value *End =
307 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
308 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
309 }
310
311 // False range check.
312 if (FalseRangeEnd != Overdefined) {
313 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
314 Value *Idx = GlobalLoad->buildCanonicalIndex(Builder);
315 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
316 if (FirstFalseElement) {
317 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
318 Idx = Builder.CreateAdd(Idx, Offs);
319 }
320
321 Value *End =
322 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
323 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
324 }
325
326 // If a magic bitvector captures the entire comparison state
327 // of this load, replace it with computation that does:
328 // ((magic_cst >> i) & 1) != 0
329 {
330 // Look for an appropriate type:
331 // - The type of Idx if the magic fits
332 // - The smallest fitting legal type
333 Type *Ty = GlobalLoad->getIndex()->getType();
334 if (ArrayElementCount > Ty->getIntegerBitWidth())
335 Ty = DL.getSmallestLegalIntType(RHSC->getContext(), ArrayElementCount);
336
337 if (Ty) {
338 Value *Idx = GlobalLoad->buildCanonicalIndex(Builder);
339 Value *V = Builder.CreateIntCast(Idx, Ty, false);
340 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
341 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
342 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
343 }
344 }
345
346 return nullptr;
347}
348
349/// Returns true if we can rewrite Start as a GEP with pointer Base
350/// and some integer offset. The nodes that need to be re-written
351/// for this transformation will be added to Explored.
353 const DataLayout &DL,
354 SetVector<Value *> &Explored) {
355 SmallVector<Value *, 16> WorkList(1, Start);
356 Explored.insert(Base);
357
358 // The following traversal gives us an order which can be used
359 // when doing the final transformation. Since in the final
360 // transformation we create the PHI replacement instructions first,
361 // we don't have to get them in any particular order.
362 //
363 // However, for other instructions we will have to traverse the
364 // operands of an instruction first, which means that we have to
365 // do a post-order traversal.
366 while (!WorkList.empty()) {
368
369 while (!WorkList.empty()) {
370 if (Explored.size() >= 100)
371 return false;
372
373 Value *V = WorkList.back();
374
375 if (Explored.contains(V)) {
376 WorkList.pop_back();
377 continue;
378 }
379
381 // We've found some value that we can't explore which is different from
382 // the base. Therefore we can't do this transformation.
383 return false;
384
385 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
386 // Only allow inbounds GEPs with at most one variable offset.
387 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
388 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
389 return false;
390
391 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
392 if (!Explored.contains(GEP->getOperand(0)))
393 WorkList.push_back(GEP->getOperand(0));
394 }
395
396 if (WorkList.back() == V) {
397 WorkList.pop_back();
398 // We've finished visiting this node, mark it as such.
399 Explored.insert(V);
400 }
401
402 if (auto *PN = dyn_cast<PHINode>(V)) {
403 // We cannot transform PHIs on unsplittable basic blocks.
404 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
405 return false;
406 Explored.insert(PN);
407 PHIs.insert(PN);
408 }
409 }
410
411 // Explore the PHI nodes further.
412 for (auto *PN : PHIs)
413 for (Value *Op : PN->incoming_values())
414 if (!Explored.contains(Op))
415 WorkList.push_back(Op);
416 }
417
418 // Make sure that we can do this. Since we can't insert GEPs in a basic
419 // block before a PHI node, we can't easily do this transformation if
420 // we have PHI node users of transformed instructions.
421 for (Value *Val : Explored) {
422 for (Value *Use : Val->uses()) {
423
424 auto *PHI = dyn_cast<PHINode>(Use);
425 auto *Inst = dyn_cast<Instruction>(Val);
426
427 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
428 !Explored.contains(PHI))
429 continue;
430
431 if (PHI->getParent() == Inst->getParent())
432 return false;
433 }
434 }
435 return true;
436}
437
438// Sets the appropriate insert point on Builder where we can add
439// a replacement Instruction for V (if that is possible).
440static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
441 bool Before = true) {
442 if (auto *PHI = dyn_cast<PHINode>(V)) {
443 BasicBlock *Parent = PHI->getParent();
444 Builder.SetInsertPoint(Parent->getFirstInsertionPt());
445 return;
446 }
447 if (auto *I = dyn_cast<Instruction>(V)) {
448 if (!Before)
449 I = &*std::next(I->getIterator());
450 Builder.SetInsertPoint(I);
451 return;
452 }
453 if (auto *A = dyn_cast<Argument>(V)) {
454 // Set the insertion point in the entry block.
455 BasicBlock &Entry = A->getParent()->getEntryBlock();
456 Builder.SetInsertPoint(Entry.getFirstInsertionPt());
457 return;
458 }
459 // Otherwise, this is a constant and we don't need to set a new
460 // insertion point.
461 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
462}
463
464/// Returns a re-written value of Start as an indexed GEP using Base as a
465/// pointer.
467 const DataLayout &DL,
468 SetVector<Value *> &Explored,
469 InstCombiner &IC) {
470 // Perform all the substitutions. This is a bit tricky because we can
471 // have cycles in our use-def chains.
472 // 1. Create the PHI nodes without any incoming values.
473 // 2. Create all the other values.
474 // 3. Add the edges for the PHI nodes.
475 // 4. Emit GEPs to get the original pointers.
476 // 5. Remove the original instructions.
477 Type *IndexType = IntegerType::get(
478 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
479
481 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
482
483 // Create the new PHI nodes, without adding any incoming values.
484 for (Value *Val : Explored) {
485 if (Val == Base)
486 continue;
487 // Create empty phi nodes. This avoids cyclic dependencies when creating
488 // the remaining instructions.
489 if (auto *PHI = dyn_cast<PHINode>(Val))
490 NewInsts[PHI] =
491 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
492 PHI->getName() + ".idx", PHI->getIterator());
493 }
494 IRBuilder<> Builder(IC.getModule());
495
496 // Create all the other instructions.
497 for (Value *Val : Explored) {
498 if (NewInsts.contains(Val))
499 continue;
500
501 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
502 setInsertionPoint(Builder, GEP);
503 Value *Op = NewInsts[GEP->getOperand(0)];
504 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
506 NewInsts[GEP] = OffsetV;
507 else
508 NewInsts[GEP] = Builder.CreateAdd(
509 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
510 /*NUW=*/NW.hasNoUnsignedWrap(),
511 /*NSW=*/NW.hasNoUnsignedSignedWrap());
512 continue;
513 }
514 if (isa<PHINode>(Val))
515 continue;
516
517 llvm_unreachable("Unexpected instruction type");
518 }
519
520 // Add the incoming values to the PHI nodes.
521 for (Value *Val : Explored) {
522 if (Val == Base)
523 continue;
524 // All the instructions have been created, we can now add edges to the
525 // phi nodes.
526 if (auto *PHI = dyn_cast<PHINode>(Val)) {
527 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
528 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
529 Value *NewIncoming = PHI->getIncomingValue(I);
530
531 auto It = NewInsts.find(NewIncoming);
532 if (It != NewInsts.end())
533 NewIncoming = It->second;
534
535 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
536 }
537 }
538 }
539
540 for (Value *Val : Explored) {
541 if (Val == Base)
542 continue;
543
544 setInsertionPoint(Builder, Val, false);
545 // Create GEP for external users.
546 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
547 Val->getName() + ".ptr", NW);
548 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
549 // Add old instruction to worklist for DCE. We don't directly remove it
550 // here because the original compare is one of the users.
552 }
553
554 return NewInsts[Start];
555}
556
557/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
558/// We can look through PHIs, GEPs and casts in order to determine a common base
559/// between GEPLHS and RHS.
562 const DataLayout &DL,
563 InstCombiner &IC) {
564 // FIXME: Support vector of pointers.
565 if (GEPLHS->getType()->isVectorTy())
566 return nullptr;
567
568 if (!GEPLHS->hasAllConstantIndices())
569 return nullptr;
570
571 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
572 Value *PtrBase =
574 /*AllowNonInbounds*/ false);
575
576 // Bail if we looked through addrspacecast.
577 if (PtrBase->getType() != GEPLHS->getType())
578 return nullptr;
579
580 // The set of nodes that will take part in this transformation.
581 SetVector<Value *> Nodes;
582 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
583 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
584 return nullptr;
585
586 // We know we can re-write this as
587 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
588 // Since we've only looked through inbouds GEPs we know that we
589 // can't have overflow on either side. We can therefore re-write
590 // this as:
591 // OFFSET1 cmp OFFSET2
592 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
593
594 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
595 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
596 // offset. Since Index is the offset of LHS to the base pointer, we will now
597 // compare the offsets instead of comparing the pointers.
599 IC.Builder.getInt(Offset), NewRHS);
600}
601
602/// Fold comparisons between a GEP instruction and something else. At this point
603/// we know that the GEP is on the LHS of the comparison.
606 // Don't transform signed compares of GEPs into index compares. Even if the
607 // GEP is inbounds, the final add of the base pointer can have signed overflow
608 // and would change the result of the icmp.
609 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
610 // the maximum signed value for the pointer type.
612 return nullptr;
613
614 // Look through bitcasts and addrspacecasts. We do not however want to remove
615 // 0 GEPs.
616 if (!isa<GetElementPtrInst>(RHS))
617 RHS = RHS->stripPointerCasts();
618
619 auto CanFold = [Cond](GEPNoWrapFlags NW) {
621 return true;
622
623 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
625 return NW != GEPNoWrapFlags::none();
626 };
627
628 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
629 if (!NW.hasNoUnsignedWrap()) {
630 // Convert signed to unsigned comparison.
631 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
632 }
633
634 auto *I = new ICmpInst(Cond, Op1, Op2);
635 I->setSameSign(NW.hasNoUnsignedSignedWrap());
636 return I;
637 };
638
640 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
641 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
642 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
643 Value *Offset =
644 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
645 return NewICmp(Base.LHSNW, Offset,
646 Constant::getNullValue(Offset->getType()));
647 }
648
649 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
651 !NullPointerIsDefined(I.getFunction(),
652 RHS->getType()->getPointerAddressSpace())) {
653 // For most address spaces, an allocation can't be placed at null, but null
654 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
655 // the only valid inbounds address derived from null, is null itself.
656 // Thus, we have four cases to consider:
657 // 1) Base == nullptr, Offset == 0 -> inbounds, null
658 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
659 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
660 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
661 //
662 // (Note if we're indexing a type of size 0, that simply collapses into one
663 // of the buckets above.)
664 //
665 // In general, we're allowed to make values less poison (i.e. remove
666 // sources of full UB), so in this case, we just select between the two
667 // non-poison cases (1 and 4 above).
668 //
669 // For vectors, we apply the same reasoning on a per-lane basis.
670 auto *Base = GEPLHS->getPointerOperand();
671 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
672 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
673 Base = Builder.CreateVectorSplat(EC, Base);
674 }
675 return new ICmpInst(Cond, Base,
677 cast<Constant>(RHS), Base->getType()));
678 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
679 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
680
681 // If the base pointers are different, but the indices are the same, just
682 // compare the base pointer.
683 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
684 bool IndicesTheSame =
685 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
686 GEPLHS->getPointerOperand()->getType() ==
687 GEPRHS->getPointerOperand()->getType() &&
688 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
689 if (IndicesTheSame)
690 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
691 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
692 IndicesTheSame = false;
693 break;
694 }
695
696 // If all indices are the same, just compare the base pointers.
697 Type *BaseType = GEPLHS->getOperand(0)->getType();
698 if (IndicesTheSame &&
699 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
700 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
701
702 // If we're comparing GEPs with two base pointers that only differ in type
703 // and both GEPs have only constant indices or just one use, then fold
704 // the compare with the adjusted indices.
705 // FIXME: Support vector of pointers.
706 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
707 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
708 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
709 GEPLHS->getOperand(0)->stripPointerCasts() ==
710 GEPRHS->getOperand(0)->stripPointerCasts() &&
711 !GEPLHS->getType()->isVectorTy()) {
712 Value *LOffset = EmitGEPOffset(GEPLHS);
713 Value *ROffset = EmitGEPOffset(GEPRHS);
714
715 // If we looked through an addrspacecast between different sized address
716 // spaces, the LHS and RHS pointers are different sized
717 // integers. Truncate to the smaller one.
718 Type *LHSIndexTy = LOffset->getType();
719 Type *RHSIndexTy = ROffset->getType();
720 if (LHSIndexTy != RHSIndexTy) {
721 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
722 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
723 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
724 } else
725 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
726 }
727
729 LOffset, ROffset);
730 return replaceInstUsesWith(I, Cmp);
731 }
732 }
733
734 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
735 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
736 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
737 // If the GEPs only differ by one index, compare it.
738 unsigned NumDifferences = 0; // Keep track of # differences.
739 unsigned DiffOperand = 0; // The operand that differs.
740 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
741 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
742 Type *LHSType = GEPLHS->getOperand(i)->getType();
743 Type *RHSType = GEPRHS->getOperand(i)->getType();
744 // FIXME: Better support for vector of pointers.
745 if (LHSType->getPrimitiveSizeInBits() !=
746 RHSType->getPrimitiveSizeInBits() ||
747 (GEPLHS->getType()->isVectorTy() &&
748 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
749 // Irreconcilable differences.
750 NumDifferences = 2;
751 break;
752 }
753
754 if (NumDifferences++)
755 break;
756 DiffOperand = i;
757 }
758
759 if (NumDifferences == 0) // SAME GEP?
760 return replaceInstUsesWith(
761 I, // No comparison is needed here.
762 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
763 // If two GEPs only differ by an index, compare them.
764 // Note that nowrap flags are always needed when comparing two indices.
765 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
766 Value *LHSV = GEPLHS->getOperand(DiffOperand);
767 Value *RHSV = GEPRHS->getOperand(DiffOperand);
768 return NewICmp(NW, LHSV, RHSV);
769 }
770 }
771
772 if (Base.Ptr && !Base.isExpensive()) {
773 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
774 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
775
776 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
777 // Without the flags, we can still fold if the offsets are constant and
778 // they cross the base's alignment boundary the same number of times, so
779 // either both arguments will wrap, or none of them will.
780 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
781 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
782 APInt LOff(BW, 0);
783 APInt ROff(BW, 0);
785 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
786 RHS->stripAndAccumulateConstantOffsets(
787 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
788 DoFold =
791 }
792
793 if (DoFold) {
794 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
795 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
796 /*RewriteGEP=*/true);
797 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
798 /*RewriteGEP=*/true);
799 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
800 }
801 }
802 }
803
804 // Try convert this to an indexed compare by looking through PHIs/casts as a
805 // last resort.
806 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
807}
808
810 // It would be tempting to fold away comparisons between allocas and any
811 // pointer not based on that alloca (e.g. an argument). However, even
812 // though such pointers cannot alias, they can still compare equal.
813 //
814 // But LLVM doesn't specify where allocas get their memory, so if the alloca
815 // doesn't escape we can argue that it's impossible to guess its value, and we
816 // can therefore act as if any such guesses are wrong.
817 //
818 // However, we need to ensure that this folding is consistent: We can't fold
819 // one comparison to false, and then leave a different comparison against the
820 // same value alone (as it might evaluate to true at runtime, leading to a
821 // contradiction). As such, this code ensures that all comparisons are folded
822 // at the same time, and there are no other escapes.
823
824 struct CmpCaptureTracker : public CaptureTracker {
825 AllocaInst *Alloca;
826 bool Captured = false;
827 /// The value of the map is a bit mask of which icmp operands the alloca is
828 /// used in.
830
831 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
832
833 void tooManyUses() override { Captured = true; }
834
835 Action captured(const Use *U, UseCaptureInfo CI) override {
836 // TODO(captures): Use UseCaptureInfo.
837 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
838 // We need to check that U is based *only* on the alloca, and doesn't
839 // have other contributions from a select/phi operand.
840 // TODO: We could check whether getUnderlyingObjects() reduces to one
841 // object, which would allow looking through phi nodes.
842 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
843 // Collect equality icmps of the alloca, and don't treat them as
844 // captures.
845 ICmps[ICmp] |= 1u << U->getOperandNo();
846 return Continue;
847 }
848
849 Captured = true;
850 return Stop;
851 }
852 };
853
854 CmpCaptureTracker Tracker(Alloca);
855 PointerMayBeCaptured(Alloca, &Tracker);
856 if (Tracker.Captured)
857 return false;
858
859 bool Changed = false;
860 for (auto [ICmp, Operands] : Tracker.ICmps) {
861 switch (Operands) {
862 case 1:
863 case 2: {
864 // The alloca is only used in one icmp operand. Assume that the
865 // equality is false.
866 auto *Res = ConstantInt::get(ICmp->getType(),
867 ICmp->getPredicate() == ICmpInst::ICMP_NE);
868 replaceInstUsesWith(*ICmp, Res);
870 Changed = true;
871 break;
872 }
873 case 3:
874 // Both icmp operands are based on the alloca, so this is comparing
875 // pointer offsets, without leaking any information about the address
876 // of the alloca. Ignore such comparisons.
877 break;
878 default:
879 llvm_unreachable("Cannot happen");
880 }
881 }
882
883 return Changed;
884}
885
886/// Fold "icmp pred (X+C), X".
888 CmpPredicate Pred) {
889 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
890 // so the values can never be equal. Similarly for all other "or equals"
891 // operators.
892 assert(!!C && "C should not be zero!");
893
894 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
895 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
896 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
897 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
898 Constant *R =
899 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
900 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
901 }
902
903 // (X+1) >u X --> X <u (0-1) --> X != 255
904 // (X+2) >u X --> X <u (0-2) --> X <u 254
905 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
906 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
907 return new ICmpInst(ICmpInst::ICMP_ULT, X,
908 ConstantInt::get(X->getType(), -C));
909
910 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
911
912 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
913 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
914 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
915 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
916 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
917 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
918 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
919 return new ICmpInst(ICmpInst::ICMP_SGT, X,
920 ConstantInt::get(X->getType(), SMax - C));
921
922 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
923 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
924 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
925 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
926 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
927 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
928
929 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
930 return new ICmpInst(ICmpInst::ICMP_SLT, X,
931 ConstantInt::get(X->getType(), SMax - (C - 1)));
932}
933
934/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
935/// (icmp eq/ne A, Log2(AP2/AP1)) ->
936/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
938 const APInt &AP1,
939 const APInt &AP2) {
940 assert(I.isEquality() && "Cannot fold icmp gt/lt");
941
942 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
943 if (I.getPredicate() == I.ICMP_NE)
944 Pred = CmpInst::getInversePredicate(Pred);
945 return new ICmpInst(Pred, LHS, RHS);
946 };
947
948 // Don't bother doing any work for cases which InstSimplify handles.
949 if (AP2.isZero())
950 return nullptr;
951
952 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
953 if (IsAShr) {
954 if (AP2.isAllOnes())
955 return nullptr;
956 if (AP2.isNegative() != AP1.isNegative())
957 return nullptr;
958 if (AP2.sgt(AP1))
959 return nullptr;
960 }
961
962 if (!AP1)
963 // 'A' must be large enough to shift out the highest set bit.
964 return getICmp(I.ICMP_UGT, A,
965 ConstantInt::get(A->getType(), AP2.logBase2()));
966
967 if (AP1 == AP2)
968 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
969
970 int Shift;
971 if (IsAShr && AP1.isNegative())
972 Shift = AP1.countl_one() - AP2.countl_one();
973 else
974 Shift = AP1.countl_zero() - AP2.countl_zero();
975
976 if (Shift > 0) {
977 if (IsAShr && AP1 == AP2.ashr(Shift)) {
978 // There are multiple solutions if we are comparing against -1 and the LHS
979 // of the ashr is not a power of two.
980 if (AP1.isAllOnes() && !AP2.isPowerOf2())
981 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
982 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
983 } else if (AP1 == AP2.lshr(Shift)) {
984 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
985 }
986 }
987
988 // Shifting const2 will never be equal to const1.
989 // FIXME: This should always be handled by InstSimplify?
990 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
991 return replaceInstUsesWith(I, TorF);
992}
993
994/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
995/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
997 const APInt &AP1,
998 const APInt &AP2) {
999 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1000
1001 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1002 if (I.getPredicate() == I.ICMP_NE)
1003 Pred = CmpInst::getInversePredicate(Pred);
1004 return new ICmpInst(Pred, LHS, RHS);
1005 };
1006
1007 // Don't bother doing any work for cases which InstSimplify handles.
1008 if (AP2.isZero())
1009 return nullptr;
1010
1011 unsigned AP2TrailingZeros = AP2.countr_zero();
1012
1013 if (!AP1 && AP2TrailingZeros != 0)
1014 return getICmp(
1015 I.ICMP_UGE, A,
1016 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1017
1018 if (AP1 == AP2)
1019 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1020
1021 // Get the distance between the lowest bits that are set.
1022 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1023
1024 if (Shift > 0 && AP2.shl(Shift) == AP1)
1025 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1026
1027 // Shifting const2 will never be equal to const1.
1028 // FIXME: This should always be handled by InstSimplify?
1029 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1030 return replaceInstUsesWith(I, TorF);
1031}
1032
1033/// The caller has matched a pattern of the form:
1034/// I = icmp ugt (add (add A, B), CI2), CI1
1035/// If this is of the form:
1036/// sum = a + b
1037/// if (sum+128 >u 255)
1038/// Then replace it with llvm.sadd.with.overflow.i8.
1039///
1041 ConstantInt *CI2, ConstantInt *CI1,
1042 InstCombinerImpl &IC) {
1043 // The transformation we're trying to do here is to transform this into an
1044 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1045 // with a narrower add, and discard the add-with-constant that is part of the
1046 // range check (if we can't eliminate it, this isn't profitable).
1047
1048 // In order to eliminate the add-with-constant, the compare can be its only
1049 // use.
1050 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1051 if (!AddWithCst->hasOneUse())
1052 return nullptr;
1053
1054 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1055 if (!CI2->getValue().isPowerOf2())
1056 return nullptr;
1057 unsigned NewWidth = CI2->getValue().countr_zero();
1058 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1059 return nullptr;
1060
1061 // The width of the new add formed is 1 more than the bias.
1062 ++NewWidth;
1063
1064 // Check to see that CI1 is an all-ones value with NewWidth bits.
1065 if (CI1->getBitWidth() == NewWidth ||
1066 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1067 return nullptr;
1068
1069 // This is only really a signed overflow check if the inputs have been
1070 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1071 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1072 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1073 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1074 return nullptr;
1075
1076 // In order to replace the original add with a narrower
1077 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1078 // and truncates that discard the high bits of the add. Verify that this is
1079 // the case.
1080 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1081 for (User *U : OrigAdd->users()) {
1082 if (U == AddWithCst)
1083 continue;
1084
1085 // Only accept truncates for now. We would really like a nice recursive
1086 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1087 // chain to see which bits of a value are actually demanded. If the
1088 // original add had another add which was then immediately truncated, we
1089 // could still do the transformation.
1091 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1092 return nullptr;
1093 }
1094
1095 // If the pattern matches, truncate the inputs to the narrower type and
1096 // use the sadd_with_overflow intrinsic to efficiently compute both the
1097 // result and the overflow bit.
1098 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1100 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1101
1102 InstCombiner::BuilderTy &Builder = IC.Builder;
1103
1104 // Put the new code above the original add, in case there are any uses of the
1105 // add between the add and the compare.
1106 Builder.SetInsertPoint(OrigAdd);
1107
1108 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1109 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1110 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1111 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1112 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1113
1114 // The inner add was the result of the narrow add, zero extended to the
1115 // wider type. Replace it with the result computed by the intrinsic.
1116 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1117 IC.eraseInstFromFunction(*OrigAdd);
1118
1119 // The original icmp gets replaced with the overflow value.
1120 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1121}
1122
1123/// If we have:
1124/// icmp eq/ne (urem/srem %x, %y), 0
1125/// iff %y is a power-of-two, we can replace this with a bit test:
1126/// icmp eq/ne (and %x, (add %y, -1)), 0
1128 // This fold is only valid for equality predicates.
1129 if (!I.isEquality())
1130 return nullptr;
1131 CmpPredicate Pred;
1132 Value *X, *Y, *Zero;
1133 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1135 return nullptr;
1136 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1137 return nullptr;
1138 // This may increase instruction count, we don't enforce that Y is a constant.
1139 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1140 Value *Masked = Builder.CreateAnd(X, Mask);
1141 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1142}
1143
1144/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1145/// by one-less-than-bitwidth into a sign test on the original value.
1147 Instruction *Val;
1148 CmpPredicate Pred;
1149 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1150 return nullptr;
1151
1152 Value *X;
1153 Type *XTy;
1154
1155 Constant *C;
1156 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1157 XTy = X->getType();
1158 unsigned XBitWidth = XTy->getScalarSizeInBits();
1160 APInt(XBitWidth, XBitWidth - 1))))
1161 return nullptr;
1162 } else if (isa<BinaryOperator>(Val) &&
1164 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1165 /*AnalyzeForSignBitExtraction=*/true))) {
1166 XTy = X->getType();
1167 } else
1168 return nullptr;
1169
1170 return ICmpInst::Create(Instruction::ICmp,
1174}
1175
1176// Handle icmp pred X, 0
1178 CmpInst::Predicate Pred = Cmp.getPredicate();
1179 if (!match(Cmp.getOperand(1), m_Zero()))
1180 return nullptr;
1181
1182 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1183 if (Pred == ICmpInst::ICMP_SGT) {
1184 Value *A, *B;
1185 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1186 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1187 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1188 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1189 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1190 }
1191 }
1192
1194 return New;
1195
1196 // Given:
1197 // icmp eq/ne (urem %x, %y), 0
1198 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1199 // icmp eq/ne %x, 0
1200 Value *X, *Y;
1201 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1202 ICmpInst::isEquality(Pred)) {
1203 KnownBits XKnown = computeKnownBits(X, &Cmp);
1204 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1205 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1206 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1207 }
1208
1209 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1210 // odd/non-zero/there is no overflow.
1211 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1212 ICmpInst::isEquality(Pred)) {
1213
1214 KnownBits XKnown = computeKnownBits(X, &Cmp);
1215 // if X % 2 != 0
1216 // (icmp eq/ne Y)
1217 if (XKnown.countMaxTrailingZeros() == 0)
1218 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1219
1220 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1221 // if Y % 2 != 0
1222 // (icmp eq/ne X)
1223 if (YKnown.countMaxTrailingZeros() == 0)
1224 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1225
1226 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1227 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1228 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1229 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1230 // but to avoid unnecessary work, first just if this is an obvious case.
1231
1232 // if X non-zero and NoOverflow(X * Y)
1233 // (icmp eq/ne Y)
1234 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1235 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1236
1237 // if Y non-zero and NoOverflow(X * Y)
1238 // (icmp eq/ne X)
1239 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1240 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1241 }
1242 // Note, we are skipping cases:
1243 // if Y % 2 != 0 AND X % 2 != 0
1244 // (false/true)
1245 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1246 // (false/true)
1247 // Those can be simplified later as we would have already replaced the (icmp
1248 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1249 // will fold to a constant elsewhere.
1250 }
1251
1252 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1253 // where f(X) == 0 if and only if X == 0
1254 if (ICmpInst::isEquality(Pred))
1255 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1256 return new ICmpInst(Pred, Stripped,
1257 Constant::getNullValue(Stripped->getType()));
1258
1259 return nullptr;
1260}
1261
1262/// Fold icmp eq (num + mask) & ~mask, num
1263/// to
1264/// icmp eq (and num, mask), 0
1265/// Where mask is a low bit mask.
1267 Value *Num;
1268 CmpPredicate Pred;
1269 const APInt *Mask, *Neg;
1270
1271 if (!match(&Cmp,
1272 m_c_ICmp(Pred, m_Value(Num),
1274 m_LowBitMask(Mask))),
1275 m_APInt(Neg))))))
1276 return nullptr;
1277
1278 if (*Neg != ~*Mask)
1279 return nullptr;
1280
1281 if (!ICmpInst::isEquality(Pred))
1282 return nullptr;
1283
1284 // Create new icmp eq (num & mask), 0
1285 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1286 auto *Zero = Constant::getNullValue(Num->getType());
1287
1288 return new ICmpInst(Pred, NewAnd, Zero);
1289}
1290
1291/// Fold icmp Pred X, C.
1292/// TODO: This code structure does not make sense. The saturating add fold
1293/// should be moved to some other helper and extended as noted below (it is also
1294/// possible that code has been made unnecessary - do we canonicalize IR to
1295/// overflow/saturating intrinsics or not?).
1297 // Match the following pattern, which is a common idiom when writing
1298 // overflow-safe integer arithmetic functions. The source performs an addition
1299 // in wider type and explicitly checks for overflow using comparisons against
1300 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1301 //
1302 // TODO: This could probably be generalized to handle other overflow-safe
1303 // operations if we worked out the formulas to compute the appropriate magic
1304 // constants.
1305 //
1306 // sum = a + b
1307 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1308 CmpInst::Predicate Pred = Cmp.getPredicate();
1309 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1310 Value *A, *B;
1311 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1312 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1313 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1314 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1315 return Res;
1316
1317 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1319 if (!C)
1320 return nullptr;
1321
1322 if (auto *Phi = dyn_cast<PHINode>(Op0))
1323 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1325 for (Value *V : Phi->incoming_values()) {
1326 Constant *Res =
1328 if (!Res)
1329 return nullptr;
1330 Ops.push_back(Res);
1331 }
1332 Builder.SetInsertPoint(Phi);
1333 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1334 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1335 NewPhi->addIncoming(V, Pred);
1336 return replaceInstUsesWith(Cmp, NewPhi);
1337 }
1338
1340 return R;
1341
1342 return nullptr;
1343}
1344
1345/// Canonicalize icmp instructions based on dominating conditions.
1347 // We already checked simple implication in InstSimplify, only handle complex
1348 // cases here.
1349 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1350 const APInt *C;
1351 if (!match(Y, m_APInt(C)))
1352 return nullptr;
1353
1354 CmpInst::Predicate Pred = Cmp.getPredicate();
1356
1357 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1358 const APInt *DomC) -> Instruction * {
1359 // We have 2 compares of a variable with constants. Calculate the constant
1360 // ranges of those compares to see if we can transform the 2nd compare:
1361 // DomBB:
1362 // DomCond = icmp DomPred X, DomC
1363 // br DomCond, CmpBB, FalseBB
1364 // CmpBB:
1365 // Cmp = icmp Pred X, C
1366 ConstantRange DominatingCR =
1367 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1368 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1369 ConstantRange Difference = DominatingCR.difference(CR);
1370 if (Intersection.isEmptySet())
1371 return replaceInstUsesWith(Cmp, Builder.getFalse());
1372 if (Difference.isEmptySet())
1373 return replaceInstUsesWith(Cmp, Builder.getTrue());
1374
1375 // Canonicalizing a sign bit comparison that gets used in a branch,
1376 // pessimizes codegen by generating branch on zero instruction instead
1377 // of a test and branch. So we avoid canonicalizing in such situations
1378 // because test and branch instruction has better branch displacement
1379 // than compare and branch instruction.
1380 bool UnusedBit;
1381 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1382 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1383 return nullptr;
1384
1385 // Avoid an infinite loop with min/max canonicalization.
1386 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1387 if (Cmp.hasOneUse() &&
1388 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1389 return nullptr;
1390
1391 if (const APInt *EqC = Intersection.getSingleElement())
1392 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1393 if (const APInt *NeC = Difference.getSingleElement())
1394 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1395 return nullptr;
1396 };
1397
1398 for (CondBrInst *BI : DC.conditionsFor(X)) {
1399 CmpPredicate DomPred;
1400 const APInt *DomC;
1401 if (!match(BI->getCondition(),
1402 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1403 continue;
1404
1405 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1406 if (DT.dominates(Edge0, Cmp.getParent())) {
1407 if (auto *V = handleDomCond(DomPred, DomC))
1408 return V;
1409 } else {
1410 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1411 if (DT.dominates(Edge1, Cmp.getParent()))
1412 if (auto *V =
1413 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1414 return V;
1415 }
1416 }
1417
1418 return nullptr;
1419}
1420
1421/// Fold icmp (trunc X), C.
1424 const APInt &C) {
1425 ICmpInst::Predicate Pred = Cmp.getPredicate();
1426 Value *X = Trunc->getOperand(0);
1427 Type *SrcTy = X->getType();
1428 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1429 SrcBits = SrcTy->getScalarSizeInBits();
1430
1431 // Match (icmp pred (trunc nuw/nsw X), C)
1432 // Which we can convert to (icmp pred X, (sext/zext C))
1433 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1434 if (Trunc->hasNoSignedWrap())
1435 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1436 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1437 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1438 }
1439
1440 if (C.isOne() && C.getBitWidth() > 1) {
1441 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1442 Value *V = nullptr;
1443 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1444 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1445 ConstantInt::get(V->getType(), 1));
1446 }
1447
1448 // TODO: Handle non-equality predicates.
1449 Value *Y;
1450 const APInt *Pow2;
1451 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1452 DstBits > Pow2->logBase2()) {
1453 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1454 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1455 // iff N > log2(Pow2)
1456 if (C.isZero()) {
1457 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1458 return new ICmpInst(NewPred, Y,
1459 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1460 }
1461 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1462 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1463 if (C.isPowerOf2())
1464 return new ICmpInst(
1465 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1466 }
1467
1468 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1469 // Canonicalize to a mask and wider compare if the wide type is suitable:
1470 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1471 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1472 Constant *Mask =
1473 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1474 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1475 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1476 return new ICmpInst(Pred, And, WideC);
1477 }
1478
1479 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1480 // of the high bits truncated out of x are known.
1482
1483 // If all the high bits are known, we can do this xform.
1484 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1485 // Pull in the high bits from known-ones set.
1486 APInt NewRHS = C.zext(SrcBits);
1487 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1488 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1489 }
1490 }
1491
1492 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1493 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1494 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1495 Value *ShOp;
1496 uint64_t ShAmt;
1497 bool TrueIfSigned;
1498 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1499 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1500 DstBits == SrcBits - ShAmt) {
1501 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1503 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1505 }
1506
1507 return nullptr;
1508}
1509
1510/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1511/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1514 const SimplifyQuery &Q) {
1515 Value *X, *Y;
1516 CmpPredicate Pred;
1517 bool YIsSExt = false;
1518 // Try to match icmp (trunc X), (trunc Y)
1519 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1520 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1521 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1522 if (Cmp.isSigned()) {
1523 // For signed comparisons, both truncs must be nsw.
1524 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1525 return nullptr;
1526 } else {
1527 // For unsigned and equality comparisons, either both must be nuw or
1528 // both must be nsw, we don't care which.
1529 if (!NoWrapFlags)
1530 return nullptr;
1531 }
1532
1533 if (X->getType() != Y->getType() &&
1534 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1535 return nullptr;
1536 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1537 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1538 std::swap(X, Y);
1539 Pred = Cmp.getSwappedPredicate(Pred);
1540 }
1541 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1542 }
1543 // Try to match icmp (trunc nuw X), (zext Y)
1544 else if (!Cmp.isSigned() &&
1545 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1546 m_OneUse(m_ZExt(m_Value(Y)))))) {
1547 // Can fold trunc nuw + zext for unsigned and equality predicates.
1548 }
1549 // Try to match icmp (trunc nsw X), (sext Y)
1550 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1552 // Can fold trunc nsw + zext/sext for all predicates.
1553 YIsSExt =
1554 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1555 } else
1556 return nullptr;
1557
1558 Type *TruncTy = Cmp.getOperand(0)->getType();
1559 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1560
1561 // If this transform will end up changing from desirable types -> undesirable
1562 // types skip it.
1563 if (isDesirableIntType(TruncBits) &&
1564 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1565 return nullptr;
1566
1567 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1568 return new ICmpInst(Pred, X, NewY);
1569}
1570
1571/// Fold icmp (xor X, Y), C.
1574 const APInt &C) {
1575 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1576 return I;
1577
1578 Value *X = Xor->getOperand(0);
1579 Value *Y = Xor->getOperand(1);
1580 const APInt *XorC;
1581 if (!match(Y, m_APInt(XorC)))
1582 return nullptr;
1583
1584 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1585 // fold the xor.
1586 ICmpInst::Predicate Pred = Cmp.getPredicate();
1587 bool TrueIfSigned = false;
1588 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1589
1590 // If the sign bit of the XorCst is not set, there is no change to
1591 // the operation, just stop using the Xor.
1592 if (!XorC->isNegative())
1593 return replaceOperand(Cmp, 0, X);
1594
1595 // Emit the opposite comparison.
1596 if (TrueIfSigned)
1597 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1598 ConstantInt::getAllOnesValue(X->getType()));
1599 else
1600 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1601 ConstantInt::getNullValue(X->getType()));
1602 }
1603
1604 if (Xor->hasOneUse()) {
1605 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1606 if (!Cmp.isEquality() && XorC->isSignMask()) {
1607 Pred = Cmp.getFlippedSignednessPredicate();
1608 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1609 }
1610
1611 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1612 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1613 Pred = Cmp.getFlippedSignednessPredicate();
1614 Pred = Cmp.getSwappedPredicate(Pred);
1615 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1616 }
1617 }
1618
1619 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1620 if (Pred == ICmpInst::ICMP_UGT) {
1621 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1622 if (*XorC == ~C && (C + 1).isPowerOf2())
1623 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1624 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1625 if (*XorC == C && (C + 1).isPowerOf2())
1626 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1627 }
1628 if (Pred == ICmpInst::ICMP_ULT) {
1629 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1630 if (*XorC == -C && C.isPowerOf2())
1631 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1632 ConstantInt::get(X->getType(), ~C));
1633 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1634 if (*XorC == C && (-C).isPowerOf2())
1635 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1636 ConstantInt::get(X->getType(), ~C));
1637 }
1638 return nullptr;
1639}
1640
1641/// For power-of-2 C:
1642/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1643/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1646 const APInt &C) {
1647 CmpInst::Predicate Pred = Cmp.getPredicate();
1648 APInt PowerOf2;
1649 if (Pred == ICmpInst::ICMP_ULT)
1650 PowerOf2 = C;
1651 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1652 PowerOf2 = C + 1;
1653 else
1654 return nullptr;
1655 if (!PowerOf2.isPowerOf2())
1656 return nullptr;
1657 Value *X;
1658 const APInt *ShiftC;
1660 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1661 return nullptr;
1662 uint64_t Shift = ShiftC->getLimitedValue();
1663 Type *XType = X->getType();
1664 if (Shift == 0 || PowerOf2.isMinSignedValue())
1665 return nullptr;
1666 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1667 APInt Bound =
1668 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1669 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1670}
1671
1672/// Fold icmp (and (sh X, Y), C2), C1.
1675 const APInt &C1,
1676 const APInt &C2) {
1677 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1678 if (!Shift || !Shift->isShift())
1679 return nullptr;
1680
1681 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1682 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1683 // code produced by the clang front-end, for bitfield access.
1684 // This seemingly simple opportunity to fold away a shift turns out to be
1685 // rather complicated. See PR17827 for details.
1686 unsigned ShiftOpcode = Shift->getOpcode();
1687 bool IsShl = ShiftOpcode == Instruction::Shl;
1688 const APInt *C3;
1689 if (match(Shift->getOperand(1), m_APInt(C3))) {
1690 APInt NewAndCst, NewCmpCst;
1691 bool AnyCmpCstBitsShiftedOut;
1692 if (ShiftOpcode == Instruction::Shl) {
1693 // For a left shift, we can fold if the comparison is not signed. We can
1694 // also fold a signed comparison if the mask value and comparison value
1695 // are not negative. These constraints may not be obvious, but we can
1696 // prove that they are correct using an SMT solver.
1697 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1698 return nullptr;
1699
1700 NewCmpCst = C1.lshr(*C3);
1701 NewAndCst = C2.lshr(*C3);
1702 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1703 } else if (ShiftOpcode == Instruction::LShr) {
1704 // For a logical right shift, we can fold if the comparison is not signed.
1705 // We can also fold a signed comparison if the shifted mask value and the
1706 // shifted comparison value are not negative. These constraints may not be
1707 // obvious, but we can prove that they are correct using an SMT solver.
1708 NewCmpCst = C1.shl(*C3);
1709 NewAndCst = C2.shl(*C3);
1710 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1711 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1712 return nullptr;
1713 } else {
1714 // For an arithmetic shift, check that both constants don't use (in a
1715 // signed sense) the top bits being shifted out.
1716 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1717 NewCmpCst = C1.shl(*C3);
1718 NewAndCst = C2.shl(*C3);
1719 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1720 if (NewAndCst.ashr(*C3) != C2)
1721 return nullptr;
1722 }
1723
1724 if (AnyCmpCstBitsShiftedOut) {
1725 // If we shifted bits out, the fold is not going to work out. As a
1726 // special case, check to see if this means that the result is always
1727 // true or false now.
1728 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1729 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1730 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1731 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1732 } else {
1733 Value *NewAnd = Builder.CreateAnd(
1734 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1735 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1736 ConstantInt::get(And->getType(), NewCmpCst));
1737 }
1738 }
1739
1740 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1741 // preferable because it allows the C2 << Y expression to be hoisted out of a
1742 // loop if Y is invariant and X is not.
1743 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1744 !Shift->isArithmeticShift() &&
1745 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1746 // Compute C2 << Y.
1747 Value *NewShift =
1748 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1749 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1750
1751 // Compute X & (C2 << Y).
1752 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1753 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1754 }
1755
1756 return nullptr;
1757}
1758
1759/// Fold icmp (and X, C2), C1.
1762 const APInt &C1) {
1763 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1764
1765 // icmp ne (and X, 1), 0 --> trunc X to i1
1766 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1767 return new TruncInst(And->getOperand(0), Cmp.getType());
1768
1769 const APInt *C2;
1770 Value *X;
1771 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1772 return nullptr;
1773
1774 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1775 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1776 C2->isNegatedPowerOf2())
1777 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1778 ConstantInt::get(X->getType(), ~*C2));
1779 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1780 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1781 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1782 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1783 ConstantInt::get(X->getType(), -*C2));
1784
1785 // Don't perform the following transforms if the AND has multiple uses
1786 if (!And->hasOneUse())
1787 return nullptr;
1788
1789 if (Cmp.isEquality() && C1.isZero()) {
1790 // Restrict this fold to single-use 'and' (PR10267).
1791 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1792 if (C2->isSignMask()) {
1793 Constant *Zero = Constant::getNullValue(X->getType());
1794 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1795 return new ICmpInst(NewPred, X, Zero);
1796 }
1797
1798 APInt NewC2 = *C2;
1799 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1800 // Set high zeros of C2 to allow matching negated power-of-2.
1801 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1802 Know.countMinLeadingZeros());
1803
1804 // Restrict this fold only for single-use 'and' (PR10267).
1805 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1806 if (NewC2.isNegatedPowerOf2()) {
1807 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1808 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1809 return new ICmpInst(NewPred, X, NegBOC);
1810 }
1811 }
1812
1813 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1814 // the input width without changing the value produced, eliminate the cast:
1815 //
1816 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1817 //
1818 // We can do this transformation if the constants do not have their sign bits
1819 // set or if it is an equality comparison. Extending a relational comparison
1820 // when we're checking the sign bit would not work.
1821 Value *W;
1822 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1823 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1824 // TODO: Is this a good transform for vectors? Wider types may reduce
1825 // throughput. Should this transform be limited (even for scalars) by using
1826 // shouldChangeType()?
1827 if (!Cmp.getType()->isVectorTy()) {
1828 Type *WideType = W->getType();
1829 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1830 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1831 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1832 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1833 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1834 }
1835 }
1836
1837 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1838 return I;
1839
1840 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1841 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1842 //
1843 // iff pred isn't signed
1844 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1845 match(And->getOperand(1), m_One())) {
1846 Constant *One = cast<Constant>(And->getOperand(1));
1847 Value *Or = And->getOperand(0);
1848 Value *A, *B, *LShr;
1849 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1850 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1851 unsigned UsesRemoved = 0;
1852 if (And->hasOneUse())
1853 ++UsesRemoved;
1854 if (Or->hasOneUse())
1855 ++UsesRemoved;
1856 if (LShr->hasOneUse())
1857 ++UsesRemoved;
1858
1859 // Compute A & ((1 << B) | 1)
1860 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1861 if (UsesRemoved >= RequireUsesRemoved) {
1862 Value *NewOr =
1863 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1864 /*HasNUW=*/true),
1865 One, Or->getName());
1866 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1867 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1868 }
1869 }
1870 }
1871
1872 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1873 // llvm.is.fpclass(X, fcInf|fcNan)
1874 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1875 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1876 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1877 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1878 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1879 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1880 Value *V;
1881 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1882 Attribute::NoImplicitFloat) &&
1883 Cmp.isEquality() &&
1885 Type *FPType = V->getType()->getScalarType();
1886 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1887 APInt ExponentMask =
1888 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1889 if (*C2 == ExponentMask) {
1890 unsigned Mask = C1.isZero()
1893 if (isICMP_NE)
1894 Mask = ~Mask & fcAllFlags;
1895 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1896 }
1897 }
1898 }
1899
1900 return nullptr;
1901}
1902
1903/// Fold icmp (and X, Y), C.
1906 const APInt &C) {
1907 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1908 return I;
1909
1910 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1911 bool TrueIfNeg;
1912 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1913 // ((X - 1) & ~X) < 0 --> X == 0
1914 // ((X - 1) & ~X) >= 0 --> X != 0
1915 Value *X;
1916 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1917 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1918 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1919 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1920 }
1921 // (X & -X) < 0 --> X == MinSignedC
1922 // (X & -X) > -1 --> X != MinSignedC
1923 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1924 Constant *MinSignedC = ConstantInt::get(
1925 X->getType(),
1926 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1927 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1928 return new ICmpInst(NewPred, X, MinSignedC);
1929 }
1930 }
1931
1932 // TODO: These all require that Y is constant too, so refactor with the above.
1933
1934 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1935 Value *X = And->getOperand(0);
1936 Value *Y = And->getOperand(1);
1937 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1938 if (auto *LI = dyn_cast<LoadInst>(X))
1940 LI, Cmp.getPredicate(), cast<Constant>(Cmp.getOperand(1)), Cmp,
1941 C2))
1942 return Res;
1943
1944 if (!Cmp.isEquality())
1945 return nullptr;
1946
1947 // (X & -X) == 0 --> X == 0
1948 // (X & -X) != 0 --> X != 0
1949 // (X & -X) == 1 --> trunc X to i1
1950 // (X & -X) != 1 --> !(trunc X to i1)
1951 // Cmp is == or != by the check above.
1952 Value *MatchedX;
1953 // Match X & -X in either operand order.
1954 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
1955 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
1956 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
1957 if (C.isZero())
1958 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
1959
1960 // (X & -X) == 1 iff the low bit of X is set.
1961 if (Pred == CmpInst::ICMP_EQ)
1962 return new TruncInst(MatchedX, Cmp.getType());
1963
1964 // The remaining case needs a trunc and not. Require the original and
1965 // to become dead to avoid increasing the instruction count.
1966 if (And->hasOneUse()) {
1967 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
1969 }
1970 }
1971
1972 // X & -C == -C -> X > u ~C
1973 // X & -C != -C -> X <= u ~C
1974 // iff C is a power of 2
1975 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
1976 auto NewPred =
1978 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
1979 }
1980
1981 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
1982 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
1983 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
1984 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
1986 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
1987 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
1988 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
1989 Value *And = Builder.CreateAnd(TruncY, X);
1991 }
1992 return BinaryOperator::CreateAnd(TruncY, X);
1993 }
1994
1995 // (icmp eq/ne (and (shl -1, X), Y), 0)
1996 // -> (icmp eq/ne (lshr Y, X), 0)
1997 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
1998 // highly unlikely the non-zero case will ever show up in code.
1999 if (C.isZero() &&
2001 m_Value(Y))))) {
2002 Value *LShr = Builder.CreateLShr(Y, X);
2003 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2004 }
2005
2006 // (icmp eq/ne (and (add A, Addend), Msk), C)
2007 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2008 {
2009 Value *A;
2010 const APInt *Addend, *Msk;
2012 m_LowBitMask(Msk)))) &&
2013 C.ule(*Msk)) {
2014 APInt NewComperand = (C - *Addend) & *Msk;
2015 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2016 return new ICmpInst(Pred, MaskA,
2017 ConstantInt::get(MaskA->getType(), NewComperand));
2018 }
2019 }
2020
2021 return nullptr;
2022}
2023
2024/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2026 InstCombiner::BuilderTy &Builder) {
2027 // Are we using xors or subs to bitwise check for a pair or pairs of
2028 // (in)equalities? Convert to a shorter form that has more potential to be
2029 // folded even further.
2030 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2031 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2032 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2033 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2034 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2035 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2037 SmallVector<Value *, 16> WorkList(1, Or);
2038
2039 while (!WorkList.empty()) {
2040 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2041 Value *Lhs, *Rhs;
2042
2043 if (match(OrOperatorArgument,
2044 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2045 CmpValues.emplace_back(Lhs, Rhs);
2046 return;
2047 }
2048
2049 if (match(OrOperatorArgument,
2050 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2051 CmpValues.emplace_back(Lhs, Rhs);
2052 return;
2053 }
2054
2055 WorkList.push_back(OrOperatorArgument);
2056 };
2057
2058 Value *CurrentValue = WorkList.pop_back_val();
2059 Value *OrOperatorLhs, *OrOperatorRhs;
2060
2061 if (!match(CurrentValue,
2062 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2063 return nullptr;
2064 }
2065
2066 MatchOrOperatorArgument(OrOperatorRhs);
2067 MatchOrOperatorArgument(OrOperatorLhs);
2068 }
2069
2070 ICmpInst::Predicate Pred = Cmp.getPredicate();
2071 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2072 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2073 CmpValues.rbegin()->second);
2074
2075 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2076 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2077 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2078 }
2079
2080 return LhsCmp;
2081}
2082
2083/// Fold icmp (or X, Y), C.
2086 const APInt &C) {
2087 ICmpInst::Predicate Pred = Cmp.getPredicate();
2088 if (C.isOne()) {
2089 // icmp slt signum(V) 1 --> icmp slt V, 1
2090 Value *V = nullptr;
2091 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2092 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2093 ConstantInt::get(V->getType(), 1));
2094 }
2095
2096 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2097
2098 // (icmp eq/ne (or disjoint x, C0), C1)
2099 // -> (icmp eq/ne x, C0^C1)
2100 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2101 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2102 Value *NewC =
2103 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2104 return new ICmpInst(Pred, OrOp0, NewC);
2105 }
2106
2107 // An `or disjoint` is equivalent to `add nuw nsw`.
2108 const APInt *C0;
2109 if (match(OrOp1, m_APInt(C0)) && cast<PossiblyDisjointInst>(Or)->isDisjoint())
2110 if (Instruction *I = foldICmpAddLikeConstant(Cmp, OrOp0, *C0,
2111 /*HasNUW=*/true,
2112 /*HasNSW=*/true, C))
2113 return I;
2114
2115 const APInt *MaskC;
2116 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2117 if (*MaskC == C && (C + 1).isPowerOf2()) {
2118 // X | C == C --> X <=u C
2119 // X | C != C --> X >u C
2120 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2122 return new ICmpInst(Pred, OrOp0, OrOp1);
2123 }
2124
2125 // More general: canonicalize 'equality with set bits mask' to
2126 // 'equality with clear bits mask'.
2127 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2128 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2129 if (Or->hasOneUse()) {
2130 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2131 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2132 return new ICmpInst(Pred, And, NewC);
2133 }
2134 }
2135
2136 // (X | (X-1)) s< 0 --> X s< 1
2137 // (X | (X-1)) s> -1 --> X s> 0
2138 Value *X;
2139 bool TrueIfSigned;
2140 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2142 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2143 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2144 return new ICmpInst(NewPred, X, NewC);
2145 }
2146
2147 const APInt *OrC;
2148 // icmp(X | OrC, C) --> icmp(X, 0)
2149 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2150 switch (Pred) {
2151 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2152 case ICmpInst::ICMP_SLT:
2153 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2154 case ICmpInst::ICMP_SGE:
2155 if (OrC->sge(C))
2156 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2157 break;
2158 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2159 case ICmpInst::ICMP_SLE:
2160 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2161 case ICmpInst::ICMP_SGT:
2162 if (OrC->sgt(C))
2164 ConstantInt::getNullValue(X->getType()));
2165 break;
2166 default:
2167 break;
2168 }
2169 }
2170
2171 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2172 return nullptr;
2173
2174 Value *P, *Q;
2176 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2177 // -> and (icmp eq P, null), (icmp eq Q, null).
2178 Value *CmpP =
2179 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2180 Value *CmpQ =
2181 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2182 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2183 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2184 }
2185
2186 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2187 return replaceInstUsesWith(Cmp, V);
2188
2189 return nullptr;
2190}
2191
2192/// Fold icmp (mul X, Y), C.
2195 const APInt &C) {
2196 ICmpInst::Predicate Pred = Cmp.getPredicate();
2197 Type *MulTy = Mul->getType();
2198 Value *X = Mul->getOperand(0);
2199
2200 // If comparing a square with a constant, try simplifying to comparing square
2201 // roots.
2202 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2203 APInt R = C.sqrtFloor();
2204 bool IsSqr = C == R * R;
2205
2206 // X * X eq/ne C
2207 if (Cmp.isEquality() &&
2208 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2209
2210 // If constant is not a square, eq/ne is false/true respectively
2211 if (!IsSqr)
2212 return replaceInstUsesWith(
2213 Cmp,
2214 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2215
2216 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2217 }
2218
2219 // If the multiply does not wrap
2220 // X * X pred C --> X pred R
2221 if (Mul->hasNoUnsignedWrap()) {
2222
2223 if (IsSqr)
2224 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2225
2226 // If C is not a square, we use floor/ceil of sqrt(C).
2227 //
2228 // If LT or LE, we need R to be an overestimate of sqrt(C),
2229 // then use the strict predicate (LT->LT, LE->LT).
2230 //
2231 // If GT or GE, we need R to be an underestimate of sqrt(C),
2232 // then use the strict predicate (GT->GT, GE->GT).
2233 //
2234 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2235 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2236 ++R;
2237
2238 return new ICmpInst(Cmp.getStrictPredicate(), X,
2239 ConstantInt::get(MulTy, R));
2240 }
2241 }
2242
2243 const APInt *MulC;
2244 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2245 return nullptr;
2246
2247 // If this is a test of the sign bit and the multiply is sign-preserving with
2248 // a constant operand, use the multiply LHS operand instead:
2249 // (X * +MulC) < 0 --> X < 0
2250 // (X * -MulC) < 0 --> X > 0
2251 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2252 if (MulC->isNegative())
2253 Pred = ICmpInst::getSwappedPredicate(Pred);
2254 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2255 }
2256
2257 if (MulC->isZero())
2258 return nullptr;
2259
2260 // If the multiply does not wrap or the constant is odd, try to divide the
2261 // compare constant by the multiplication factor.
2262 if (Cmp.isEquality()) {
2263 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2264 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2265 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2266 return new ICmpInst(Pred, X, NewC);
2267 }
2268
2269 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2270 // correct to transform if MulC * N == C including overflow. I.e with i8
2271 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2272 // miss that case.
2273 if (C.urem(*MulC).isZero()) {
2274 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2275 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2276 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2277 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2278 return new ICmpInst(Pred, X, NewC);
2279 }
2280 }
2281 }
2282
2283 // With a matching no-overflow guarantee, fold the constants:
2284 // (X * MulC) < C --> X < (C / MulC)
2285 // (X * MulC) > C --> X > (C / MulC)
2286 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2287 Constant *NewC = nullptr;
2288 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2289 // MININT / -1 --> overflow.
2290 if (C.isMinSignedValue() && MulC->isAllOnes())
2291 return nullptr;
2292 if (MulC->isNegative())
2293 Pred = ICmpInst::getSwappedPredicate(Pred);
2294
2295 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2296 NewC = ConstantInt::get(
2298 } else {
2299 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2300 "Unexpected predicate");
2301 NewC = ConstantInt::get(
2303 }
2304 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2305 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2306 NewC = ConstantInt::get(
2308 } else {
2309 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2310 "Unexpected predicate");
2311 NewC = ConstantInt::get(
2313 }
2314 }
2315
2316 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2317}
2318
2319/// Fold icmp (shl nuw C2, Y), C.
2321 const APInt &C) {
2322 Value *Y;
2323 const APInt *C2;
2324 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2325 return nullptr;
2326
2327 Type *ShiftType = Shl->getType();
2328 unsigned TypeBits = C.getBitWidth();
2329 ICmpInst::Predicate Pred = Cmp.getPredicate();
2330 if (Cmp.isUnsigned()) {
2331 if (C2->isZero() || C2->ugt(C))
2332 return nullptr;
2333 APInt Div, Rem;
2334 APInt::udivrem(C, *C2, Div, Rem);
2335 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2336
2337 // (1 << Y) pred C -> Y pred Log2(C)
2338 if (!CIsPowerOf2) {
2339 // (1 << Y) < 30 -> Y <= 4
2340 // (1 << Y) <= 30 -> Y <= 4
2341 // (1 << Y) >= 30 -> Y > 4
2342 // (1 << Y) > 30 -> Y > 4
2343 if (Pred == ICmpInst::ICMP_ULT)
2345 else if (Pred == ICmpInst::ICMP_UGE)
2347 }
2348
2349 unsigned CLog2 = Div.logBase2();
2350 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2351 } else if (Cmp.isSigned() && C2->isOne()) {
2352 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2353 // (1 << Y) > 0 -> Y != 31
2354 // (1 << Y) > C -> Y != 31 if C is negative.
2355 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2356 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2357
2358 // (1 << Y) < 0 -> Y == 31
2359 // (1 << Y) < 1 -> Y == 31
2360 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2361 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2362 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2363 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2364 }
2365
2366 return nullptr;
2367}
2368
2369/// Fold icmp (shl X, Y), C.
2371 BinaryOperator *Shl,
2372 const APInt &C) {
2373 const APInt *ShiftVal;
2374 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2375 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2376
2377 ICmpInst::Predicate Pred = Cmp.getPredicate();
2378 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2379 // -> (icmp pred X, Csle0)
2380 //
2381 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2382 // so X's must be what is used.
2383 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2384 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2385
2386 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2387 // -> (icmp eq/ne X, 0)
2388 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2389 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2390 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2391
2392 // (icmp slt (shl nsw X, Y), 0/1)
2393 // -> (icmp slt X, 0/1)
2394 // (icmp sgt (shl nsw X, Y), 0/-1)
2395 // -> (icmp sgt X, 0/-1)
2396 //
2397 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2398 if (Shl->hasNoSignedWrap() &&
2399 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2400 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2401 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2402
2403 const APInt *ShiftAmt;
2404 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2405 return foldICmpShlLHSC(Cmp, Shl, C);
2406
2407 // Check that the shift amount is in range. If not, don't perform undefined
2408 // shifts. When the shift is visited, it will be simplified.
2409 unsigned TypeBits = C.getBitWidth();
2410 if (ShiftAmt->uge(TypeBits))
2411 return nullptr;
2412
2413 Value *X = Shl->getOperand(0);
2414 Type *ShType = Shl->getType();
2415
2416 // NSW guarantees that we are only shifting out sign bits from the high bits,
2417 // so we can ASHR the compare constant without needing a mask and eliminate
2418 // the shift.
2419 if (Shl->hasNoSignedWrap()) {
2420 if (Pred == ICmpInst::ICMP_SGT) {
2421 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2422 APInt ShiftedC = C.ashr(*ShiftAmt);
2423 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2424 }
2425 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2426 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2427 APInt ShiftedC = C.ashr(*ShiftAmt);
2428 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2429 }
2430 if (Pred == ICmpInst::ICMP_SLT) {
2431 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2432 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2433 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2434 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2435 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2436 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2437 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2438 }
2439 }
2440
2441 // NUW guarantees that we are only shifting out zero bits from the high bits,
2442 // so we can LSHR the compare constant without needing a mask and eliminate
2443 // the shift.
2444 if (Shl->hasNoUnsignedWrap()) {
2445 if (Pred == ICmpInst::ICMP_UGT) {
2446 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2447 APInt ShiftedC = C.lshr(*ShiftAmt);
2448 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2449 }
2450 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2451 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2452 APInt ShiftedC = C.lshr(*ShiftAmt);
2453 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2454 }
2455 if (Pred == ICmpInst::ICMP_ULT) {
2456 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2457 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2458 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2459 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2460 assert(C.ugt(0) && "ult 0 should have been eliminated");
2461 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2462 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2463 }
2464 }
2465
2466 if (Cmp.isEquality() && Shl->hasOneUse()) {
2467 // Strength-reduce the shift into an 'and'.
2468 Constant *Mask = ConstantInt::get(
2469 ShType,
2470 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2471 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2472 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2473 return new ICmpInst(Pred, And, LShrC);
2474 }
2475
2476 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2477 bool TrueIfSigned = false;
2478 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2479 // (X << 31) <s 0 --> (X & 1) != 0
2480 Constant *Mask = ConstantInt::get(
2481 ShType,
2482 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2483 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2484 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2485 And, Constant::getNullValue(ShType));
2486 }
2487
2488 // Simplify 'shl' inequality test into 'and' equality test.
2489 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2490 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2491 if ((C + 1).isPowerOf2() &&
2492 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2493 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2494 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2496 And, Constant::getNullValue(ShType));
2497 }
2498 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2499 if (C.isPowerOf2() &&
2500 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2501 Value *And =
2502 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2503 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2505 And, Constant::getNullValue(ShType));
2506 }
2507 }
2508
2509 // Transform (icmp pred iM (shl iM %v, N), C)
2510 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2511 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2512 // This enables us to get rid of the shift in favor of a trunc that may be
2513 // free on the target. It has the additional benefit of comparing to a
2514 // smaller constant that may be more target-friendly.
2515 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2516 if (Shl->hasOneUse() && Amt != 0 &&
2517 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2518 ICmpInst::Predicate CmpPred = Pred;
2519 APInt RHSC = C;
2520
2521 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2522 // Try the flipped strictness predicate.
2523 // e.g.:
2524 // icmp ult i64 (shl X, 32), 8589934593 ->
2525 // icmp ule i64 (shl X, 32), 8589934592 ->
2526 // icmp ule i32 (trunc X, i32), 2 ->
2527 // icmp ult i32 (trunc X, i32), 3
2528 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2529 Pred, ConstantInt::get(ShType->getContext(), C))) {
2530 CmpPred = FlippedStrictness->first;
2531 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2532 }
2533 }
2534
2535 if (RHSC.countr_zero() >= Amt) {
2536 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2537 Constant *NewC =
2538 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2539 return new ICmpInst(CmpPred,
2540 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2541 Shl->hasNoSignedWrap()),
2542 NewC);
2543 }
2544 }
2545
2546 return nullptr;
2547}
2548
2549/// Fold icmp ({al}shr X, Y), C.
2551 BinaryOperator *Shr,
2552 const APInt &C) {
2553 // An exact shr only shifts out zero bits, so:
2554 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2555 Value *X = Shr->getOperand(0);
2556 CmpInst::Predicate Pred = Cmp.getPredicate();
2557 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2558 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2559
2560 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2561 const APInt *ShiftValC;
2562 if (match(X, m_APInt(ShiftValC))) {
2563 if (Cmp.isEquality())
2564 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2565
2566 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2567 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2568 bool TrueIfSigned;
2569 if (!IsAShr && ShiftValC->isNegative() &&
2570 isSignBitCheck(Pred, C, TrueIfSigned))
2571 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2572 Shr->getOperand(1),
2573 ConstantInt::getNullValue(X->getType()));
2574
2575 // If the shifted constant is a power-of-2, test the shift amount directly:
2576 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2577 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2578 if (!IsAShr && ShiftValC->isPowerOf2() &&
2579 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2580 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2581 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2582 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2583
2584 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2585 unsigned ShiftLZ = ShiftValC->countl_zero();
2586 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2587 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2588 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2589 }
2590 }
2591
2592 const APInt *ShiftAmtC;
2593 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2594 return nullptr;
2595
2596 // Check that the shift amount is in range. If not, don't perform undefined
2597 // shifts. When the shift is visited it will be simplified.
2598 unsigned TypeBits = C.getBitWidth();
2599 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2600 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2601 return nullptr;
2602
2603 bool IsExact = Shr->isExact();
2604 Type *ShrTy = Shr->getType();
2605 // TODO: If we could guarantee that InstSimplify would handle all of the
2606 // constant-value-based preconditions in the folds below, then we could assert
2607 // those conditions rather than checking them. This is difficult because of
2608 // undef/poison (PR34838).
2609 if (IsAShr && Shr->hasOneUse()) {
2610 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2611 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2612 // When C - 1 is a power of two and the transform can be legally
2613 // performed, prefer this form so the produced constant is close to a
2614 // power of two.
2615 // icmp slt/ult (ashr exact X, ShAmtC), C
2616 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2617 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2618 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2619 }
2620 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2621 // When ShAmtC can be shifted losslessly:
2622 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2623 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2624 APInt ShiftedC = C.shl(ShAmtVal);
2625 if (ShiftedC.ashr(ShAmtVal) == C)
2626 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2627 }
2628 if (Pred == CmpInst::ICMP_SGT) {
2629 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2630 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2631 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2632 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2633 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2634 }
2635 if (Pred == CmpInst::ICMP_UGT) {
2636 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2637 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2638 // clause accounts for that pattern.
2639 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2640 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2641 (C + 1).shl(ShAmtVal).isMinSignedValue())
2642 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2643 }
2644
2645 // If the compare constant has significant bits above the lowest sign-bit,
2646 // then convert an unsigned cmp to a test of the sign-bit:
2647 // (ashr X, ShiftC) u> C --> X s< 0
2648 // (ashr X, ShiftC) u< C --> X s> -1
2649 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2650 if (Pred == CmpInst::ICMP_UGT) {
2651 return new ICmpInst(CmpInst::ICMP_SLT, X,
2653 }
2654 if (Pred == CmpInst::ICMP_ULT) {
2655 return new ICmpInst(CmpInst::ICMP_SGT, X,
2657 }
2658 }
2659 } else if (!IsAShr) {
2660 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2661 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2662 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2663 APInt ShiftedC = C.shl(ShAmtVal);
2664 if (ShiftedC.lshr(ShAmtVal) == C)
2665 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2666 }
2667 if (Pred == CmpInst::ICMP_UGT) {
2668 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2669 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2670 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2671 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2672 }
2673 }
2674
2675 if (!Cmp.isEquality())
2676 return nullptr;
2677
2678 // Handle equality comparisons of shift-by-constant.
2679
2680 // If the comparison constant changes with the shift, the comparison cannot
2681 // succeed (bits of the comparison constant cannot match the shifted value).
2682 // This should be known by InstSimplify and already be folded to true/false.
2683 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2684 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2685 "Expected icmp+shr simplify did not occur.");
2686
2687 // If the bits shifted out are known zero, compare the unshifted value:
2688 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2689 if (Shr->isExact())
2690 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2691
2692 if (Shr->hasOneUse()) {
2693 // Canonicalize the shift into an 'and':
2694 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2695 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2696 Constant *Mask = ConstantInt::get(ShrTy, Val);
2697 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2698 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2699 }
2700
2701 return nullptr;
2702}
2703
2705 BinaryOperator *SRem,
2706 const APInt &C) {
2707 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2708 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2709 // Canonicalize unsigned predicates to signed:
2710 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2711 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2712 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2713 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2714
2715 const APInt *DivisorC;
2716 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2717 return nullptr;
2718 if (DivisorC->isZero())
2719 return nullptr;
2720
2721 APInt NormalizedC = C;
2722 if (Pred == ICmpInst::ICMP_ULT) {
2723 assert(!NormalizedC.isZero() &&
2724 "ult X, 0 should have been simplified already.");
2725 --NormalizedC;
2726 }
2727 if (C.isNegative())
2728 NormalizedC.flipAllBits();
2729 if (!NormalizedC.uge(DivisorC->abs() - 1))
2730 return nullptr;
2731
2732 Type *Ty = SRem->getType();
2733 if (Pred == ICmpInst::ICMP_UGT)
2734 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2736 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2738 }
2739 // Match an 'is positive' or 'is negative' comparison of remainder by a
2740 // constant power-of-2 value:
2741 // (X % pow2C) sgt/slt 0
2742 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2743 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2744 return nullptr;
2745
2746 // TODO: The one-use check is standard because we do not typically want to
2747 // create longer instruction sequences, but this might be a special-case
2748 // because srem is not good for analysis or codegen.
2749 if (!SRem->hasOneUse())
2750 return nullptr;
2751
2752 const APInt *DivisorC;
2753 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2754 return nullptr;
2755
2756 // For cmp_sgt/cmp_slt only zero valued C is handled.
2757 // For cmp_eq/cmp_ne only positive valued C is handled.
2758 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2759 !C.isZero()) ||
2760 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2761 !C.isStrictlyPositive()))
2762 return nullptr;
2763
2764 // Mask off the sign bit and the modulo bits (low-bits).
2765 Type *Ty = SRem->getType();
2766 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2767 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2768 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2769
2770 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2771 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2772
2773 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2774 // bit is set. Example:
2775 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2776 if (Pred == ICmpInst::ICMP_SGT)
2778
2779 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2780 // bit is set. Example:
2781 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2782 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2783}
2784
2785/// Fold icmp (udiv X, Y), C.
2787 BinaryOperator *UDiv,
2788 const APInt &C) {
2789 ICmpInst::Predicate Pred = Cmp.getPredicate();
2790 Value *X = UDiv->getOperand(0);
2791 Value *Y = UDiv->getOperand(1);
2792 Type *Ty = UDiv->getType();
2793
2794 const APInt *C2;
2795 if (!match(X, m_APInt(C2)))
2796 return nullptr;
2797
2798 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2799
2800 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2801 if (Pred == ICmpInst::ICMP_UGT) {
2802 assert(!C.isMaxValue() &&
2803 "icmp ugt X, UINT_MAX should have been simplified already.");
2804 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2805 ConstantInt::get(Ty, C2->udiv(C + 1)));
2806 }
2807
2808 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2809 if (Pred == ICmpInst::ICMP_ULT) {
2810 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2811 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2812 ConstantInt::get(Ty, C2->udiv(C)));
2813 }
2814
2815 return nullptr;
2816}
2817
2818/// Fold icmp ({su}div X, Y), C.
2821 const APInt &C) {
2822 ICmpInst::Predicate Pred = Cmp.getPredicate();
2823 Value *X = Div->getOperand(0);
2824 Value *Y = Div->getOperand(1);
2825 Type *Ty = Div->getType();
2826 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2827
2828 // If unsigned division and the compare constant is bigger than
2829 // UMAX/2 (negative), there's only one pair of values that satisfies an
2830 // equality check, so eliminate the division:
2831 // (X u/ Y) == C --> (X == C) && (Y == 1)
2832 // (X u/ Y) != C --> (X != C) || (Y != 1)
2833 // Similarly, if signed division and the compare constant is exactly SMIN:
2834 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2835 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2836 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2837 (!DivIsSigned || C.isMinSignedValue())) {
2838 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2839 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2840 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2841 return BinaryOperator::Create(Logic, XBig, YOne);
2842 }
2843
2844 // Fold: icmp pred ([us]div X, C2), C -> range test
2845 // Fold this div into the comparison, producing a range check.
2846 // Determine, based on the divide type, what the range is being
2847 // checked. If there is an overflow on the low or high side, remember
2848 // it, otherwise compute the range [low, hi) bounding the new value.
2849 // See: InsertRangeTest above for the kinds of replacements possible.
2850 const APInt *C2;
2851 if (!match(Y, m_APInt(C2)))
2852 return nullptr;
2853
2854 // FIXME: If the operand types don't match the type of the divide
2855 // then don't attempt this transform. The code below doesn't have the
2856 // logic to deal with a signed divide and an unsigned compare (and
2857 // vice versa). This is because (x /s C2) <s C produces different
2858 // results than (x /s C2) <u C or (x /u C2) <s C or even
2859 // (x /u C2) <u C. Simply casting the operands and result won't
2860 // work. :( The if statement below tests that condition and bails
2861 // if it finds it.
2862 // However, when the divisor is a positive constant and the dividend is
2863 // known non-negative, sdiv is equivalent to udiv, so we can lower
2864 // DivIsSigned and proceed through the unsigned path.
2865 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2866 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2867 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2868 return nullptr;
2869 DivIsSigned = false;
2870 }
2871
2872 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2873 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2874 // division-by-constant cases should be present, we can not assert that they
2875 // have happened before we reach this icmp instruction.
2876 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2877 return nullptr;
2878
2879 // Compute Prod = C * C2. We are essentially solving an equation of
2880 // form X / C2 = C. We solve for X by multiplying C2 and C.
2881 // By solving for X, we can turn this into a range check instead of computing
2882 // a divide.
2883 APInt Prod = C * *C2;
2884
2885 // Determine if the product overflows by seeing if the product is not equal to
2886 // the divide. Make sure we do the same kind of divide as in the LHS
2887 // instruction that we're folding.
2888 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2889
2890 // If the division is known to be exact, then there is no remainder from the
2891 // divide, so the covered range size is unit, otherwise it is the divisor.
2892 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2893
2894 // Figure out the interval that is being checked. For example, a comparison
2895 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2896 // Compute this interval based on the constants involved and the signedness of
2897 // the compare/divide. This computes a half-open interval, keeping track of
2898 // whether either value in the interval overflows. After analysis each
2899 // overflow variable is set to 0 if it's corresponding bound variable is valid
2900 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2901 int LoOverflow = 0, HiOverflow = 0;
2902 APInt LoBound, HiBound;
2903
2904 if (!DivIsSigned) { // udiv
2905 // e.g. X/5 op 3 --> [15, 20)
2906 LoBound = Prod;
2907 HiOverflow = LoOverflow = ProdOV;
2908 if (!HiOverflow) {
2909 // If this is not an exact divide, then many values in the range collapse
2910 // to the same result value.
2911 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2912 }
2913 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2914 if (C.isZero()) { // (X / pos) op 0
2915 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2916 LoBound = -(RangeSize - 1);
2917 HiBound = RangeSize;
2918 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2919 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2920 HiOverflow = LoOverflow = ProdOV;
2921 if (!HiOverflow)
2922 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2923 } else { // (X / pos) op neg
2924 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2925 HiBound = Prod + 1;
2926 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2927 if (!LoOverflow) {
2928 APInt DivNeg = -RangeSize;
2929 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2930 }
2931 }
2932 } else if (C2->isNegative()) { // Divisor is < 0.
2933 if (Div->isExact())
2934 RangeSize.negate();
2935 if (C.isZero()) { // (X / neg) op 0
2936 // e.g. X/-5 op 0 --> [-4, 5)
2937 LoBound = RangeSize + 1;
2938 HiBound = -RangeSize;
2939 if (HiBound == *C2) { // -INTMIN = INTMIN
2940 HiOverflow = 1; // [INTMIN+1, overflow)
2941 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2942 }
2943 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2944 // e.g. X/-5 op 3 --> [-19, -14)
2945 HiBound = Prod + 1;
2946 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2947 if (!LoOverflow)
2948 LoOverflow =
2949 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
2950 } else { // (X / neg) op neg
2951 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
2952 LoOverflow = HiOverflow = ProdOV;
2953 if (!HiOverflow)
2954 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
2955 }
2956
2957 // Dividing by a negative swaps the condition. LT <-> GT
2958 Pred = ICmpInst::getSwappedPredicate(Pred);
2959 }
2960
2961 switch (Pred) {
2962 default:
2963 llvm_unreachable("Unhandled icmp predicate!");
2964 case ICmpInst::ICMP_EQ:
2965 if (LoOverflow && HiOverflow)
2966 return replaceInstUsesWith(Cmp, Builder.getFalse());
2967 if (HiOverflow)
2968 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2969 X, ConstantInt::get(Ty, LoBound));
2970 if (LoOverflow)
2971 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2972 X, ConstantInt::get(Ty, HiBound));
2973 return replaceInstUsesWith(
2974 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
2975 case ICmpInst::ICMP_NE:
2976 if (LoOverflow && HiOverflow)
2977 return replaceInstUsesWith(Cmp, Builder.getTrue());
2978 if (HiOverflow)
2979 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
2980 X, ConstantInt::get(Ty, LoBound));
2981 if (LoOverflow)
2982 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
2983 X, ConstantInt::get(Ty, HiBound));
2984 return replaceInstUsesWith(
2985 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
2986 case ICmpInst::ICMP_ULT:
2987 case ICmpInst::ICMP_SLT:
2988 if (LoOverflow == +1) // Low bound is greater than input range.
2989 return replaceInstUsesWith(Cmp, Builder.getTrue());
2990 if (LoOverflow == -1) // Low bound is less than input range.
2991 return replaceInstUsesWith(Cmp, Builder.getFalse());
2992 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
2993 case ICmpInst::ICMP_UGT:
2994 case ICmpInst::ICMP_SGT:
2995 if (HiOverflow == +1) // High bound greater than input range.
2996 return replaceInstUsesWith(Cmp, Builder.getFalse());
2997 if (HiOverflow == -1) // High bound less than input range.
2998 return replaceInstUsesWith(Cmp, Builder.getTrue());
2999 if (Pred == ICmpInst::ICMP_UGT)
3000 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3001 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3002 }
3003
3004 return nullptr;
3005}
3006
3007/// Fold icmp (sub X, Y), C.
3010 const APInt &C) {
3011 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3012 ICmpInst::Predicate Pred = Cmp.getPredicate();
3013 Type *Ty = Sub->getType();
3014
3015 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3016 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3017 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3018 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3019 const APInt *D;
3020 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3021 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3022 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3023 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3024 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3025 }
3026
3027 // (SubC - Y) == C) --> Y == (SubC - C)
3028 // (SubC - Y) != C) --> Y != (SubC - C)
3029 Constant *SubC;
3030 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3031 return new ICmpInst(Pred, Y,
3032 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3033 }
3034
3035 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3036 const APInt *C2;
3037 APInt SubResult;
3038 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3039 bool HasNSW = Sub->hasNoSignedWrap();
3040 bool HasNUW = Sub->hasNoUnsignedWrap();
3041 if (match(X, m_APInt(C2)) &&
3042 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3043 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3044 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3045
3046 // X - Y == 0 --> X == Y.
3047 // X - Y != 0 --> X != Y.
3048 // TODO: We allow this with multiple uses as long as the other uses are not
3049 // in phis. The phi use check is guarding against a codegen regression
3050 // for a loop test. If the backend could undo this (and possibly
3051 // subsequent transforms), we would not need this hack.
3052 if (Cmp.isEquality() && C.isZero() &&
3053 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3054 return new ICmpInst(Pred, X, Y);
3055
3056 // The following transforms are only worth it if the only user of the subtract
3057 // is the icmp.
3058 // TODO: This is an artificial restriction for all of the transforms below
3059 // that only need a single replacement icmp. Can these use the phi test
3060 // like the transform above here?
3061 if (!Sub->hasOneUse())
3062 return nullptr;
3063
3064 if (Sub->hasNoSignedWrap()) {
3065 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3066 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3067 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3068
3069 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3070 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3071 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3072
3073 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3074 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3075 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3076
3077 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3078 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3079 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3080 }
3081
3082 if (!match(X, m_APInt(C2)))
3083 return nullptr;
3084
3085 // C2 - Y <u C -> (Y | (C - 1)) == C2
3086 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3087 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3088 (*C2 & (C - 1)) == (C - 1))
3089 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3090
3091 // C2 - Y >u C -> (Y | C) != C2
3092 // iff C2 & C == C and C + 1 is a power of 2
3093 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3094 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3095
3096 // We have handled special cases that reduce.
3097 // Canonicalize any remaining sub to add as:
3098 // (C2 - Y) > C --> (Y + ~C2) < ~C
3099 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3100 HasNUW, HasNSW);
3101 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3102}
3103
3104static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3105 Value *Op1, IRBuilderBase &Builder,
3106 bool HasOneUse) {
3107 auto FoldConstant = [&](bool Val) {
3108 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3109 if (Op0->getType()->isVectorTy())
3111 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3112 return Res;
3113 };
3114
3115 switch (Table.to_ulong()) {
3116 case 0: // 0 0 0 0
3117 return FoldConstant(false);
3118 case 1: // 0 0 0 1
3119 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3120 case 2: // 0 0 1 0
3121 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3122 case 3: // 0 0 1 1
3123 return Builder.CreateNot(Op0);
3124 case 4: // 0 1 0 0
3125 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3126 case 5: // 0 1 0 1
3127 return Builder.CreateNot(Op1);
3128 case 6: // 0 1 1 0
3129 return Builder.CreateXor(Op0, Op1);
3130 case 7: // 0 1 1 1
3131 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3132 case 8: // 1 0 0 0
3133 return Builder.CreateAnd(Op0, Op1);
3134 case 9: // 1 0 0 1
3135 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3136 case 10: // 1 0 1 0
3137 return Op1;
3138 case 11: // 1 0 1 1
3139 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3140 case 12: // 1 1 0 0
3141 return Op0;
3142 case 13: // 1 1 0 1
3143 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3144 case 14: // 1 1 1 0
3145 return Builder.CreateOr(Op0, Op1);
3146 case 15: // 1 1 1 1
3147 return FoldConstant(true);
3148 default:
3149 llvm_unreachable("Invalid Operation");
3150 }
3151 return nullptr;
3152}
3153
3155 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3156 Value *A, *B;
3157 Constant *C1, *C2, *C3, *C4;
3158 if (!match(BO->getOperand(0),
3160 !match(BO->getOperand(1),
3162 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3163 return nullptr;
3164
3165 std::bitset<4> Table;
3166 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3167 Constant *L = First ? C1 : C2;
3168 Constant *R = Second ? C3 : C4;
3169 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3170 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3171 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3172 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3173 }
3174 return std::nullopt;
3175 };
3176
3177 for (unsigned I = 0; I < 4; ++I) {
3178 bool First = (I >> 1) & 1;
3179 bool Second = I & 1;
3180 if (auto Res = ComputeTable(First, Second))
3181 Table[I] = *Res;
3182 else
3183 return nullptr;
3184 }
3185
3186 // Synthesize optimal logic.
3187 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3188 return replaceInstUsesWith(Cmp, Cond);
3189 return nullptr;
3190}
3191
3192/// Fold `icmp pred (add X, C2), C` using the no-wrap flags of the add.
3193/// This function is also used by `or disjoint X, C2`.
3195 const APInt &C2,
3196 bool HasNUW, bool HasNSW,
3197 const APInt &C) {
3198 const CmpPredicate Pred = Cmp.getCmpPredicate();
3199 Type *Ty = X->getType();
3200
3201 // If the add does not wrap, we can always adjust the compare by subtracting
3202 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3203 // have been canonicalized to SGT/SLT/UGT/ULT.
3204 if (HasNUW && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3205 bool Overflow;
3206 APInt NewC = C.usub_ov(C2, Overflow);
3207 // If there is overflow, the result must be true or false.
3208 if (!Overflow)
3209 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3210 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3211 }
3212
3213 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3214
3215 if (HasNSW &&
3216 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3217 bool Overflow;
3218 APInt NewC = C.ssub_ov(C2, Overflow);
3219 if (!Overflow)
3220 // icmp samesign ugt/ult (add nsw X, C2), C
3221 // -> icmp sgt/slt X, (C - C2)
3222 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3223 }
3224
3225 if (ICmpInst::isUnsigned(Pred) && HasNSW && C.isNonNegative() &&
3226 (C - C2).isNonNegative() &&
3227 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3228 .add(C2)
3229 .isAllNonNegative())
3230 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3231 ConstantInt::get(Ty, C - C2));
3232
3233 return nullptr;
3234}
3235
3236/// Fold icmp (add X, Y), C.
3239 const APInt &C) {
3240 Value *Y = Add->getOperand(1);
3241 Value *X = Add->getOperand(0);
3242 const CmpPredicate Pred = Cmp.getCmpPredicate();
3243
3244 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3245 // when C <= (1 << ShAmtC).
3246 const APInt *ShAmtC;
3247 Value *A;
3248 unsigned BitWidth = C.getBitWidth();
3249 if (Pred == ICmpInst::ICMP_ULT &&
3250 match(Add,
3251 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3252 ShAmtC->ult(BitWidth) &&
3253 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3254 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3255
3256 const APInt *C2;
3257 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3258 return nullptr;
3259
3260 // Fold icmp pred (add X, C2), C.
3261 Type *Ty = Add->getType();
3262
3264 Cmp, X, *C2, Add->hasNoUnsignedWrap(), Add->hasNoSignedWrap(), C))
3265 return I;
3266
3267 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3268 const APInt &Upper = CR.getUpper();
3269 const APInt &Lower = CR.getLower();
3270 if (Cmp.isSigned()) {
3271 if (Lower.isSignMask())
3272 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3273 if (Upper.isSignMask())
3274 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3275 } else {
3276 if (Lower.isMinValue())
3277 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3278 if (Upper.isMinValue())
3279 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3280 }
3281
3282 // This set of folds is intentionally placed after folds that use no-wrapping
3283 // flags because those folds are likely better for later analysis/codegen.
3284 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3285 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3286
3287 // Fold compare with offset to opposite sign compare if it eliminates offset:
3288 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3289 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3290 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3291
3292 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3293 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3294 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3295
3296 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3297 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3298 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3299
3300 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3301 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3302 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3303
3304 // (X + -1) <u C --> X <=u C (if X is never null)
3305 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3306 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3307 if (llvm::isKnownNonZero(X, Q))
3308 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3309 }
3310
3311 if (!Add->hasOneUse())
3312 return nullptr;
3313
3314 // X+C <u C2 -> (X & -C2) == C
3315 // iff C & (C2-1) == 0
3316 // C2 is a power of 2
3317 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3318 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3320
3321 // X+C2 <u C -> (X & C) == 2C
3322 // iff C == -(C2)
3323 // C2 is a power of 2
3324 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3325 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3326 ConstantInt::get(Ty, C * 2));
3327
3328 // X+C >u C2 -> (X & ~C2) != C
3329 // iff C & C2 == 0
3330 // C2+1 is a power of 2
3331 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3332 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3334
3335 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3336 // to the ult form.
3337 // X+C2 >u C -> X+(C2-C-1) <u ~C
3338 if (Pred == ICmpInst::ICMP_UGT)
3339 return new ICmpInst(ICmpInst::ICMP_ULT,
3340 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3341 ConstantInt::get(Ty, ~C));
3342
3343 // zext(V) + C2 pred C -> V + C3 pred' C4
3344 Value *V;
3345 if (match(X, m_ZExt(m_Value(V)))) {
3346 Type *NewCmpTy = V->getType();
3347 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3348 if (shouldChangeType(Ty, NewCmpTy)) {
3349 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3350 CmpInst::Predicate EquivPred;
3351 APInt EquivInt;
3352 APInt EquivOffset;
3353
3354 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3355 return new ICmpInst(
3356 EquivPred,
3357 EquivOffset.isZero()
3358 ? V
3359 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3360 ConstantInt::get(NewCmpTy, EquivInt));
3361 }
3362 }
3363
3364 return nullptr;
3365}
3366
3368 Value *&RHS, ConstantInt *&Less,
3369 ConstantInt *&Equal,
3370 ConstantInt *&Greater) {
3371 // TODO: Generalize this to work with other comparison idioms or ensure
3372 // they get canonicalized into this form.
3373
3374 // select i1 (a == b),
3375 // i32 Equal,
3376 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3377 // where Equal, Less and Greater are placeholders for any three constants.
3378 CmpPredicate PredA;
3379 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3380 !ICmpInst::isEquality(PredA))
3381 return false;
3382 Value *EqualVal = SI->getTrueValue();
3383 Value *UnequalVal = SI->getFalseValue();
3384 // We still can get non-canonical predicate here, so canonicalize.
3385 if (PredA == ICmpInst::ICMP_NE)
3386 std::swap(EqualVal, UnequalVal);
3387 if (!match(EqualVal, m_ConstantInt(Equal)))
3388 return false;
3389 CmpPredicate PredB;
3390 Value *LHS2, *RHS2;
3391 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3392 m_ConstantInt(Less), m_ConstantInt(Greater))))
3393 return false;
3394 // We can get predicate mismatch here, so canonicalize if possible:
3395 // First, ensure that 'LHS' match.
3396 if (LHS2 != LHS) {
3397 // x sgt y <--> y slt x
3398 std::swap(LHS2, RHS2);
3399 PredB = ICmpInst::getSwappedPredicate(PredB);
3400 }
3401 if (LHS2 != LHS)
3402 return false;
3403 // We also need to canonicalize 'RHS'.
3404 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3405 // x sgt C-1 <--> x sge C <--> not(x slt C)
3406 auto FlippedStrictness =
3408 if (!FlippedStrictness)
3409 return false;
3410 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3411 "basic correctness failure");
3412 RHS2 = FlippedStrictness->second;
3413 // And kind-of perform the result swap.
3414 std::swap(Less, Greater);
3415 PredB = ICmpInst::ICMP_SLT;
3416 }
3417 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3418}
3419
3422 ConstantInt *C) {
3423
3424 assert(C && "Cmp RHS should be a constant int!");
3425 // If we're testing a constant value against the result of a three way
3426 // comparison, the result can be expressed directly in terms of the
3427 // original values being compared. Note: We could possibly be more
3428 // aggressive here and remove the hasOneUse test. The original select is
3429 // really likely to simplify or sink when we remove a test of the result.
3430 Value *OrigLHS, *OrigRHS;
3431 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3432 if (Cmp.hasOneUse() &&
3433 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3434 C3GreaterThan)) {
3435 assert(C1LessThan && C2Equal && C3GreaterThan);
3436
3437 bool TrueWhenLessThan = ICmpInst::compare(
3438 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3439 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3440 Cmp.getPredicate());
3441 bool TrueWhenGreaterThan = ICmpInst::compare(
3442 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3443
3444 // This generates the new instruction that will replace the original Cmp
3445 // Instruction. Instead of enumerating the various combinations when
3446 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3447 // false, we rely on chaining of ORs and future passes of InstCombine to
3448 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3449
3450 // When none of the three constants satisfy the predicate for the RHS (C),
3451 // the entire original Cmp can be simplified to a false.
3452 Value *Cond = Builder.getFalse();
3453 if (TrueWhenLessThan)
3454 Cond = Builder.CreateOr(
3455 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3456 if (TrueWhenEqual)
3457 Cond = Builder.CreateOr(
3458 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3459 if (TrueWhenGreaterThan)
3460 Cond = Builder.CreateOr(
3461 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3462
3463 return replaceInstUsesWith(Cmp, Cond);
3464 }
3465 return nullptr;
3466}
3467
3469 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3470 if (!Bitcast)
3471 return nullptr;
3472
3473 ICmpInst::Predicate Pred = Cmp.getPredicate();
3474 Value *Op1 = Cmp.getOperand(1);
3475 Value *BCSrcOp = Bitcast->getOperand(0);
3476 Type *SrcType = Bitcast->getSrcTy();
3477 Type *DstType = Bitcast->getType();
3478
3479 // Make sure the bitcast doesn't change between scalar and vector and
3480 // doesn't change the number of vector elements.
3481 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3482 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3483 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3484 Value *X;
3485 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3486 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3487 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3488 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3489 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3490 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3491 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3492 match(Op1, m_Zero()))
3493 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3494
3495 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3496 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3497 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3498
3499 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3500 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3501 return new ICmpInst(Pred, X,
3502 ConstantInt::getAllOnesValue(X->getType()));
3503 }
3504
3505 // Zero-equality checks are preserved through unsigned floating-point casts:
3506 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3507 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3508 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3509 if (Cmp.isEquality() && match(Op1, m_Zero()))
3510 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3511
3512 const APInt *C;
3513 bool TrueIfSigned;
3514 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3515 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3516 // the FP extend/truncate because that cast does not change the sign-bit.
3517 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3518 // The sign-bit is always the most significant bit in those types.
3519 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3520 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3521 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3522 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3523 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3524 Type *XType = X->getType();
3525
3526 // We can't currently handle Power style floating point operations here.
3527 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3528 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3529 if (auto *XVTy = dyn_cast<VectorType>(XType))
3530 NewType = VectorType::get(NewType, XVTy->getElementCount());
3531 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3532 if (TrueIfSigned)
3533 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3534 ConstantInt::getNullValue(NewType));
3535 else
3536 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3538 }
3539 }
3540
3541 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3542 Type *FPType = SrcType->getScalarType();
3543 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3544 Attribute::NoImplicitFloat) &&
3545 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3546 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3547 if (Mask & (fcInf | fcZero)) {
3548 if (Pred == ICmpInst::ICMP_NE)
3549 Mask = ~Mask;
3550 return replaceInstUsesWith(Cmp,
3551 Builder.createIsFPClass(BCSrcOp, Mask));
3552 }
3553 }
3554 }
3555 }
3556
3557 // Fold the canonicalized form of vector_reduce_or if the arg is
3558 // get_active_lane mask.
3559 // icmp ne (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3560 // icmp ult l, h
3561 // icmp eq (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3562 // icmp uge l, h
3563 Value *Upper, *Lower;
3565 m_Value(Lower), m_Value(Upper))) &&
3566 match(Op1, m_Zero()) && DstType->isIntegerTy()) {
3567 if (Pred == ICmpInst::ICMP_NE)
3568 return new ICmpInst(ICmpInst::ICMP_ULT, Lower, Upper);
3569 if (Pred == ICmpInst::ICMP_EQ)
3570 return new ICmpInst(ICmpInst::ICMP_UGE, Lower, Upper);
3571 }
3572
3573 const APInt *C;
3574 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3575 !SrcType->isIntOrIntVectorTy())
3576 return nullptr;
3577
3578 // If this is checking if all elements of a vector compare are set or not,
3579 // invert the casted vector equality compare and test if all compare
3580 // elements are clear or not. Compare against zero is generally easier for
3581 // analysis and codegen.
3582 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3583 // Example: are all elements equal? --> are zero elements not equal?
3584 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3585 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3586 if (Value *NotBCSrcOp =
3587 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3588 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3589 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3590 }
3591 }
3592
3593 // If this is checking if all elements of an extended vector are clear or not,
3594 // compare in a narrow type to eliminate the extend:
3595 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3596 Value *X;
3597 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3598 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3599 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3600 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3601 Value *NewCast = Builder.CreateBitCast(X, NewType);
3602 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3603 }
3604 }
3605
3606 // Folding: icmp <pred> iN X, C
3607 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3608 // and C is a splat of a K-bit pattern
3609 // and SC is a constant vector = <C', C', C', ..., C'>
3610 // Into:
3611 // %E = extractelement <M x iK> %vec, i32 C'
3612 // icmp <pred> iK %E, trunc(C)
3613 Value *Vec;
3614 ArrayRef<int> Mask;
3615 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3616 // Check whether every element of Mask is the same constant
3617 if (all_equal(Mask)) {
3618 auto *VecTy = cast<VectorType>(SrcType);
3619 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3620 if (C->isSplat(EltTy->getBitWidth())) {
3621 // Fold the icmp based on the value of C
3622 // If C is M copies of an iK sized bit pattern,
3623 // then:
3624 // => %E = extractelement <N x iK> %vec, i64 Elem
3625 // icmp <pred> iK %SplatVal, <pattern>
3626 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3627 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3628 return new ICmpInst(Pred, Extract, NewC);
3629 }
3630 }
3631 }
3632 return nullptr;
3633}
3634
3635/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3636/// where X is some kind of instruction.
3638 const APInt *C;
3639
3640 if (match(Cmp.getOperand(1), m_APInt(C))) {
3641 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3642 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3643 return I;
3644
3645 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3646 // For now, we only support constant integers while folding the
3647 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3648 // similar to the cases handled by binary ops above.
3649 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3650 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3651 return I;
3652
3653 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3654 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3655 return I;
3656
3657 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3659 return I;
3660
3661 {
3662 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3663 // fcmp olt/oge (fabs X), 2^ExpVal
3664 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3665 Value *X;
3666 if (match(Cmp.getOperand(0),
3669 ICmpInst::Predicate Pred = Cmp.getPredicate();
3670 APInt Exp;
3671 FCmpInst::Predicate NewPred;
3672 bool ValidPred = true;
3673
3674 switch (Pred) {
3675 case ICmpInst::ICMP_SLT:
3676 NewPred = FCmpInst::FCMP_OLT;
3677 Exp = *C - 1;
3678 break;
3679 case ICmpInst::ICMP_SGT:
3680 NewPred = FCmpInst::FCMP_OGE;
3681 Exp = *C;
3682 break;
3683 default:
3684 ValidPred = false;
3685 break;
3686 }
3687
3688 if (ValidPred) {
3689 const fltSemantics &Sem =
3690 X->getType()->getScalarType()->getFltSemantics();
3691 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3692
3693 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3694 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3695 int ExpVal = static_cast<int>(Exp.getSExtValue());
3696 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3698 Value *Fabs = Builder.CreateFAbs(X);
3699 return new FCmpInst(NewPred, Fabs,
3700 ConstantFP::get(X->getType(), CmpConst));
3701 }
3702 }
3703 }
3704 }
3705
3706 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3707 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3708 // TODO: This checks one-use, but that is not strictly necessary.
3709 Value *Cmp0 = Cmp.getOperand(0);
3710 Value *X, *Y;
3711 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3712 (match(Cmp0,
3714 m_Value(X), m_Value(Y)))) ||
3715 match(Cmp0,
3717 m_Value(X), m_Value(Y))))))
3718 return new ICmpInst(Cmp.getPredicate(), X, Y);
3719 }
3720
3721 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3723
3724 return nullptr;
3725}
3726
3727/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3728/// icmp eq/ne BO, C.
3730 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3731 // TODO: Some of these folds could work with arbitrary constants, but this
3732 // function is limited to scalar and vector splat constants.
3733 if (!Cmp.isEquality())
3734 return nullptr;
3735
3736 ICmpInst::Predicate Pred = Cmp.getPredicate();
3737 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3738 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3739 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3740
3741 switch (BO->getOpcode()) {
3742 case Instruction::SRem:
3743 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3744 if (C.isZero() && BO->hasOneUse()) {
3745 const APInt *BOC;
3746 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3747 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3748 return new ICmpInst(Pred, NewRem,
3750 }
3751 }
3752 break;
3753 case Instruction::Add: {
3754 // (A + C2) == C --> A == (C - C2)
3755 // (A + C2) != C --> A != (C - C2)
3756 // TODO: Remove the one-use limitation? See discussion in D58633.
3757 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3758 if (BO->hasOneUse())
3759 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3760 } else if (C.isZero()) {
3761 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3762 // efficiently invertible, or if the add has just this one use.
3763 if (Value *NegVal = dyn_castNegVal(BOp1))
3764 return new ICmpInst(Pred, BOp0, NegVal);
3765 if (Value *NegVal = dyn_castNegVal(BOp0))
3766 return new ICmpInst(Pred, NegVal, BOp1);
3767 if (BO->hasOneUse()) {
3768 // (add nuw A, B) != 0 -> (or A, B) != 0
3769 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3770 Value *Or = Builder.CreateOr(BOp0, BOp1);
3771 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3772 }
3773 Value *Neg = Builder.CreateNeg(BOp1);
3774 Neg->takeName(BO);
3775 return new ICmpInst(Pred, BOp0, Neg);
3776 }
3777 }
3778 break;
3779 }
3780 case Instruction::Xor:
3781 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3782 // For the xor case, we can xor two constants together, eliminating
3783 // the explicit xor.
3784 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3785 } else if (C.isZero()) {
3786 // Replace ((xor A, B) != 0) with (A != B)
3787 return new ICmpInst(Pred, BOp0, BOp1);
3788 }
3789 break;
3790 case Instruction::Or: {
3791 const APInt *BOC;
3792 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3793 // Comparing if all bits outside of a constant mask are set?
3794 // Replace (X | C) == -1 with (X & ~C) == ~C.
3795 // This removes the -1 constant.
3797 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3798 return new ICmpInst(Pred, And, NotBOC);
3799 }
3800 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3801 // -> (and cond, (icmp eq Other, 0))
3802 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3803 // -> (or cond, (icmp ne Other, 0))
3804 Value *Cond, *TV, *FV, *Other, *Sel;
3805 if (C.isZero() &&
3806 match(BO,
3809 m_Value(FV))),
3810 m_Value(Other)))) &&
3811 Cond->getType() == Cmp.getType()) {
3812 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3813 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3814 if (Pred == ICmpInst::ICMP_EQ
3815 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3816 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3817 Value *Cmp = Builder.CreateICmp(
3818 Pred, Other, Constant::getNullValue(Other->getType()));
3820 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3821 Cond);
3822 }
3823 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3824 // case we need to invert the select condition so we need to be careful to
3825 // avoid creating extra instructions.
3826 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3827 // -> (or (not cond), (icmp ne Other, 0))
3828 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3829 // -> (and (not cond), (icmp eq Other, 0))
3830 //
3831 // Only do this if the inner select has one use, in which case we are
3832 // replacing `select` with `(not cond)`. Otherwise, we will create more
3833 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3834 // cond was freely invertable, the select arms would have been inverted.
3835 if (Sel->hasOneUse() &&
3836 (Pred == ICmpInst::ICMP_EQ
3837 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3838 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3839 Value *NotCond = Builder.CreateNot(Cond);
3840 Value *Cmp = Builder.CreateICmp(
3841 Pred, Other, Constant::getNullValue(Other->getType()));
3843 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3844 NotCond);
3845 }
3846 }
3847 break;
3848 }
3849 case Instruction::UDiv:
3850 case Instruction::SDiv:
3851 if (BO->isExact()) {
3852 // div exact X, Y eq/ne 0 -> X eq/ne 0
3853 // div exact X, Y eq/ne 1 -> X eq/ne Y
3854 // div exact X, Y eq/ne C ->
3855 // if Y * C never-overflow && OneUse:
3856 // -> Y * C eq/ne X
3857 if (C.isZero())
3858 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3859 else if (C.isOne())
3860 return new ICmpInst(Pred, BOp0, BOp1);
3861 else if (BO->hasOneUse()) {
3863 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3864 Cmp.getOperand(1), BO);
3866 Value *YC =
3867 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3868 return new ICmpInst(Pred, YC, BOp0);
3869 }
3870 }
3871 }
3872 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3873 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3874 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3875 return new ICmpInst(NewPred, BOp1, BOp0);
3876 }
3877 break;
3878 default:
3879 break;
3880 }
3881 return nullptr;
3882}
3883
3885 const APInt &CRhs,
3886 InstCombiner::BuilderTy &Builder,
3887 const SimplifyQuery &Q) {
3888 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3889 "Non-ctpop intrin in ctpop fold");
3890 if (!CtpopLhs->hasOneUse())
3891 return nullptr;
3892
3893 // Power of 2 test:
3894 // isPow2OrZero : ctpop(X) u< 2
3895 // isPow2 : ctpop(X) == 1
3896 // NotPow2OrZero: ctpop(X) u> 1
3897 // NotPow2 : ctpop(X) != 1
3898 // If we know any bit of X can be folded to:
3899 // IsPow2 : X & (~Bit) == 0
3900 // NotPow2 : X & (~Bit) != 0
3901 const ICmpInst::Predicate Pred = I.getPredicate();
3902 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3903 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3904 Value *Op = CtpopLhs->getArgOperand(0);
3905 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CtxI, Q.DT);
3906 // No need to check for count > 1, that should be already constant folded.
3907 if (OpKnown.countMinPopulation() == 1) {
3908 Value *And = Builder.CreateAnd(
3909 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3910 return new ICmpInst(
3914 And, Constant::getNullValue(Op->getType()));
3915 }
3916 }
3917
3918 return nullptr;
3919}
3920
3921/// Fold an equality icmp with LLVM intrinsic and constant operand.
3923 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3924 Type *Ty = II->getType();
3925 unsigned BitWidth = C.getBitWidth();
3926 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3927
3928 switch (II->getIntrinsicID()) {
3929 case Intrinsic::abs:
3930 // abs(A) == 0 -> A == 0
3931 // abs(A) == INT_MIN -> A == INT_MIN
3932 if (C.isZero() || C.isMinSignedValue())
3933 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3934 break;
3935
3936 case Intrinsic::bswap:
3937 // bswap(A) == C -> A == bswap(C)
3938 return new ICmpInst(Pred, II->getArgOperand(0),
3939 ConstantInt::get(Ty, C.byteSwap()));
3940
3941 case Intrinsic::bitreverse:
3942 // bitreverse(A) == C -> A == bitreverse(C)
3943 return new ICmpInst(Pred, II->getArgOperand(0),
3944 ConstantInt::get(Ty, C.reverseBits()));
3945
3946 case Intrinsic::ctlz:
3947 case Intrinsic::cttz: {
3948 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3949 if (C == BitWidth)
3950 return new ICmpInst(Pred, II->getArgOperand(0),
3952
3953 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3954 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3955 // Limit to one use to ensure we don't increase instruction count.
3956 unsigned Num = C.getLimitedValue(BitWidth);
3957 if (Num != BitWidth && II->hasOneUse()) {
3958 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3959 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3960 : APInt::getHighBitsSet(BitWidth, Num + 1);
3961 APInt Mask2 = IsTrailing
3964 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
3965 ConstantInt::get(Ty, Mask2));
3966 }
3967 break;
3968 }
3969
3970 case Intrinsic::ctpop: {
3971 // popcount(A) == 0 -> A == 0 and likewise for !=
3972 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
3973 bool IsZero = C.isZero();
3974 if (IsZero || C == BitWidth)
3975 return new ICmpInst(Pred, II->getArgOperand(0),
3976 IsZero ? Constant::getNullValue(Ty)
3978
3979 break;
3980 }
3981
3982 case Intrinsic::fshl:
3983 case Intrinsic::fshr:
3984 if (II->getArgOperand(0) == II->getArgOperand(1)) {
3985 const APInt *RotAmtC;
3986 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
3987 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
3988 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
3989 return new ICmpInst(Pred, II->getArgOperand(0),
3990 II->getIntrinsicID() == Intrinsic::fshl
3991 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
3992 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
3993 }
3994 break;
3995
3996 case Intrinsic::umax:
3997 case Intrinsic::uadd_sat: {
3998 // uadd.sat(a, b) == 0 -> (a | b) == 0
3999 // umax(a, b) == 0 -> (a | b) == 0
4000 if (C.isZero() && II->hasOneUse()) {
4001 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4002 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4003 }
4004 break;
4005 }
4006
4007 case Intrinsic::ssub_sat:
4008 // ssub.sat(a, b) == 0 -> a == b
4009 //
4010 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4011 // (because 1 saturates to 0). Just skip the optimization for i1.
4012 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4013 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4014 break;
4015 case Intrinsic::usub_sat: {
4016 // usub.sat(a, b) == 0 -> a <= b
4017 if (C.isZero()) {
4018 ICmpInst::Predicate NewPred =
4020 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4021 }
4022 break;
4023 }
4024 default:
4025 break;
4026 }
4027
4028 return nullptr;
4029}
4030
4031/// Fold an icmp with LLVM intrinsics
4032static Instruction *
4034 InstCombiner::BuilderTy &Builder) {
4035 assert(Cmp.isEquality());
4036
4037 ICmpInst::Predicate Pred = Cmp.getPredicate();
4038 Value *Op0 = Cmp.getOperand(0);
4039 Value *Op1 = Cmp.getOperand(1);
4040 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4041 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4042 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4043 return nullptr;
4044
4045 switch (IIOp0->getIntrinsicID()) {
4046 case Intrinsic::bswap:
4047 case Intrinsic::bitreverse:
4048 // If both operands are byte-swapped or bit-reversed, just compare the
4049 // original values.
4050 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4051 case Intrinsic::fshl:
4052 case Intrinsic::fshr: {
4053 // If both operands are rotated by same amount, just compare the
4054 // original values.
4055 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4056 break;
4057 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4058 break;
4059 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4060 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4061
4062 // rotate(X, AmtX) == rotate(Y, AmtY)
4063 // -> rotate(X, AmtX - AmtY) == Y
4064 // Do this if either both rotates have one use or if only one has one use
4065 // and AmtX/AmtY are constants.
4066 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4067 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4068 if (OneUses == 2 ||
4069 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4070 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4071
4072 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4073 // of two.
4074 if (isPowerOf2_32(BW)) {
4075 Value *SubAmt =
4076 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4077 Value *CombinedRotate = Builder.CreateIntrinsic(
4078 Op0->getType(), IIOp0->getIntrinsicID(),
4079 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4080 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4081 }
4082 }
4083 } break;
4084 default:
4085 break;
4086 }
4087
4088 return nullptr;
4089}
4090
4091/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4092/// where X is some kind of instruction and C is AllowPoison.
4093/// TODO: Move more folds which allow poison to this function.
4096 const APInt &C) {
4097 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4098 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4099 switch (II->getIntrinsicID()) {
4100 default:
4101 break;
4102 case Intrinsic::fshl:
4103 case Intrinsic::fshr:
4104 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4105 // (rot X, ?) == 0/-1 --> X == 0/-1
4106 if (C.isZero() || C.isAllOnes())
4107 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4108 }
4109 break;
4110 }
4111 }
4112
4113 return nullptr;
4114}
4115
4116/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4118 BinaryOperator *BO,
4119 const APInt &C) {
4120 switch (BO->getOpcode()) {
4121 case Instruction::Xor:
4122 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4123 return I;
4124 break;
4125 case Instruction::And:
4126 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4127 return I;
4128 break;
4129 case Instruction::Or:
4130 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4131 return I;
4132 break;
4133 case Instruction::Mul:
4134 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4135 return I;
4136 break;
4137 case Instruction::Shl:
4138 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4139 return I;
4140 break;
4141 case Instruction::LShr:
4142 case Instruction::AShr:
4143 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4144 return I;
4145 break;
4146 case Instruction::SRem:
4147 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4148 return I;
4149 break;
4150 case Instruction::UDiv:
4151 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4152 return I;
4153 [[fallthrough]];
4154 case Instruction::SDiv:
4155 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4156 return I;
4157 break;
4158 case Instruction::Sub:
4159 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4160 return I;
4161 break;
4162 case Instruction::Add:
4163 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4164 return I;
4165 break;
4166 default:
4167 break;
4168 }
4169
4170 // TODO: These folds could be refactored to be part of the above calls.
4172 return I;
4173
4174 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4175 // : C4), C5` pattern, by computing a truth table of the four constant
4176 // variants.
4178}
4179
4180static Instruction *
4182 const APInt &C,
4183 InstCombiner::BuilderTy &Builder) {
4184 // This transform may end up producing more than one instruction for the
4185 // intrinsic, so limit it to one user of the intrinsic.
4186 if (!II->hasOneUse())
4187 return nullptr;
4188
4189 // Let Y = [add/sub]_sat(X, C) pred C2
4190 // SatVal = The saturating value for the operation
4191 // WillWrap = Whether or not the operation will underflow / overflow
4192 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4193 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4194 //
4195 // When (SatVal pred C2) is true, then
4196 // Y = WillWrap ? true : ((X binop C) pred C2)
4197 // => Y = WillWrap || ((X binop C) pred C2)
4198 // else
4199 // Y = WillWrap ? false : ((X binop C) pred C2)
4200 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4201 // => Y = !WillWrap && ((X binop C) pred C2)
4202 Value *Op0 = II->getOperand(0);
4203 Value *Op1 = II->getOperand(1);
4204
4205 const APInt *COp1;
4206 // This transform only works when the intrinsic has an integral constant or
4207 // splat vector as the second operand.
4208 if (!match(Op1, m_APInt(COp1)))
4209 return nullptr;
4210
4211 APInt SatVal;
4212 switch (II->getIntrinsicID()) {
4213 default:
4215 "This function only works with usub_sat and uadd_sat for now!");
4216 case Intrinsic::uadd_sat:
4217 SatVal = APInt::getAllOnes(C.getBitWidth());
4218 break;
4219 case Intrinsic::usub_sat:
4220 SatVal = APInt::getZero(C.getBitWidth());
4221 break;
4222 }
4223
4224 // Check (SatVal pred C2)
4225 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4226
4227 // !WillWrap.
4229 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4230
4231 // WillWrap.
4232 if (SatValCheck)
4233 C1 = C1.inverse();
4234
4236 if (II->getBinaryOp() == Instruction::Add)
4237 C2 = C2.sub(*COp1);
4238 else
4239 C2 = C2.add(*COp1);
4240
4241 Instruction::BinaryOps CombiningOp =
4242 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4243
4244 std::optional<ConstantRange> Combination;
4245 if (CombiningOp == Instruction::BinaryOps::Or)
4246 Combination = C1.exactUnionWith(C2);
4247 else /* CombiningOp == Instruction::BinaryOps::And */
4248 Combination = C1.exactIntersectWith(C2);
4249
4250 if (!Combination)
4251 return nullptr;
4252
4253 CmpInst::Predicate EquivPred;
4254 APInt EquivInt;
4255 APInt EquivOffset;
4256
4257 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4258
4259 return new ICmpInst(
4260 EquivPred,
4261 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4262 ConstantInt::get(Op1->getType(), EquivInt));
4263}
4264
4265static Instruction *
4267 const APInt &C,
4268 InstCombiner::BuilderTy &Builder) {
4269 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4270 switch (Pred) {
4271 case ICmpInst::ICMP_EQ:
4272 case ICmpInst::ICMP_NE:
4273 if (C.isZero())
4274 NewPredicate = Pred;
4275 else if (C.isOne())
4276 NewPredicate =
4278 else if (C.isAllOnes())
4279 NewPredicate =
4281 break;
4282
4283 case ICmpInst::ICMP_SGT:
4284 if (C.isAllOnes())
4285 NewPredicate = ICmpInst::ICMP_UGE;
4286 else if (C.isZero())
4287 NewPredicate = ICmpInst::ICMP_UGT;
4288 break;
4289
4290 case ICmpInst::ICMP_SLT:
4291 if (C.isZero())
4292 NewPredicate = ICmpInst::ICMP_ULT;
4293 else if (C.isOne())
4294 NewPredicate = ICmpInst::ICMP_ULE;
4295 break;
4296
4297 case ICmpInst::ICMP_ULT:
4298 if (C.ugt(1))
4299 NewPredicate = ICmpInst::ICMP_UGE;
4300 break;
4301
4302 case ICmpInst::ICMP_UGT:
4303 if (!C.isZero() && !C.isAllOnes())
4304 NewPredicate = ICmpInst::ICMP_ULT;
4305 break;
4306
4307 default:
4308 break;
4309 }
4310
4311 if (!NewPredicate)
4312 return nullptr;
4313
4314 if (I->getIntrinsicID() == Intrinsic::scmp)
4315 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4316 Value *LHS = I->getOperand(0);
4317 Value *RHS = I->getOperand(1);
4318 return new ICmpInst(*NewPredicate, LHS, RHS);
4319}
4320
4321/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4324 const APInt &C) {
4325 ICmpInst::Predicate Pred = Cmp.getPredicate();
4326
4327 // Handle folds that apply for any kind of icmp.
4328 switch (II->getIntrinsicID()) {
4329 default:
4330 break;
4331 case Intrinsic::uadd_sat:
4332 case Intrinsic::usub_sat:
4334 Pred, cast<SaturatingInst>(II), C, Builder))
4335 return Folded;
4336 break;
4337 case Intrinsic::ctpop: {
4338 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4339 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4340 return R;
4341 } break;
4342 case Intrinsic::scmp:
4343 case Intrinsic::ucmp:
4345 return Folded;
4346 break;
4347 }
4348
4349 if (Cmp.isEquality())
4350 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4351
4352 Type *Ty = II->getType();
4353 unsigned BitWidth = C.getBitWidth();
4354 switch (II->getIntrinsicID()) {
4355 case Intrinsic::ctpop: {
4356 // (ctpop X > BitWidth - 1) --> X == -1
4357 Value *X = II->getArgOperand(0);
4358 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4359 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4361 // (ctpop X < BitWidth) --> X != -1
4362 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4363 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4365 break;
4366 }
4367 case Intrinsic::ctlz: {
4368 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4369 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4370 unsigned Num = C.getLimitedValue();
4371 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4372 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4373 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4374 }
4375
4376 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4377 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4378 unsigned Num = C.getLimitedValue();
4380 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4381 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4382 }
4383 break;
4384 }
4385 case Intrinsic::cttz: {
4386 // Limit to one use to ensure we don't increase instruction count.
4387 if (!II->hasOneUse())
4388 return nullptr;
4389
4390 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4391 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4392 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4393 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4394 Builder.CreateAnd(II->getArgOperand(0), Mask),
4396 }
4397
4398 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4399 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4400 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4401 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4402 Builder.CreateAnd(II->getArgOperand(0), Mask),
4404 }
4405 break;
4406 }
4407 case Intrinsic::ssub_sat:
4408 // ssub.sat(a, b) spred 0 -> a spred b
4409 //
4410 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4411 // (because 1 saturates to 0). Just skip the optimization for i1.
4412 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4413 if (C.isZero())
4414 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4415 // X s<= 0 is cannonicalized to X s< 1
4416 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4417 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4418 II->getArgOperand(1));
4419 // X s>= 0 is cannonicalized to X s> -1
4420 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4421 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4422 II->getArgOperand(1));
4423 }
4424 break;
4425 case Intrinsic::abs: {
4426 if (!II->hasOneUse())
4427 return nullptr;
4428
4429 Value *X = II->getArgOperand(0);
4430
4431 // If C >= 0:
4432 // abs(X) u> C --> X + C u> 2 * C
4433 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4434 return new ICmpInst(ICmpInst::ICMP_UGT,
4435 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4436 ConstantInt::get(Ty, 2 * C));
4437 }
4438
4439 // If C >= 1:
4440 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4441 if (Pred == CmpInst::ICMP_ULT && C.sge(1))
4442 return new ICmpInst(ICmpInst::ICMP_ULE,
4443 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4444 ConstantInt::get(Ty, 2 * (C - 1)));
4445
4446 break;
4447 }
4448 default:
4449 break;
4450 }
4451
4452 return nullptr;
4453}
4454
4455/// Handle icmp with constant (but not simple integer constant) RHS.
4457 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4458 Constant *RHSC = dyn_cast<Constant>(Op1);
4460 if (!RHSC || !LHSI)
4461 return nullptr;
4462
4463 switch (LHSI->getOpcode()) {
4464 // umax(X, Y) == null -> (X == null) && (Y == null).
4465 // umax(X, Y) != null -> (X != null) || (Y != null).
4466 case Instruction::Select: {
4467 CmpInst::Predicate Pred = I.getPredicate();
4468 if (!ICmpInst::isEquality(Pred) || !RHSC->getType()->isPtrOrPtrVectorTy())
4469 break;
4470
4471 // Require zero address bits, the minimum unsigned pointer value.
4472 Constant *RHSIndexBits = ConstantFoldCastOperand(
4473 Instruction::PtrToAddr, RHSC, DL.getIndexType(RHSC->getType()), DL);
4474 if (!RHSIndexBits || !RHSIndexBits->isNullValue())
4475 break;
4476
4477 auto *SI = cast<SelectInst>(LHSI);
4478 // Both the select and its comparison must die to avoid adding instructions.
4479 if (!SI->hasOneUse() || !SI->getCondition()->hasOneUse())
4480 break;
4481
4482 // Require the condition to compare the select operands directly.
4483 Value *A = SI->getTrueValue();
4484 Value *B = SI->getFalseValue();
4485 CmpPredicate SelectPred;
4486 if (!match(SI->getCondition(),
4487 m_c_ICmp(SelectPred, m_Specific(A), m_Specific(B))) ||
4488 (SelectPred != ICmpInst::ICMP_UGT && SelectPred != ICmpInst::ICMP_UGE))
4489 break;
4490
4491 Value *ACmp = Builder.CreateICmp(Pred, A, RHSC);
4492 Value *BCmp = Builder.CreateICmp(Pred, B, RHSC);
4493 // The original icmp propagates poison from both operands; and/or is safe.
4494 return BinaryOperator::Create(Pred == ICmpInst::ICMP_EQ ? Instruction::And
4495 : Instruction::Or,
4496 ACmp, BCmp);
4497 }
4498
4499 case Instruction::IntToPtr:
4500 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4501 if (isa<ConstantPointerNull>(RHSC)) {
4502 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4503 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4504 APInt NullPtrValue =
4505 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4506 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4507 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4508 }
4509 }
4510 break;
4511
4512 case Instruction::Load:
4513 // Try to optimize things like "A[i] > 4" to index computations.
4515 cast<LoadInst>(LHSI), I.getPredicate(), RHSC, I))
4516 return Res;
4517 break;
4518 }
4519
4520 return nullptr;
4521}
4522
4524 Value *RHS, const ICmpInst &I) {
4525 // Try to fold the comparison into the select arms, which will cause the
4526 // select to be converted into a logical and/or.
4527 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4528 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4529 return Res;
4530 if (std::optional<bool> Impl = isImpliedCondition(
4531 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4532 return ConstantInt::get(I.getType(), *Impl);
4533 return nullptr;
4534 };
4535
4536 ConstantInt *CI = nullptr;
4537 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4538 if (Op1)
4539 CI = dyn_cast<ConstantInt>(Op1);
4540
4541 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4542 if (Op2)
4543 CI = dyn_cast<ConstantInt>(Op2);
4544
4545 auto Simplifies = [&](Value *Op, unsigned Idx) {
4546 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4547 const APInt *Dummy;
4548 return Op ||
4549 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4550 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4551 };
4552
4553 // We only want to perform this transformation if it will not lead to
4554 // additional code. This is true if either both sides of the select
4555 // fold to a constant (in which case the icmp is replaced with a select
4556 // which will usually simplify) or this is the only user of the
4557 // select (in which case we are trading a select+icmp for a simpler
4558 // select+icmp) or all uses of the select can be replaced based on
4559 // dominance information ("Global cases").
4560 bool Transform = false;
4561 if (Op1 && Op2)
4562 Transform = true;
4563 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4564 // Local case
4565 if (SI->hasOneUse())
4566 Transform = true;
4567 // Global cases
4568 else if (CI && !CI->isZero())
4569 // When Op1 is constant try replacing select with second operand.
4570 // Otherwise Op2 is constant and try replacing select with first
4571 // operand.
4572 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4573 }
4574 if (Transform) {
4575 if (!Op1)
4576 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4577 if (!Op2)
4578 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4579 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr, SI);
4580 }
4581
4582 // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
4583 // When the select condition compares X with a constant P and the select
4584 // arms are constants C1/C2, we can fold to a set membership test.
4585 // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
4586 // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
4587 if (ICmpInst::isEquality(Pred)) {
4588 CmpPredicate CondPred;
4589 const APInt *C1, *C2, *P;
4590 if (match(SI,
4591 m_OneUse(m_Select(m_ICmp(CondPred, m_Specific(RHS), m_APInt(P)),
4592 m_APInt(C1), m_APInt(C2))))) {
4593 bool C1SatisfiesCond = ICmpInst::compare(*C1, *P, CondPred);
4594 bool C2SatisfiesCond = ICmpInst::compare(*C2, *P, CondPred);
4595
4596 if (C1SatisfiesCond && !C2SatisfiesCond) {
4597 // X == select(cond, C1, C2) -> (X == C1) | (X == C2)
4598 // X != select(cond, C1, C2) -> (X != C1) & (X != C2)
4599 Value *Cmp1 = Builder.CreateICmp(Pred, RHS, SI->getTrueValue());
4600 Value *Cmp2 = Builder.CreateICmp(Pred, RHS, SI->getFalseValue());
4601 if (Pred == ICmpInst::ICMP_EQ)
4602 return BinaryOperator::CreateOr(Cmp1, Cmp2);
4603 return BinaryOperator::CreateAnd(Cmp1, Cmp2);
4604 }
4605 }
4606 }
4607
4608 return nullptr;
4609}
4610
4611// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4612static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4613 unsigned Depth = 0) {
4615 return true;
4616 if (V->getType()->getScalarSizeInBits() == 1)
4617 return true;
4619 return false;
4620 Value *X;
4622 if (!I)
4623 return false;
4624 switch (I->getOpcode()) {
4625 case Instruction::ZExt:
4626 // ZExt(Mask) is a Mask.
4627 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4628 case Instruction::SExt:
4629 // SExt(Mask) is a Mask.
4630 // SExt(~Mask) is a ~Mask.
4631 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4632 case Instruction::And:
4633 case Instruction::Or:
4634 // Mask0 | Mask1 is a Mask.
4635 // Mask0 & Mask1 is a Mask.
4636 // ~Mask0 | ~Mask1 is a ~Mask.
4637 // ~Mask0 & ~Mask1 is a ~Mask.
4638 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4639 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4640 case Instruction::Xor:
4641 if (match(V, m_Not(m_Value(X))))
4642 return isMaskOrZero(X, !Not, Q, Depth);
4643
4644 // (X ^ -X) is a ~Mask
4645 if (Not)
4646 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4647 // (X ^ (X - 1)) is a Mask
4648 else
4649 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4650 case Instruction::Select:
4651 // c ? Mask0 : Mask1 is a Mask.
4652 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4653 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4654 case Instruction::Shl:
4655 // (~Mask) << X is a ~Mask.
4656 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4657 case Instruction::LShr:
4658 // Mask >> X is a Mask.
4659 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4660 case Instruction::AShr:
4661 // Mask s>> X is a Mask.
4662 // ~Mask s>> X is a ~Mask.
4663 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4664 case Instruction::Add:
4665 // Pow2 - 1 is a Mask.
4666 if (!Not && match(I->getOperand(1), m_AllOnes()))
4667 return isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero=*/true, Q,
4668 Depth);
4669 break;
4670 case Instruction::Sub:
4671 // -Pow2 is a ~Mask.
4672 if (Not && match(I->getOperand(0), m_Zero()))
4673 return isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero=*/true, Q,
4674 Depth);
4675 break;
4676 case Instruction::Call: {
4677 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4678 switch (II->getIntrinsicID()) {
4679 // min/max(Mask0, Mask1) is a Mask.
4680 // min/max(~Mask0, ~Mask1) is a ~Mask.
4681 case Intrinsic::umax:
4682 case Intrinsic::smax:
4683 case Intrinsic::umin:
4684 case Intrinsic::smin:
4685 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4686 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4687
4688 // In the context of masks, bitreverse(Mask) == ~Mask
4689 case Intrinsic::bitreverse:
4690 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4691 default:
4692 break;
4693 }
4694 }
4695 break;
4696 }
4697 default:
4698 break;
4699 }
4700 return false;
4701}
4702
4703/// Some comparisons can be simplified.
4704/// In this case, we are looking for comparisons that look like
4705/// a check for a lossy truncation.
4706/// Folds:
4707/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4708/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4709/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4710/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4711/// Where Mask is some pattern that produces all-ones in low bits:
4712/// (-1 >> y)
4713/// ((-1 << y) >> y) <- non-canonical, has extra uses
4714/// ~(-1 << y)
4715/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4716/// The Mask can be a constant, too.
4717/// For some predicates, the operands are commutative.
4718/// For others, x can only be on a specific side.
4720 Value *Op1, const SimplifyQuery &Q,
4721 InstCombiner &IC) {
4722
4723 ICmpInst::Predicate DstPred;
4724 switch (Pred) {
4726 // x & Mask == x
4727 // x & ~Mask == 0
4728 // ~x | Mask == -1
4729 // -> x u<= Mask
4730 // x & ~Mask == ~Mask
4731 // -> ~Mask u<= x
4733 break;
4735 // x & Mask != x
4736 // x & ~Mask != 0
4737 // ~x | Mask != -1
4738 // -> x u> Mask
4739 // x & ~Mask != ~Mask
4740 // -> ~Mask u> x
4742 break;
4744 // x & Mask u< x
4745 // -> x u> Mask
4746 // x & ~Mask u< ~Mask
4747 // -> ~Mask u> x
4749 break;
4751 // x & Mask u>= x
4752 // -> x u<= Mask
4753 // x & ~Mask u>= ~Mask
4754 // -> ~Mask u<= x
4756 break;
4758 // x & Mask s< x [iff Mask s>= 0]
4759 // -> x s> Mask
4760 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4761 // -> ~Mask s> x
4763 break;
4765 // x & Mask s>= x [iff Mask s>= 0]
4766 // -> x s<= Mask
4767 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4768 // -> ~Mask s<= x
4770 break;
4771 default:
4772 // We don't support sgt,sle
4773 // ult/ugt are simplified to true/false respectively.
4774 return nullptr;
4775 }
4776
4777 Value *X, *M;
4778 // Put search code in lambda for early positive returns.
4779 auto IsLowBitMask = [&]() {
4780 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4781 X = Op1;
4782 // Look for: x & Mask pred x
4783 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4784 return !ICmpInst::isSigned(Pred) ||
4785 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4786 }
4787
4788 // Look for: x & ~Mask pred ~Mask
4789 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4790 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4791 }
4792 return false;
4793 }
4794 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4795 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4796
4797 auto Check = [&]() {
4798 // Look for: ~x | Mask == -1
4799 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4800 if (Value *NotX =
4801 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4802 X = NotX;
4803 return true;
4804 }
4805 }
4806 return false;
4807 };
4808 if (Check())
4809 return true;
4810 std::swap(X, M);
4811 return Check();
4812 }
4813 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4814 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4815 auto Check = [&]() {
4816 // Look for: x & ~Mask == 0
4817 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4818 if (Value *NotM =
4819 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4820 M = NotM;
4821 return true;
4822 }
4823 }
4824 return false;
4825 };
4826 if (Check())
4827 return true;
4828 std::swap(X, M);
4829 return Check();
4830 }
4831 return false;
4832 };
4833
4834 if (!IsLowBitMask())
4835 return nullptr;
4836
4837 return IC.Builder.CreateICmp(DstPred, X, M);
4838}
4839
4840/// Some comparisons can be simplified.
4841/// In this case, we are looking for comparisons that look like
4842/// a check for a lossy signed truncation.
4843/// Folds: (MaskedBits is a constant.)
4844/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4845/// Into:
4846/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4847/// Where KeptBits = bitwidth(%x) - MaskedBits
4848static Value *
4850 InstCombiner::BuilderTy &Builder) {
4851 CmpPredicate SrcPred;
4852 Value *X;
4853 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4854 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4855 if (!match(&I, m_c_ICmp(SrcPred,
4857 m_APInt(C1))),
4858 m_Deferred(X))))
4859 return nullptr;
4860
4861 // Potential handling of non-splats: for each element:
4862 // * if both are undef, replace with constant 0.
4863 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4864 // * if both are not undef, and are different, bailout.
4865 // * else, only one is undef, then pick the non-undef one.
4866
4867 // The shift amount must be equal.
4868 if (*C0 != *C1)
4869 return nullptr;
4870 const APInt &MaskedBits = *C0;
4871 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4872
4873 ICmpInst::Predicate DstPred;
4874 switch (SrcPred) {
4876 // ((%x << MaskedBits) a>> MaskedBits) == %x
4877 // =>
4878 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4880 break;
4882 // ((%x << MaskedBits) a>> MaskedBits) != %x
4883 // =>
4884 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4886 break;
4887 // FIXME: are more folds possible?
4888 default:
4889 return nullptr;
4890 }
4891
4892 auto *XType = X->getType();
4893 const unsigned XBitWidth = XType->getScalarSizeInBits();
4894 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4895 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4896
4897 // KeptBits = bitwidth(%x) - MaskedBits
4898 const APInt KeptBits = BitWidth - MaskedBits;
4899 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4900 // ICmpCst = (1 << KeptBits)
4901 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4902 assert(ICmpCst.isPowerOf2());
4903 // AddCst = (1 << (KeptBits-1))
4904 const APInt AddCst = ICmpCst.lshr(1);
4905 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4906
4907 // T0 = add %x, AddCst
4908 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4909 // T1 = T0 DstPred ICmpCst
4910 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4911
4912 return T1;
4913}
4914
4915// Given pattern:
4916// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4917// we should move shifts to the same hand of 'and', i.e. rewrite as
4918// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4919// We are only interested in opposite logical shifts here.
4920// One of the shifts can be truncated.
4921// If we can, we want to end up creating 'lshr' shift.
4922static Value *
4924 InstCombiner::BuilderTy &Builder) {
4925 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4926 !I.getOperand(0)->hasOneUse())
4927 return nullptr;
4928
4929 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4930
4931 // Look for an 'and' of two logical shifts, one of which may be truncated.
4932 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4933 Instruction *XShift, *MaybeTruncation, *YShift;
4934 if (!match(
4935 I.getOperand(0),
4936 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4938 m_AnyLogicalShift, m_Instruction(YShift))),
4939 m_Instruction(MaybeTruncation)))))
4940 return nullptr;
4941
4942 // We potentially looked past 'trunc', but only when matching YShift,
4943 // therefore YShift must have the widest type.
4944 Instruction *WidestShift = YShift;
4945 // Therefore XShift must have the shallowest type.
4946 // Or they both have identical types if there was no truncation.
4947 Instruction *NarrowestShift = XShift;
4948
4949 Type *WidestTy = WidestShift->getType();
4950 Type *NarrowestTy = NarrowestShift->getType();
4951 assert(NarrowestTy == I.getOperand(0)->getType() &&
4952 "We did not look past any shifts while matching XShift though.");
4953 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4954
4955 // If YShift is a 'lshr', swap the shifts around.
4956 if (match(YShift, m_LShr(m_Value(), m_Value())))
4957 std::swap(XShift, YShift);
4958
4959 // The shifts must be in opposite directions.
4960 auto XShiftOpcode = XShift->getOpcode();
4961 if (XShiftOpcode == YShift->getOpcode())
4962 return nullptr; // Do not care about same-direction shifts here.
4963
4964 Value *X, *XShAmt, *Y, *YShAmt;
4965 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4966 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4967
4968 // If one of the values being shifted is a constant, then we will end with
4969 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4970 // however, we will need to ensure that we won't increase instruction count.
4971 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4972 // At least one of the hands of the 'and' should be one-use shift.
4973 if (!match(I.getOperand(0),
4974 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4975 return nullptr;
4976 if (HadTrunc) {
4977 // Due to the 'trunc', we will need to widen X. For that either the old
4978 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4979 if (!MaybeTruncation->hasOneUse() &&
4980 !NarrowestShift->getOperand(1)->hasOneUse())
4981 return nullptr;
4982 }
4983 }
4984
4985 // We have two shift amounts from two different shifts. The types of those
4986 // shift amounts may not match. If that's the case let's bailout now.
4987 if (XShAmt->getType() != YShAmt->getType())
4988 return nullptr;
4989
4990 // As input, we have the following pattern:
4991 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4992 // We want to rewrite that as:
4993 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4994 // While we know that originally (Q+K) would not overflow
4995 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
4996 // shift amounts. so it may now overflow in smaller bitwidth.
4997 // To ensure that does not happen, we need to ensure that the total maximal
4998 // shift amount is still representable in that smaller bit width.
4999 unsigned MaximalPossibleTotalShiftAmount =
5000 (WidestTy->getScalarSizeInBits() - 1) +
5001 (NarrowestTy->getScalarSizeInBits() - 1);
5002 APInt MaximalRepresentableShiftAmount =
5004 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
5005 return nullptr;
5006
5007 // Can we fold (XShAmt+YShAmt) ?
5008 auto *NewShAmt = dyn_cast_or_null<Constant>(
5009 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
5010 /*isNUW=*/false, SQ.getWithInstruction(&I)));
5011 if (!NewShAmt)
5012 return nullptr;
5013 if (NewShAmt->getType() != WidestTy) {
5014 NewShAmt =
5015 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
5016 if (!NewShAmt)
5017 return nullptr;
5018 }
5019 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
5020
5021 // Is the new shift amount smaller than the bit width?
5022 // FIXME: could also rely on ConstantRange.
5023 if (!match(NewShAmt,
5025 APInt(WidestBitWidth, WidestBitWidth))))
5026 return nullptr;
5027
5028 // An extra legality check is needed if we had trunc-of-lshr.
5029 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
5030 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5031 WidestShift]() {
5032 // It isn't obvious whether it's worth it to analyze non-constants here.
5033 // Also, let's basically give up on non-splat cases, pessimizing vectors.
5034 // If *any* of these preconditions matches we can perform the fold.
5035 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
5036 ? NewShAmt->getSplatValue()
5037 : NewShAmt;
5038 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
5039 if (NewShAmtSplat &&
5040 (NewShAmtSplat->isNullValue() ||
5041 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
5042 return true;
5043 // We consider *min* leading zeros so a single outlier
5044 // blocks the transform as opposed to allowing it.
5045 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
5047 unsigned MinLeadZero = Known.countMinLeadingZeros();
5048 // If the value being shifted has at most lowest bit set we can fold.
5049 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5050 if (MaxActiveBits <= 1)
5051 return true;
5052 // Precondition: NewShAmt u<= countLeadingZeros(C)
5053 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5054 return true;
5055 }
5056 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5058 unsigned MinLeadZero = Known.countMinLeadingZeros();
5059 // If the value being shifted has at most lowest bit set we can fold.
5060 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5061 if (MaxActiveBits <= 1)
5062 return true;
5063 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5064 if (NewShAmtSplat) {
5065 APInt AdjNewShAmt =
5066 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5067 if (AdjNewShAmt.ule(MinLeadZero))
5068 return true;
5069 }
5070 }
5071 return false; // Can't tell if it's ok.
5072 };
5073 if (!CanFold())
5074 return nullptr;
5075 }
5076
5077 // All good, we can do this fold.
5078 X = Builder.CreateZExt(X, WidestTy);
5079 Y = Builder.CreateZExt(Y, WidestTy);
5080 // The shift is the same that was for X.
5081 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5082 ? Builder.CreateLShr(X, NewShAmt)
5083 : Builder.CreateShl(X, NewShAmt);
5084 Value *T1 = Builder.CreateAnd(T0, Y);
5085 return Builder.CreateICmp(I.getPredicate(), T1,
5086 Constant::getNullValue(WidestTy));
5087}
5088
5089/// Fold
5090/// (-1 u/ x) u< y
5091/// ((x * y) ?/ x) != y
5092/// to
5093/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5094/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5095/// will mean that we are looking for the opposite answer.
5097 CmpPredicate Pred;
5098 Value *X, *Y;
5101 bool NeedNegation;
5102 // Look for: (-1 u/ x) u</u>= y
5103 if (!I.isEquality() &&
5104 match(&I, m_c_ICmp(Pred,
5107 m_Value(Y)))) {
5108 Mul = nullptr;
5109
5110 // Are we checking that overflow does not happen, or does happen?
5111 switch (Pred) {
5113 NeedNegation = false;
5114 break; // OK
5116 NeedNegation = true;
5117 break; // OK
5118 default:
5119 return nullptr; // Wrong predicate.
5120 }
5121 } else // Look for: ((x * y) / x) !=/== y
5122 if (I.isEquality() &&
5123 match(&I, m_c_ICmp(Pred, m_Value(Y),
5126 m_Value(X)),
5128 m_Deferred(X))),
5129 m_Instruction(Div))))) {
5130 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5131 } else
5132 return nullptr;
5133
5135 // If the pattern included (x * y), we'll want to insert new instructions
5136 // right before that original multiplication so that we can replace it.
5137 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5138 if (MulHadOtherUses)
5139 Builder.SetInsertPoint(Mul);
5140
5141 Value *Call = Builder.CreateIntrinsic(
5142 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5143 : Intrinsic::smul_with_overflow,
5144 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5145
5146 // If the multiplication was used elsewhere, to ensure that we don't leave
5147 // "duplicate" instructions, replace uses of that original multiplication
5148 // with the multiplication result from the with.overflow intrinsic.
5149 if (MulHadOtherUses)
5150 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5151
5152 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5153 if (NeedNegation) // This technically increases instruction count.
5154 Res = Builder.CreateNot(Res, "mul.not.ov");
5155
5156 // If we replaced the mul, erase it. Do this after all uses of Builder,
5157 // as the mul is used as insertion point.
5158 if (MulHadOtherUses)
5160
5161 return Res;
5162}
5163
5165 InstCombiner::BuilderTy &Builder) {
5167 Value *X;
5168 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5169
5172 else if (ICmpInst::isUnsigned(Pred))
5174 // else for equality-comparisons just keep the predicate.
5175
5176 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5177 Constant::getNullValue(X->getType()), I.getName());
5178 }
5179
5180 // A value is not equal to its negation unless that value is 0 or
5181 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5184 Type *Ty = X->getType();
5185 uint32_t BitWidth = Ty->getScalarSizeInBits();
5186 Constant *MaxSignedVal =
5187 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5188 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5190 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5191 }
5192
5193 return nullptr;
5194}
5195
5197 InstCombinerImpl &IC) {
5198 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5199 // Normalize and operand as operand 0.
5200 CmpInst::Predicate Pred = I.getPredicate();
5201 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5202 std::swap(Op0, Op1);
5204 }
5205
5206 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5207 return nullptr;
5208
5209 // (icmp (X & Y) u< X --> (X & Y) != X
5210 if (Pred == ICmpInst::ICMP_ULT)
5211 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5212
5213 // (icmp (X & Y) u>= X --> (X & Y) == X
5214 if (Pred == ICmpInst::ICMP_UGE)
5215 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5216
5217 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5218 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5219 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5220 // so don't do this fold.
5221 if (!match(Op1, m_ImmConstant()))
5222 if (auto *NotOp1 =
5223 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5224 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5225 Constant::getAllOnesValue(Op1->getType()));
5226 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5227 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5228 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5229 Constant::getNullValue(Op1->getType()));
5230 }
5231
5233 return nullptr;
5234
5235 KnownBits KnownY = IC.computeKnownBits(A, &I);
5236 // (X & NegY) spred X --> (X & NegY) upred X
5237 if (KnownY.isNegative())
5238 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5239
5241 return nullptr;
5242
5243 if (KnownY.isNonNegative())
5244 // (X & PosY) s<= X --> X s>= 0
5245 // (X & PosY) s> X --> X s< 0
5247 Constant::getNullValue(Op1->getType()));
5248
5250 // (NegX & Y) s<= NegX --> Y s< 0
5251 // (NegX & Y) s> NegX --> Y s>= 0
5253 Constant::getNullValue(A->getType()));
5254
5255 return nullptr;
5256}
5257
5259 InstCombinerImpl &IC) {
5260 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5261
5262 // Normalize or operand as operand 0.
5263 CmpInst::Predicate Pred = I.getPredicate();
5264 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5265 std::swap(Op0, Op1);
5267 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5268 return nullptr;
5269 }
5270
5271 // icmp (X | Y) u<= X --> (X | Y) == X
5272 if (Pred == ICmpInst::ICMP_ULE)
5273 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5274
5275 // icmp (X | Y) u> X --> (X | Y) != X
5276 if (Pred == ICmpInst::ICMP_UGT)
5277 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5278
5279 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5280 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5281 if (Value *NotOp1 = IC.getFreelyInverted(
5282 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5283 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5284 Constant::getNullValue(Op1->getType()));
5285 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5286 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5287 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5288 Constant::getAllOnesValue(Op1->getType()));
5289 }
5290 return nullptr;
5291}
5292
5294 InstCombinerImpl &IC) {
5295 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5296 // Normalize xor operand as operand 0.
5297 CmpInst::Predicate Pred = I.getPredicate();
5298 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5299 std::swap(Op0, Op1);
5301 }
5302 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5303 return nullptr;
5304
5305 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5306 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5307 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5308 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5310 if (PredOut != Pred && isKnownNonZero(A, Q))
5311 return new ICmpInst(PredOut, Op0, Op1);
5312
5313 // These transform work when A is negative.
5314 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5315 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5316 if (match(A, m_Negative())) {
5317 CmpInst::Predicate NewPred;
5319 default:
5320 return nullptr;
5321 case ICmpInst::ICMP_SLT:
5322 case ICmpInst::ICMP_UGT:
5323 NewPred = ICmpInst::ICMP_SLT;
5324 break;
5325 case ICmpInst::ICMP_SGT:
5326 case ICmpInst::ICMP_ULT:
5327 NewPred = ICmpInst::ICMP_SGE;
5328 break;
5329 }
5330 Constant *Const = Constant::getNullValue(Op0->getType());
5331 return new ICmpInst(NewPred, Op0, Const);
5332 }
5333
5334 return nullptr;
5335}
5336
5337/// Return true if X is a multiple of C.
5338/// TODO: Handle non-power-of-2 factors.
5339static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5340 if (C.isOne())
5341 return true;
5342
5343 if (!C.isPowerOf2())
5344 return false;
5345
5346 return MaskedValueIsZero(X, C - 1, Q);
5347}
5348
5350 bool &HasNSW, bool &HasNUW) {
5352 HasNUW = BO.hasNoUnsignedWrap();
5353 HasNSW = BO.hasNoSignedWrap();
5354 return ICmpInst::isEquality(Pred) ||
5355 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5356 (CmpInst::isSigned(Pred) && HasNSW);
5357 }
5358 if (BO.getOpcode() == Instruction::Or) {
5359 // The callers only use this result for an or matched by m_AddLike, which
5360 // must be an or disjoint and is equivalent to an add nuw nsw.
5361 HasNUW = true;
5362 HasNSW = true;
5363 return true;
5364 }
5365 return false;
5366}
5367
5369 CmpInst::Predicate Pred,
5370 Value *&LHS, Value *&RHS,
5371 const SimplifyQuery &Q) {
5372 auto *BO0 = dyn_cast<BinaryOperator>(Op0);
5373 auto *BO1 = dyn_cast<BinaryOperator>(Op1);
5374 if (!BO0 || !BO1)
5375 return false;
5376
5377 bool IsEquality = ICmpInst::isEquality(Pred);
5378 bool IsSigned = ICmpInst::isSigned(Pred);
5379
5380 bool Op0HasNSW = false, Op0HasNUW = false;
5381 bool Op1HasNSW = false, Op1HasNUW = false;
5382 bool NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5383 bool NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5384
5385 Value *A, *B, *C, *D;
5386
5387 // Handle all add-like operations.
5388 if (match(BO0, m_AddLike(m_Value(A), m_Value(B))) &&
5389 match(BO1, m_AddLike(m_Value(C), m_Value(D)))) {
5390 if (!NoOp0WrapProblem || !NoOp1WrapProblem)
5391 return false;
5392
5393 if (A == C) {
5394 // (A + B) cmp (A + D) -> B cmp D
5395 LHS = B;
5396 RHS = D;
5397 return true;
5398 }
5399 if (A == D) {
5400 // (A + B) cmp (C + A) -> B cmp C
5401 LHS = B;
5402 RHS = C;
5403 return true;
5404 }
5405 if (B == C) {
5406 // (A + B) cmp (B + D) -> A cmp D
5407 LHS = A;
5408 RHS = D;
5409 return true;
5410 }
5411 if (B == D) {
5412 // (A + B) cmp (C + B) -> A cmp C
5413 LHS = A;
5414 RHS = C;
5415 return true;
5416 }
5417 return false;
5418 }
5419
5420 if (BO0->getOpcode() != BO1->getOpcode())
5421 return false;
5422
5423 A = BO0->getOperand(0);
5424 B = BO0->getOperand(1);
5425 C = BO1->getOperand(0);
5426 D = BO1->getOperand(1);
5427
5428 switch (BO0->getOpcode()) {
5429 default:
5430 break;
5431 case Instruction::Sub:
5432 if (!NoOp0WrapProblem || !NoOp1WrapProblem)
5433 return false;
5434
5435 // (A - B) cmp (C - B) -> A cmp C
5436 if (B == D) {
5437 LHS = A;
5438 RHS = C;
5439 return true;
5440 }
5441 // (A - B) cmp (A - D) -> D cmp B
5442 if (A == C) {
5443 LHS = D;
5444 RHS = B;
5445 return true;
5446 }
5447 return false;
5448
5449 case Instruction::Mul: {
5450 // Equality comparisons have additional modular-arithmetic folds and are
5451 // handled by the existing multiplication logic in foldICmpBinOp().
5452 if (IsEquality || !NoOp0WrapProblem || !NoOp1WrapProblem)
5453 return false;
5454
5455 Value *Z;
5456
5457 if (A == C) {
5458 // (A * B) cmp (A * D) -> B cmp D
5459 Z = A;
5460 LHS = B;
5461 RHS = D;
5462 } else if (A == D) {
5463 // (A * B) cmp (C * A) -> B cmp C
5464 Z = A;
5465 LHS = B;
5466 RHS = C;
5467 } else if (B == C) {
5468 // (A * B) cmp (B * D) -> A cmp D
5469 Z = B;
5470 LHS = A;
5471 RHS = D;
5472 } else if (B == D) {
5473 // (A * B) cmp (C * B) -> A cmp C
5474 Z = B;
5475 LHS = A;
5476 RHS = C;
5477 } else {
5478 return false;
5479 }
5480
5481 if (!IsSigned)
5482 return isKnownNonZero(Z, Q);
5483
5484 WithCache<const Value *> ZCache(Z);
5485 if (isKnownPositive(ZCache, Q))
5486 return true;
5487
5488 if (isKnownNegative(ZCache, Q)) {
5489 std::swap(LHS, RHS);
5490 return true;
5491 }
5492
5493 return false;
5494 }
5495 }
5496
5497 // Only apply if one of the operands has one use, consistent with
5498 // existing icmp fold criteria for common operands.
5499 if (!BO0->hasOneUse() && !BO1->hasOneUse())
5500 return false;
5501 if (B != D)
5502 return false;
5503
5504 LHS = A;
5505 RHS = C;
5506
5507 switch (BO0->getOpcode()) {
5508 default:
5509 break;
5510 case Instruction::Shl: {
5511 bool NUW = Op0HasNUW && Op1HasNUW;
5512 bool NSW = Op0HasNSW && Op1HasNSW;
5513 if (!NUW && !NSW)
5514 return false;
5515 if (!NSW && IsSigned)
5516 return false;
5517
5518 return true;
5519 }
5520 case Instruction::LShr:
5521 return !IsSigned && BO0->isExact() && BO1->isExact();
5522 case Instruction::AShr:
5523 return BO0->isExact() && BO1->isExact();
5524 case Instruction::UDiv:
5525 return !IsSigned && BO0->isExact() && BO1->isExact();
5526 case Instruction::SDiv:
5527 if (!BO0->isExact() || !BO1->isExact())
5528 return false;
5529
5530 return IsEquality || match(B, m_NonNegative());
5531 }
5532 return false;
5533}
5534
5535/// Try to fold icmp (binop), X or icmp X, (binop).
5536/// TODO: A large part of this logic is duplicated in InstSimplify's
5537/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5538/// duplication.
5540 const SimplifyQuery &SQ) {
5541 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5542 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5543
5544 // Special logic for binary operators.
5547 if (!BO0 && !BO1)
5548 return nullptr;
5549
5550 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5551 return NewICmp;
5552
5553 const CmpInst::Predicate Pred = I.getPredicate();
5554
5555 // (X urem Y) == X --> X u< Y
5556 // (X urem Y) != X --> X u>= Y
5557 Value *Dividend, *Divisor;
5558 if (I.isEquality() &&
5559 match(&I, m_c_ICmp(m_URem(m_Value(Dividend), m_Value(Divisor)),
5560 m_Deferred(Dividend)))) {
5561 CmpInst::Predicate NewPred =
5563 return new ICmpInst(NewPred, Dividend, Divisor);
5564 }
5565
5566 Value *X;
5567
5568 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5569 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5570 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5571 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5572 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5573 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5574 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5575 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5576 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5577
5578 {
5579 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5580 Constant *C;
5581 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5582 m_ImmConstant(C)))) &&
5583 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5585 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5586 }
5587 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5588 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5589 m_ImmConstant(C)))) &&
5590 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5592 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5593 }
5594 }
5595
5596 // (icmp eq/ne (X, -P2), INT_MIN)
5597 // -> (icmp slt/sge X, INT_MIN + P2)
5598 if (ICmpInst::isEquality(Pred) && BO0 &&
5599 match(I.getOperand(1), m_SignMask()) &&
5601 // Will Constant fold.
5602 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5603 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5605 BO0->getOperand(0), NewC);
5606 }
5607
5608 {
5609 // Similar to above: an unsigned overflow comparison may use offset + mask:
5610 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5611 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5612 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5613 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5614 BinaryOperator *BO;
5615 const APInt *C;
5616 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5617 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5619 CmpInst::Predicate NewPred =
5621 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5622 return new ICmpInst(NewPred, Op1, Zero);
5623 }
5624
5625 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5626 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5628 CmpInst::Predicate NewPred =
5630 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5631 return new ICmpInst(NewPred, Op0, Zero);
5632 }
5633 }
5634
5635 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5636 bool Op0HasNUW = false, Op1HasNUW = false;
5637 bool Op0HasNSW = false, Op1HasNSW = false;
5638 // Analyze the case when either Op0 or Op1 is an add instruction.
5639 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5640 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5641
5642 if (BO0) {
5643 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5644 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5645 }
5646 if (BO1) {
5647 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5648 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5649 }
5650
5651 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5652 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5653 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5654 return new ICmpInst(Pred, A == Op1 ? B : A,
5655 Constant::getNullValue(Op1->getType()));
5656
5657 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5658 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5659 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5660 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5661 C == Op0 ? D : C);
5662
5663 // Fold comparisons of binops with a removable common operand.
5664 Value *LHS;
5665 Value *RHS;
5666 if (matchCommonBinOpOperands(Op0, Op1, Pred, LHS, RHS, Q))
5667 return new ICmpInst(Pred, LHS, RHS);
5668
5669 if (ICmpInst::isRelational(Pred)) {
5670 // Return if both X and Y is divisible by Z/-Z.
5671 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5672 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5673 bool IsNegative) -> bool {
5674 const APInt *OffsetC;
5675 if (!match(Z, m_APInt(OffsetC)))
5676 return false;
5677
5678 // Fast path for Z == 1/-1.
5679 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5680 return true;
5681
5682 APInt C = *OffsetC;
5683 if (IsNegative)
5684 C.negate();
5685 // Note: -INT_MIN is also negative.
5686 if (!C.isStrictlyPositive())
5687 return false;
5688
5689 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5690 };
5691
5692 // The subtraction-related identities (A -nuw B) shown below require that
5693 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5694 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5695 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5696 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5697 // requires proving A <u B, for which the nowrap precondition can never be
5698 // satisfied. These are therefore skipped.
5699 //
5700 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5701 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5702 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5703 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5704
5705 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5706 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5707 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5708 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5709 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5710 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5711 bool IsNegative = ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred);
5712 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5713 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5714 ShareCommonDivisor(A, Op1, B, IsNegative))
5716 Op1);
5717
5718 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5719 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5720 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5721 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5722 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5723 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5724 if (C && NoOp1WrapProblem &&
5725 ShareCommonDivisor(Op0, C, D,
5726 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5728 C);
5729 }
5730
5731 // if C1 has greater magnitude than C2:
5732 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5733 // s.t. C3 = C1 - C2
5734 //
5735 // if C2 has greater magnitude than C1:
5736 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5737 // s.t. C3 = C2 - C1
5738 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5739 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5740 const APInt *AP1, *AP2;
5741 // TODO: Support non-uniform vectors.
5742 // TODO: Allow poison passthrough if B or D's element is poison.
5743 if (match(B, m_APIntAllowPoison(AP1)) &&
5744 match(D, m_APIntAllowPoison(AP2)) &&
5745 AP1->isNegative() == AP2->isNegative()) {
5746 APInt AP1Abs = AP1->abs();
5747 APInt AP2Abs = AP2->abs();
5748 if (AP1Abs.uge(AP2Abs)) {
5749 APInt Diff = *AP1 - *AP2;
5750 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5751 Value *NewAdd = Builder.CreateAdd(
5752 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5753 return new ICmpInst(Pred, NewAdd, C);
5754 } else {
5755 APInt Diff = *AP2 - *AP1;
5756 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5757 Value *NewAdd = Builder.CreateAdd(
5758 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5759 return new ICmpInst(Pred, A, NewAdd);
5760 }
5761 }
5762 Constant *Cst1, *Cst2;
5763 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5764 ICmpInst::isEquality(Pred)) {
5765 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5766 Value *NewAdd = Builder.CreateAdd(C, Diff);
5767 return new ICmpInst(Pred, A, NewAdd);
5768 }
5769 }
5770
5771 // Analyze the case when either Op0 or Op1 is a sub instruction.
5772 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5773 A = nullptr;
5774 B = nullptr;
5775 C = nullptr;
5776 D = nullptr;
5777 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5778 A = BO0->getOperand(0);
5779 B = BO0->getOperand(1);
5780 }
5781 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5782 C = BO1->getOperand(0);
5783 D = BO1->getOperand(1);
5784 }
5785
5786 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5787 if (A == Op1 && NoOp0WrapProblem)
5788 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5789 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5790 if (C == Op0 && NoOp1WrapProblem)
5791 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5792
5793 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5794 // (A - B) u>/u<= A --> B u>/u<= A
5795 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5796 return new ICmpInst(Pred, B, A);
5797 // C u</u>= (C - D) --> C u</u>= D
5798 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5799 return new ICmpInst(Pred, C, D);
5800 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5801 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5802 isKnownNonZero(B, Q))
5804 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5805 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5806 isKnownNonZero(D, Q))
5808
5809 // icmp (0-X) < cst --> x > -cst
5810 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5811 Value *X;
5812 if (match(BO0, m_Neg(m_Value(X))))
5813 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5814 if (RHSC->isNotMinSignedValue())
5815 return new ICmpInst(I.getSwappedPredicate(), X,
5816 ConstantExpr::getNeg(RHSC));
5817 }
5818
5819 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5820 return R;
5821 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5822 return R;
5823
5824 {
5825 // Try to remove shared multiplier from comparison:
5826 // X * Z pred Y * Z
5827 Value *X, *Y, *Z;
5828 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5829 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5830 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5831 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5832 if (ICmpInst::isSigned(Pred)) {
5833 if (Op0HasNSW && Op1HasNSW) {
5835 SQ.getWithInstruction(&I));
5836 if (LessThan && match(LessThan, m_One()))
5837 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5838 Constant::getNullValue(Z->getType()));
5839 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5840 SQ.getWithInstruction(&I));
5841 if (GreaterThan && match(GreaterThan, m_One()))
5842 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5843 }
5844 } else if (ICmpInst::isEquality(Pred)) {
5845 // Handle equality folds beyond direct multiplier cancellation.
5846 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5847 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5848 isKnownNonEqual(X, Y, SQ))
5849 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5850
5851 KnownBits ZKnown = computeKnownBits(Z, &I);
5852 // if Z % 2 != 0
5853 // X * Z eq/ne Y * Z -> X eq/ne Y
5854 if (ZKnown.countMaxTrailingZeros() == 0)
5855 return new ICmpInst(Pred, X, Y);
5856 bool NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5857 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5858 // X * Z eq/ne Y * Z -> X eq/ne Y
5859 if (NonZero && Op0HasNSW && Op1HasNSW)
5860 return new ICmpInst(Pred, X, Y);
5861
5862 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5863 // X * Z eq/ne Y * Z -> X eq/ne Y
5864 if (NonZero && Op0HasNUW && Op1HasNUW)
5865 return new ICmpInst(Pred, X, Y);
5866 }
5867 }
5868 }
5869
5870 BinaryOperator *SRem = nullptr;
5871 // icmp (srem X, Y), Y
5872 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5873 SRem = BO0;
5874 // icmp Y, (srem X, Y)
5875 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5876 Op0 == BO1->getOperand(1))
5877 SRem = BO1;
5878 if (SRem) {
5879 // We don't check hasOneUse to avoid increasing register pressure because
5880 // the value we use is the same value this instruction was already using.
5881 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5882 default:
5883 break;
5884 case ICmpInst::ICMP_EQ:
5885 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5886 case ICmpInst::ICMP_NE:
5887 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5888 case ICmpInst::ICMP_SGT:
5889 case ICmpInst::ICMP_SGE:
5890 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5892 case ICmpInst::ICMP_SLT:
5893 case ICmpInst::ICMP_SLE:
5894 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5896 }
5897 }
5898
5899 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5900 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5901 BO0->getOperand(1) == BO1->getOperand(1)) {
5902 switch (BO0->getOpcode()) {
5903 default:
5904 break;
5905 case Instruction::Add:
5906 case Instruction::Sub:
5907 case Instruction::Xor: {
5908 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5909 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5910
5911 const APInt *C;
5912 if (match(BO0->getOperand(1), m_APInt(C))) {
5913 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5914 if (C->isSignMask()) {
5915 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5916 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5917 }
5918
5919 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5920 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5921 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5922 NewPred = I.getSwappedPredicate(NewPred);
5923 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5924 }
5925 }
5926 break;
5927 }
5928 case Instruction::Mul: {
5929 if (!I.isEquality())
5930 break;
5931
5932 const APInt *C;
5933 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5934 !C->isOne()) {
5935 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5936 // Mask = -1 >> count-trailing-zeros(C).
5937 if (unsigned TZs = C->countr_zero()) {
5938 Constant *Mask = ConstantInt::get(
5939 BO0->getType(),
5940 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5941 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5942 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5943 return new ICmpInst(Pred, And1, And2);
5944 }
5945 }
5946 break;
5947 }
5948 }
5949 }
5950
5951 if (BO0) {
5952 // Transform A & (L - 1) `ult` L --> L != 0
5953 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5954 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5955
5956 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5957 auto *Zero = Constant::getNullValue(BO0->getType());
5958 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5959 }
5960 }
5961
5962 // For unsigned predicates / eq / ne:
5963 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5964 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5965 if (!ICmpInst::isSigned(Pred)) {
5966 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5967 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5968 Constant::getNullValue(Op1->getType()));
5969 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5970 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5971 Constant::getNullValue(Op0->getType()), Op0);
5972 }
5973
5975 return replaceInstUsesWith(I, V);
5976
5977 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5978 return R;
5979
5981 return replaceInstUsesWith(I, V);
5982
5984 return replaceInstUsesWith(I, V);
5985
5986 return nullptr;
5987}
5988
5989/// Fold icmp Pred min|max(X, Y), Z.
5992 Value *Z, CmpPredicate Pred) {
5993 Value *X = MinMax->getLHS();
5994 Value *Y = MinMax->getRHS();
5995 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5996 return nullptr;
5997 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5998 // Revert the transform signed pred -> unsigned pred
5999 // TODO: We can flip the signedness of predicate if both operands of icmp
6000 // are negative.
6001 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
6002 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
6004 } else
6005 return nullptr;
6006 }
6007 SimplifyQuery Q = SQ.getWithInstruction(&I);
6008 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
6009 if (!Val)
6010 return std::nullopt;
6011 if (match(Val, m_One()))
6012 return true;
6013 if (match(Val, m_Zero()))
6014 return false;
6015 return std::nullopt;
6016 };
6017 // Remove samesign here since it is illegal to keep it when we speculatively
6018 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
6019 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
6020 // -46, -32)`. `X` is allowed to be non-negative here.
6021 Pred = Pred.dropSameSign();
6022 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
6023 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
6024 if (!CmpXZ.has_value() && !CmpYZ.has_value())
6025 return nullptr;
6026 if (!CmpXZ.has_value()) {
6027 std::swap(X, Y);
6028 std::swap(CmpXZ, CmpYZ);
6029 }
6030
6031 auto FoldIntoCmpYZ = [&]() -> Instruction * {
6032 if (CmpYZ.has_value())
6033 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
6034 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
6035 };
6036
6037 switch (Pred) {
6038 case ICmpInst::ICMP_EQ:
6039 case ICmpInst::ICMP_NE: {
6040 // If X == Z:
6041 // Expr Result
6042 // min(X, Y) == Z X <= Y
6043 // max(X, Y) == Z X >= Y
6044 // min(X, Y) != Z X > Y
6045 // max(X, Y) != Z X < Y
6046 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
6047 ICmpInst::Predicate NewPred =
6048 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
6049 if (Pred == ICmpInst::ICMP_NE)
6050 NewPred = ICmpInst::getInversePredicate(NewPred);
6051 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
6052 }
6053 // Otherwise (X != Z):
6054 ICmpInst::Predicate NewPred = MinMax->getPredicate();
6055 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
6056 if (!MinMaxCmpXZ.has_value()) {
6057 std::swap(X, Y);
6058 std::swap(CmpXZ, CmpYZ);
6059 // Re-check pre-condition X != Z
6060 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
6061 break;
6062 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
6063 }
6064 if (!MinMaxCmpXZ.has_value())
6065 break;
6066 if (*MinMaxCmpXZ) {
6067 // Expr Fact Result
6068 // min(X, Y) == Z X < Z false
6069 // max(X, Y) == Z X > Z false
6070 // min(X, Y) != Z X < Z true
6071 // max(X, Y) != Z X > Z true
6072 return replaceInstUsesWith(
6073 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
6074 } else {
6075 // Expr Fact Result
6076 // min(X, Y) == Z X > Z Y == Z
6077 // max(X, Y) == Z X < Z Y == Z
6078 // min(X, Y) != Z X > Z Y != Z
6079 // max(X, Y) != Z X < Z Y != Z
6080 return FoldIntoCmpYZ();
6081 }
6082 break;
6083 }
6084 case ICmpInst::ICMP_SLT:
6085 case ICmpInst::ICMP_ULT:
6086 case ICmpInst::ICMP_SLE:
6087 case ICmpInst::ICMP_ULE:
6088 case ICmpInst::ICMP_SGT:
6089 case ICmpInst::ICMP_UGT:
6090 case ICmpInst::ICMP_SGE:
6091 case ICmpInst::ICMP_UGE: {
6092 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
6093 if (*CmpXZ) {
6094 if (IsSame) {
6095 // Expr Fact Result
6096 // min(X, Y) < Z X < Z true
6097 // min(X, Y) <= Z X <= Z true
6098 // max(X, Y) > Z X > Z true
6099 // max(X, Y) >= Z X >= Z true
6100 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6101 } else {
6102 // Expr Fact Result
6103 // max(X, Y) < Z X < Z Y < Z
6104 // max(X, Y) <= Z X <= Z Y <= Z
6105 // min(X, Y) > Z X > Z Y > Z
6106 // min(X, Y) >= Z X >= Z Y >= Z
6107 return FoldIntoCmpYZ();
6108 }
6109 } else {
6110 if (IsSame) {
6111 // Expr Fact Result
6112 // min(X, Y) < Z X >= Z Y < Z
6113 // min(X, Y) <= Z X > Z Y <= Z
6114 // max(X, Y) > Z X <= Z Y > Z
6115 // max(X, Y) >= Z X < Z Y >= Z
6116 return FoldIntoCmpYZ();
6117 } else {
6118 // Expr Fact Result
6119 // max(X, Y) < Z X >= Z false
6120 // max(X, Y) <= Z X > Z false
6121 // min(X, Y) > Z X <= Z false
6122 // min(X, Y) >= Z X < Z false
6123 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6124 }
6125 }
6126 break;
6127 }
6128 default:
6129 break;
6130 }
6131
6132 return nullptr;
6133}
6134
6135/// Match and fold patterns like:
6136/// icmp eq/ne X, min(max(X, Lo), Hi)
6137/// which represents a range check and can be represented as a ConstantRange.
6138///
6139/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
6140/// (X - Lo) u< (Hi + 1 - Lo)
6141/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
6142/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
6144 MinMaxIntrinsic *Min) {
6145 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
6146 return nullptr;
6147
6148 const APInt *Lo = nullptr, *Hi = nullptr;
6149 if (Min->isSigned()) {
6150 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
6151 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
6152 return nullptr;
6153 } else {
6154 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
6155 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
6156 return nullptr;
6157 }
6158
6161 APInt C, Offset;
6162 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6163 CR.getEquivalentICmp(Pred, C, Offset);
6164 else
6165 CR.inverse().getEquivalentICmp(Pred, C, Offset);
6166
6167 if (!Offset.isZero())
6168 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
6169
6170 return replaceInstUsesWith(
6171 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
6172}
6173
6174// Canonicalize checking for a power-of-2-or-zero value:
6176 InstCombiner::BuilderTy &Builder) {
6177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6178 const CmpInst::Predicate Pred = I.getPredicate();
6179 Value *A = nullptr;
6180 bool CheckIs;
6181 if (I.isEquality()) {
6182 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6183 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6184 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6185 m_Deferred(A)))) ||
6186 !match(Op1, m_ZeroInt()))
6187 A = nullptr;
6188
6189 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6190 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6191 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6192 A = Op1;
6193 else if (match(Op1,
6195 A = Op0;
6196
6197 CheckIs = Pred == ICmpInst::ICMP_EQ;
6198 } else if (ICmpInst::isUnsigned(Pred)) {
6199 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6200 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6201
6204 m_Specific(Op1))))) {
6205 A = Op1;
6206 CheckIs = Pred == ICmpInst::ICMP_UGE;
6207 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6209 m_Specific(Op0))))) {
6210 A = Op0;
6211 CheckIs = Pred == ICmpInst::ICMP_ULE;
6212 }
6213 }
6214
6215 if (A) {
6216 Type *Ty = A->getType();
6217 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6218 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6219 ConstantInt::get(Ty, 2))
6220 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6221 ConstantInt::get(Ty, 1));
6222 }
6223
6224 return nullptr;
6225}
6226
6227/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6228using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6230 bool AllowRecursion) {
6232 if (!Inst || !Inst->hasOneUse())
6233 return;
6234
6235 switch (Inst->getOpcode()) {
6236 case Instruction::Add:
6237 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6238 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6239 break;
6240 case Instruction::Sub:
6241 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6242 break;
6243 case Instruction::Xor:
6244 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6245 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6246 break;
6247 case Instruction::Shl:
6248 if (Inst->hasNoSignedWrap())
6249 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6250 if (Inst->hasNoUnsignedWrap())
6251 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6252 break;
6253 case Instruction::Select:
6254 if (AllowRecursion) {
6255 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6256 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6257 }
6258 break;
6259 default:
6260 break;
6261 }
6262}
6263
6265
6270
6272 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6273 }
6275 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6276 }
6277 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6279 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6280 }
6281 bool isValid() const { return Kind != OffsetKind::Invalid; }
6283 switch (Kind) {
6285 llvm_unreachable("Invalid offset result");
6286 case OffsetKind::Value:
6287 return V0;
6288 case OffsetKind::Select:
6289 return Builder.CreateSelect(V0, V1, V2, "", MDFrom);
6290 }
6291 llvm_unreachable("Unknown OffsetKind enum");
6292 }
6293};
6294
6295/// Offset both sides of an equality icmp to see if we can save some
6296/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6297/// Note: This operation should not introduce poison.
6299 InstCombiner::BuilderTy &Builder,
6300 const SimplifyQuery &SQ) {
6301 assert(I.isEquality() && "Expected an equality icmp");
6302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6303 if (!Op0->getType()->isIntOrIntVectorTy())
6304 return nullptr;
6305
6306 SmallVector<OffsetOp, 4> OffsetOps;
6307 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6308 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6309
6310 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6311 switch (BinOpc) {
6312 // V = shl nsw X, RHS => X = ashr V, RHS
6313 case Instruction::AShr: {
6314 const APInt *CV, *CRHS;
6315 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6316 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6318 return nullptr;
6319 break;
6320 }
6321 // V = shl nuw X, RHS => X = lshr V, RHS
6322 case Instruction::LShr: {
6323 const APInt *CV, *CRHS;
6324 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6325 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6327 return nullptr;
6328 break;
6329 }
6330 default:
6331 break;
6332 }
6333
6334 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6335 if (!Simplified)
6336 return nullptr;
6337 // Reject constant expressions as they don't simplify things.
6338 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6339 return nullptr;
6340 // Check if the transformation introduces poison.
6341 return impliesPoison(RHS, V) ? Simplified : nullptr;
6342 };
6343
6344 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6345 Value *RHS) -> OffsetResult {
6346 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6347 if (!Sel->hasOneUse())
6348 return OffsetResult::invalid();
6349 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6350 if (!TrueVal)
6351 return OffsetResult::invalid();
6352 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6353 if (!FalseVal)
6354 return OffsetResult::invalid();
6355 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6356 }
6357 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6358 return OffsetResult::value(Simplified);
6359 return OffsetResult::invalid();
6360 };
6361
6362 for (auto [BinOp, RHS] : OffsetOps) {
6363 auto BinOpc = static_cast<unsigned>(BinOp);
6364
6365 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6366 if (!Op0Result.isValid())
6367 continue;
6368 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6369 if (!Op1Result.isValid())
6370 continue;
6371
6372 Value *NewLHS = Op0Result.materialize(Builder);
6373 Value *NewRHS = Op1Result.materialize(Builder);
6374 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6375 }
6376
6377 return nullptr;
6378}
6379
6381 if (!I.isEquality())
6382 return nullptr;
6383
6384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6385 const CmpInst::Predicate Pred = I.getPredicate();
6386 Value *A, *B, *C, *D;
6387 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6388 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6389 Value *OtherVal = A == Op1 ? B : A;
6390 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6391 }
6392
6393 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6394 // A^c1 == C^c2 --> A == C^(c1^c2)
6395 ConstantInt *C1, *C2;
6396 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6397 Op1->hasOneUse()) {
6398 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6399 Value *Xor = Builder.CreateXor(C, NC);
6400 return new ICmpInst(Pred, A, Xor);
6401 }
6402
6403 // A^B == A^D -> B == D
6404 if (A == C)
6405 return new ICmpInst(Pred, B, D);
6406 if (A == D)
6407 return new ICmpInst(Pred, B, C);
6408 if (B == C)
6409 return new ICmpInst(Pred, A, D);
6410 if (B == D)
6411 return new ICmpInst(Pred, A, C);
6412 }
6413 }
6414
6415 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6416 // A == (A^B) -> B == 0
6417 Value *OtherVal = A == Op0 ? B : A;
6418 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6419 }
6420
6421 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6422 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6423 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6424 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6425
6426 if (A == C) {
6427 X = B;
6428 Y = D;
6429 Z = A;
6430 } else if (A == D) {
6431 X = B;
6432 Y = C;
6433 Z = A;
6434 } else if (B == C) {
6435 X = A;
6436 Y = D;
6437 Z = B;
6438 } else if (B == D) {
6439 X = A;
6440 Y = C;
6441 Z = B;
6442 }
6443
6444 if (X) {
6445 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6446 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6447 // instructions.
6448 const APInt *C0, *C1;
6449 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6450 (*C0 ^ *C1).isNegatedPowerOf2();
6451
6452 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6453 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6454 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6455 int UseCnt =
6456 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6457 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6458 if (XorIsNegP2 || UseCnt >= 2) {
6459 // Build (X^Y) & Z
6460 Op1 = Builder.CreateXor(X, Y);
6461 Op1 = Builder.CreateAnd(Op1, Z);
6462 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6463 }
6464 }
6465 }
6466
6467 {
6468 // Similar to above, but specialized for constant because invert is needed:
6469 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6470 Value *X, *Y;
6471 Constant *C;
6472 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6473 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6474 Value *Xor = Builder.CreateXor(X, Y);
6475 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6476 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6477 }
6478 }
6479
6480 if (match(Op1, m_ZExt(m_Value(A))) &&
6481 (Op0->hasOneUse() || Op1->hasOneUse())) {
6482 // (B & (Pow2C-1)) == zext A --> A == trunc B
6483 // (B & (Pow2C-1)) != zext A --> A != trunc B
6484 const APInt *MaskC;
6485 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6486 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6487 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6488 }
6489
6490 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6491 // For lshr and ashr pairs.
6492 const APInt *AP1, *AP2;
6493 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6494 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6495 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6496 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6497 if (*AP1 != *AP2)
6498 return nullptr;
6499 unsigned TypeBits = AP1->getBitWidth();
6500 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6501 if (ShAmt < TypeBits && ShAmt != 0) {
6502 ICmpInst::Predicate NewPred =
6504 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6505 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6506 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6507 }
6508 }
6509
6510 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6511 ConstantInt *Cst1;
6512 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6513 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6514 unsigned TypeBits = Cst1->getBitWidth();
6515 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6516 if (ShAmt < TypeBits && ShAmt != 0) {
6517 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6518 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6519 Value *And =
6520 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6521 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6522 }
6523 }
6524
6525 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6526 // "icmp (and X, mask), cst"
6527 uint64_t ShAmt = 0;
6528 if (Op0->hasOneUse() &&
6529 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6530 match(Op1, m_ConstantInt(Cst1)) &&
6531 // Only do this when A has multiple uses. This is most important to do
6532 // when it exposes other optimizations.
6533 !A->hasOneUse()) {
6534 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6535
6536 if (ShAmt < ASize) {
6537 APInt MaskV =
6539 MaskV <<= ShAmt;
6540
6541 APInt CmpV = Cst1->getValue().zext(ASize);
6542 CmpV <<= ShAmt;
6543
6544 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6545 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6546 }
6547 }
6548
6550 return ICmp;
6551
6552 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6553 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6554 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6555 // few steps of instcombine.
6556 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6557 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6559 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6560 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6562 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6563 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6565 Add, ConstantInt::get(A->getType(), C.shl(1)));
6566 }
6567
6568 // Canonicalize:
6569 // Assume B_Pow2 != 0
6570 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6571 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6572 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6573 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6574 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6576
6577 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6578 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6579 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6580 ConstantInt::getNullValue(Op1->getType()));
6581
6582 // Canonicalize:
6583 // icmp eq/ne X, OneUse(rotate-right(X))
6584 // -> icmp eq/ne X, rotate-left(X)
6585 // We generally try to convert rotate-right -> rotate-left, this just
6586 // canonicalizes another case.
6587 if (match(&I, m_c_ICmp(m_Value(A),
6589 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6590 return new ICmpInst(
6591 Pred, A,
6592 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6593
6594 // Canonicalize:
6595 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6596 Constant *Cst;
6599 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6600
6601 {
6602 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6603 auto m_Matcher =
6606 m_Sub(m_Value(B), m_Deferred(A)));
6607 std::optional<bool> IsZero = std::nullopt;
6608 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6609 m_Deferred(A))))
6610 IsZero = false;
6611 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6612 else if (match(&I,
6613 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6614 IsZero = true;
6615
6616 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6617 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6618 // -> (icmp eq/ne (and X, P2), 0)
6619 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6620 // -> (icmp eq/ne (and X, P2), P2)
6621 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6622 *IsZero ? A
6623 : ConstantInt::getNullValue(A->getType()));
6624 }
6625
6626 if (auto *Res = foldICmpEqualityWithOffset(
6627 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6628 return Res;
6629
6630 return nullptr;
6631}
6632
6634 ICmpInst::Predicate Pred = ICmp.getPredicate();
6635 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6636
6637 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6638 // The trunc masks high bits while the compare may effectively mask low bits.
6639 Value *X;
6640 const APInt *C;
6641 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6642 return nullptr;
6643
6644 // This matches patterns corresponding to tests of the signbit as well as:
6645 // (trunc X) pred C2 --> (X & Mask) == C
6646 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6647 /*AllowNonZeroC=*/true)) {
6648 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6649 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6650 return new ICmpInst(Res->Pred, And, C);
6651 }
6652
6653 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6654 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6655 if (II->getIntrinsicID() == Intrinsic::cttz ||
6656 II->getIntrinsicID() == Intrinsic::ctlz) {
6657 unsigned MaxRet = SrcBits;
6658 // If the "is_zero_poison" argument is set, then we know at least
6659 // one bit is set in the input, so the result is always at least one
6660 // less than the full bitwidth of that input.
6661 if (match(II->getArgOperand(1), m_One()))
6662 MaxRet--;
6663
6664 // Make sure the destination is wide enough to hold the largest output of
6665 // the intrinsic.
6666 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6667 if (Instruction *I =
6668 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6669 return I;
6670 }
6671 }
6672
6673 return nullptr;
6674}
6675
6677 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6678 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6679 Value *X;
6680 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6681 return nullptr;
6682
6683 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6684 bool IsSignedCmp = ICmp.isSigned();
6685
6686 // icmp Pred (ext X), (ext Y)
6687 Value *Y;
6688 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6689 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6690 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6691
6692 if (IsZext0 != IsZext1) {
6693 // If X and Y and both i1
6694 // (icmp eq/ne (zext X) (sext Y))
6695 // eq -> (icmp eq (or X, Y), 0)
6696 // ne -> (icmp ne (or X, Y), 0)
6697 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6698 Y->getType()->isIntOrIntVectorTy(1))
6699 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6700 Constant::getNullValue(X->getType()));
6701
6702 // If we have mismatched casts and zext has the nneg flag, we can
6703 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6704
6705 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6706 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6707
6708 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6709 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6710
6711 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6712 IsSignedExt = true;
6713 else
6714 return nullptr;
6715 }
6716
6717 // Not an extension from the same type?
6718 Type *XTy = X->getType(), *YTy = Y->getType();
6719 if (XTy != YTy) {
6720 // One of the casts must have one use because we are creating a new cast.
6721 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6722 return nullptr;
6723 // Extend the narrower operand to the type of the wider operand.
6724 CastInst::CastOps CastOpcode =
6725 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6726 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6727 X = Builder.CreateCast(CastOpcode, X, YTy);
6728 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6729 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6730 else
6731 return nullptr;
6732 }
6733
6734 // (zext X) == (zext Y) --> X == Y
6735 // (sext X) == (sext Y) --> X == Y
6736 if (ICmp.isEquality())
6737 return new ICmpInst(ICmp.getPredicate(), X, Y);
6738
6739 // A signed comparison of sign extended values simplifies into a
6740 // signed comparison.
6741 if (IsSignedCmp && IsSignedExt)
6742 return new ICmpInst(ICmp.getPredicate(), X, Y);
6743
6744 // The other three cases all fold into an unsigned comparison.
6745 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6746 }
6747
6748 // Below here, we are only folding a compare with constant.
6749 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6750 if (!C)
6751 return nullptr;
6752
6753 // If a lossless truncate is possible...
6754 Type *SrcTy = CastOp0->getSrcTy();
6755 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6756 if (Res) {
6757 if (ICmp.isEquality())
6758 return new ICmpInst(ICmp.getPredicate(), X, Res);
6759
6760 // A signed comparison of sign extended values simplifies into a
6761 // signed comparison.
6762 if (IsSignedExt && IsSignedCmp)
6763 return new ICmpInst(ICmp.getPredicate(), X, Res);
6764
6765 // The other three cases all fold into an unsigned comparison.
6766 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6767 }
6768
6769 // The re-extended constant changed, partly changed (in the case of a vector),
6770 // or could not be determined to be equal (in the case of a constant
6771 // expression), so the constant cannot be represented in the shorter type.
6772 // All the cases that fold to true or false will have already been handled
6773 // by simplifyICmpInst, so only deal with the tricky case.
6774 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6775 return nullptr;
6776
6777 // Is source op positive?
6778 // icmp ult (sext X), C --> icmp sgt X, -1
6779 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6781
6782 // Is source op negative?
6783 // icmp ugt (sext X), C --> icmp slt X, 0
6784 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6786}
6787
6788/// Handle icmp (cast x), (cast or constant).
6790 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6791 // icmp compares only pointer's value.
6792 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6793 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6794 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6795 if (SimplifiedOp0 || SimplifiedOp1)
6796 return new ICmpInst(ICmp.getPredicate(),
6797 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6798 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6799
6800 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6801 Value *Op1 = ICmp.getOperand(1);
6802 if (!CastOp0)
6803 return nullptr;
6804 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6805 return nullptr;
6806
6807 Value *Op0Src = CastOp0->getOperand(0);
6808 Type *SrcTy = CastOp0->getSrcTy();
6809 Type *DestTy = CastOp0->getDestTy();
6810
6811 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6812 // integer type is the same size as the pointer type.
6813 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6814 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6815 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6816 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6817 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6818 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6819 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6820 };
6821 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6822 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6823 Value *NewOp1 = nullptr;
6824 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6825 NewOp1 = PtrToIntOp1->getOperand(0);
6826 HasPtrToInt = true;
6827 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6828 NewOp1 = PtrToAddrOp1->getOperand(0);
6829 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6830 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6831 }
6832
6833 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6834 // check PtrWidth.
6835 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6836 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6837 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6838 }
6839
6840 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6841 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6842 CompatibleSizes(DestTy, SrcTy)) {
6843 Value *NewOp1 = nullptr;
6844 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6845 Value *IntSrc = IntToPtrOp1->getOperand(0);
6846 if (IntSrc->getType() == Op0Src->getType())
6847 NewOp1 = IntToPtrOp1->getOperand(0);
6848 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6849 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6850 }
6851
6852 if (NewOp1)
6853 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6854 }
6855
6856 if (Instruction *R = foldICmpWithTrunc(ICmp))
6857 return R;
6858
6859 return foldICmpWithZextOrSext(ICmp);
6860}
6861
6863 bool IsSigned) {
6864 switch (BinaryOp) {
6865 default:
6866 llvm_unreachable("Unsupported binary op");
6867 case Instruction::Add:
6868 case Instruction::Sub:
6869 return match(RHS, m_Zero());
6870 case Instruction::Mul:
6871 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6872 match(RHS, m_One());
6873 }
6874}
6875
6878 bool IsSigned, Value *LHS, Value *RHS,
6879 Instruction *CtxI) const {
6880 switch (BinaryOp) {
6881 default:
6882 llvm_unreachable("Unsupported binary op");
6883 case Instruction::Add:
6884 if (IsSigned)
6885 return computeOverflowForSignedAdd(LHS, RHS, CtxI);
6886 else
6887 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI);
6888 case Instruction::Sub:
6889 if (IsSigned)
6890 return computeOverflowForSignedSub(LHS, RHS, CtxI);
6891 else
6892 return computeOverflowForUnsignedSub(LHS, RHS, CtxI);
6893 case Instruction::Mul:
6894 if (IsSigned)
6895 return computeOverflowForSignedMul(LHS, RHS, CtxI);
6896 else
6897 return computeOverflowForUnsignedMul(LHS, RHS, CtxI);
6898 }
6899}
6900
6901bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6902 bool IsSigned, Value *LHS,
6903 Value *RHS, Instruction &OrigI,
6904 Value *&Result,
6905 Constant *&Overflow) {
6906 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6907 std::swap(LHS, RHS);
6908
6909 // If the overflow check was an add followed by a compare, the insertion point
6910 // may be pointing to the compare. We want to insert the new instructions
6911 // before the add in case there are uses of the add between the add and the
6912 // compare.
6913 Builder.SetInsertPoint(&OrigI);
6914
6915 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6916 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6917 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6918
6919 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6920 Result = LHS;
6921 Overflow = ConstantInt::getFalse(OverflowTy);
6922 return true;
6923 }
6924
6925 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6927 return false;
6930 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6931 Result->takeName(&OrigI);
6932 Overflow = ConstantInt::getTrue(OverflowTy);
6933 return true;
6935 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6936 Result->takeName(&OrigI);
6937 Overflow = ConstantInt::getFalse(OverflowTy);
6938 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6939 if (IsSigned)
6940 Inst->setHasNoSignedWrap();
6941 else
6942 Inst->setHasNoUnsignedWrap();
6943 }
6944 return true;
6945 }
6946
6947 llvm_unreachable("Unexpected overflow result");
6948}
6949
6950/// Recognize and process idiom involving test for unsigned
6951/// overflow.
6952///
6953/// The caller has matched a pattern of the form:
6954/// I = cmp u (add(zext A, zext B), V
6955/// I = cmp u (mul(zext A, zext B), V
6956/// The function checks if this is a test for overflow and if so replaces
6957/// addition/multiplication with call to the umul intrinsic or the canonical
6958/// form of uadd overflow.
6959///
6960/// \param I Compare instruction.
6961/// \param Val Result of add/mul instruction. It is one of the arguments of
6962/// the compare instruction. Must be of integer type.
6963/// \param OtherVal The other argument of compare instruction.
6964/// \returns Instruction which must replace the compare instruction, NULL if no
6965/// replacement required.
6967 const APInt *OtherVal,
6968 InstCombinerImpl &IC) {
6969 // Don't bother doing this transformation for pointers, don't do it for
6970 // vectors.
6971 if (!isa<IntegerType>(Val->getType()))
6972 return nullptr;
6973
6974 auto *Instr = cast<Instruction>(Val);
6975 unsigned Opcode = Instr->getOpcode();
6976 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6977
6978 auto *LHS = cast<ZExtInst>(Instr->getOperand(0)),
6979 *RHS = cast<ZExtInst>(Instr->getOperand(1));
6980 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6981
6982 // Calculate type and width of the result produced by add/mul.with.overflow.
6983 Type *TyA = A->getType(), *TyB = B->getType();
6984 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6985 WidthB = TyB->getPrimitiveSizeInBits();
6986 unsigned ResultWidth;
6987 Type *ResultType;
6988 if (WidthB > WidthA) {
6989 ResultWidth = WidthB;
6990 ResultType = TyB;
6991 } else {
6992 ResultWidth = WidthA;
6993 ResultType = TyA;
6994 }
6995
6996 // In order to replace the original result with a narrower one, all uses must
6997 // ignore upper bits of the result. The number of used low bits must be not
6998 // greater than the width of add or mul.with.overflow.
6999 if (Val->hasNUsesOrMore(2))
7000 for (User *U : Val->users()) {
7001 if (U == &I)
7002 continue;
7003 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
7004 // Check if truncation ignores bits above ResultWidth.
7005 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
7006 if (TruncWidth > ResultWidth)
7007 return nullptr;
7008 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
7009 // Check if AND ignores bits above ResultWidth.
7010 if (BO->getOpcode() != Instruction::And)
7011 return nullptr;
7012 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7013 const APInt &CVal = CI->getValue();
7014 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
7015 return nullptr;
7016 } else {
7017 // In this case we could have the operand of the binary operation
7018 // being defined in another block, and performing the replacement
7019 // could break the dominance relation.
7020 return nullptr;
7021 }
7022 } else {
7023 // Other uses prohibit this transformation.
7024 return nullptr;
7025 }
7026 }
7027
7028 // Recognize patterns
7029 switch (I.getPredicate()) {
7030 case ICmpInst::ICMP_UGT: {
7031 // Recognize pattern:
7032 // val = add/mul(zext A, zext B)
7033 // cmp ugt val, max
7034 APInt MaxVal = APInt::getMaxValue(ResultWidth);
7035 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
7036 if (MaxVal.eq(*OtherVal))
7037 break; // Recognized
7038 return nullptr;
7039 }
7040
7041 case ICmpInst::ICMP_ULT: {
7042 // Recognize pattern:
7043 // val = add/mul(zext A, zext B)
7044 // cmp ult val, max + 1
7045 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), ResultWidth);
7046 if (MaxVal.eq(*OtherVal))
7047 break; // Recognized
7048 return nullptr;
7049 }
7050
7051 default:
7052 return nullptr;
7053 }
7054
7055 InstCombiner::BuilderTy &Builder = IC.Builder;
7056 Builder.SetInsertPoint(Instr);
7057
7058 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
7059 Value *ResultA = A, *ResultB = B;
7060 if (WidthA < ResultWidth)
7061 ResultA = Builder.CreateZExt(A, ResultType);
7062 if (WidthB < ResultWidth)
7063 ResultB = Builder.CreateZExt(B, ResultType);
7064
7065 Value *ArithResult;
7066 Value *OverflowCheck;
7067
7068 if (Opcode == Instruction::Add) {
7069 // Canonical add overflow check: add + compare
7070 ArithResult = Builder.CreateAdd(ResultA, ResultB, "add");
7071 // Overflow if result < either operand (for unsigned add)
7072 if (I.getPredicate() == ICmpInst::ICMP_ULT)
7073 OverflowCheck =
7074 Builder.CreateICmpUGE(ArithResult, ResultA, "not.add.overflow");
7075 else
7076 OverflowCheck =
7077 Builder.CreateICmpULT(ArithResult, ResultA, "add.overflow");
7078 } else {
7079 // For multiplication, the intrinsic is actually the canonical form
7080 Value *Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
7081 ResultType, {ResultA, ResultB},
7082 /*FMFSource=*/nullptr, "umul");
7083 ArithResult = Builder.CreateExtractValue(Call, 0, "umul.value");
7084 OverflowCheck = Builder.CreateExtractValue(Call, 1, "umul.overflow");
7085 if (I.getPredicate() == ICmpInst::ICMP_ULT)
7086 OverflowCheck = Builder.CreateNot(OverflowCheck);
7087 }
7088
7089 IC.addToWorklist(Instr);
7090
7091 // Replace uses of the original add/mul result with the new arithmetic result
7092 if (Val->hasNUsesOrMore(2)) {
7093 for (User *U : make_early_inc_range(Val->users())) {
7094 if (U == &I)
7095 continue;
7096 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
7097 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
7098 IC.replaceInstUsesWith(*TI, ArithResult);
7099 else
7100 TI->setOperand(0, ArithResult);
7101 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
7102 assert(BO->getOpcode() == Instruction::And);
7103 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
7104 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
7105 APInt ShortMask = CI->getValue().trunc(ResultWidth);
7106 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
7107 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
7108 IC.replaceInstUsesWith(*BO, Zext);
7109 } else {
7110 llvm_unreachable("Unexpected Binary operation");
7111 }
7113 }
7114 }
7115
7116 return IC.replaceInstUsesWith(I, OverflowCheck);
7117}
7118
7119/// When performing a comparison against a constant, it is possible that not all
7120/// the bits in the LHS are demanded. This helper method computes the mask that
7121/// IS demanded.
7123 const APInt *RHS;
7124 if (!match(I.getOperand(1), m_APInt(RHS)))
7126
7127 // If this is a normal comparison, it demands all bits. If it is a sign bit
7128 // comparison, it only demands the sign bit.
7129 bool UnusedBit;
7130 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
7132
7133 switch (I.getPredicate()) {
7134 // For a UGT comparison, we don't care about any bits that
7135 // correspond to the trailing ones of the comparand. The value of these
7136 // bits doesn't impact the outcome of the comparison, because any value
7137 // greater than the RHS must differ in a bit higher than these due to carry.
7138 case ICmpInst::ICMP_UGT:
7139 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
7140
7141 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
7142 // Any value less than the RHS must differ in a higher bit because of carries.
7143 case ICmpInst::ICMP_ULT:
7144 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
7145
7146 default:
7148 }
7149}
7150
7151/// Check that one use is in the same block as the definition and all
7152/// other uses are in blocks dominated by a given block.
7153///
7154/// \param DI Definition
7155/// \param UI Use
7156/// \param DB Block that must dominate all uses of \p DI outside
7157/// the parent block
7158/// \return true when \p UI is the only use of \p DI in the parent block
7159/// and all other uses of \p DI are in blocks dominated by \p DB.
7160///
7162 const Instruction *UI,
7163 const BasicBlock *DB) const {
7164 assert(DI && UI && "Instruction not defined\n");
7165 // Ignore incomplete definitions.
7166 if (!DI->getParent())
7167 return false;
7168 // DI and UI must be in the same block.
7169 if (DI->getParent() != UI->getParent())
7170 return false;
7171 // Protect from self-referencing blocks.
7172 if (DI->getParent() == DB)
7173 return false;
7174 for (const Instruction *Usr : DI->users()) {
7175 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
7176 return false;
7177 }
7178 return true;
7179}
7180
7181/// Return true when the instruction sequence within a block is select-cmp-br.
7183 const BasicBlock *BB = SI->getParent();
7184 if (!BB)
7185 return false;
7186 auto *BI = dyn_cast<CondBrInst>(BB->getTerminator());
7187 if (!BI)
7188 return false;
7189 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7190 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7191 return false;
7192 return true;
7193}
7194
7195/// True when a select result is replaced by one of its operands
7196/// in select-icmp sequence. This will eventually result in the elimination
7197/// of the select.
7198///
7199/// \param SI Select instruction
7200/// \param Icmp Compare instruction
7201/// \param SIOpd Operand that replaces the select
7202///
7203/// Notes:
7204/// - The replacement is global and requires dominator information
7205/// - The caller is responsible for the actual replacement
7206///
7207/// Example:
7208///
7209/// entry:
7210/// %4 = select i1 %3, %C* %0, %C* null
7211/// %5 = icmp eq %C* %4, null
7212/// br i1 %5, label %9, label %7
7213/// ...
7214/// ; <label>:7 ; preds = %entry
7215/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7216/// ...
7217///
7218/// can be transformed to
7219///
7220/// %5 = icmp eq %C* %0, null
7221/// %6 = select i1 %3, i1 %5, i1 true
7222/// br i1 %6, label %9, label %7
7223/// ...
7224/// ; <label>:7 ; preds = %entry
7225/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7226///
7227/// Similar when the first operand of the select is a constant or/and
7228/// the compare is for not equal rather than equal.
7229///
7230/// NOTE: The function is only called when the select and compare constants
7231/// are equal, the optimization can work only for EQ predicates. This is not a
7232/// major restriction since a NE compare should be 'normalized' to an equal
7233/// compare, which usually happens in the combiner and test case
7234/// select-cmp-br.ll checks for it.
7236 const ICmpInst *Icmp,
7237 const unsigned SIOpd) {
7238 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7240 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7241 // The check for the single predecessor is not the best that can be
7242 // done. But it protects efficiently against cases like when SI's
7243 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7244 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7245 // replaced can be reached on either path. So the uniqueness check
7246 // guarantees that the path all uses of SI (outside SI's parent) are on
7247 // is disjoint from all other paths out of SI. But that information
7248 // is more expensive to compute, and the trade-off here is in favor
7249 // of compile-time. It should also be noticed that we check for a single
7250 // predecessor and not only uniqueness. This to handle the situation when
7251 // Succ and Succ1 points to the same basic block.
7252 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7253 NumSel++;
7254 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7255 return true;
7256 }
7257 }
7258 return false;
7259}
7260
7261/// Try to fold the comparison based on range information we can get by checking
7262/// whether bits are known to be zero or one in the inputs.
7264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7265 Type *Ty = Op0->getType();
7266 ICmpInst::Predicate Pred = I.getPredicate();
7267
7268 // Get scalar or pointer size.
7269 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7270 ? Ty->getScalarSizeInBits()
7271 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7272
7273 if (!BitWidth)
7274 return nullptr;
7275
7276 KnownBits Op0Known(BitWidth);
7277 KnownBits Op1Known(BitWidth);
7278
7279 {
7280 // Don't use dominating conditions when folding icmp using known bits. This
7281 // may convert signed into unsigned predicates in ways that other passes
7282 // (especially IndVarSimplify) may not be able to reliably undo.
7283 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7285 Op0Known, Q))
7286 return &I;
7287
7288 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7289 return &I;
7290 }
7291
7292 // If an unsigned samesign comparison is not poison, both operands have the
7293 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7294 // values so the existing range folds can use that constraint.
7295 if (I.hasSameSign() && I.isUnsigned()) {
7296 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7297 if (To.isNegative() || To.isNonNegative())
7298 return;
7299 if (From.isNegative())
7300 To.makeNegative();
7301 else if (From.isNonNegative())
7302 To.makeNonNegative();
7303 };
7304 PropagateSignBit(Op0Known, Op1Known);
7305 PropagateSignBit(Op1Known, Op0Known);
7306 }
7307
7308 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7309 return new ICmpInst(
7310 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7311 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7312 return new ICmpInst(
7313 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7314
7315 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7316 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7317
7318 // Given the known and unknown bits, compute a range that the LHS could be
7319 // in. Compute the Min, Max and RHS values based on the known bits. For the
7320 // EQ and NE we use unsigned values.
7321 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7322 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7323 if (I.isSigned()) {
7324 Op0Min = Op0Known.getSignedMinValue();
7325 Op0Max = Op0Known.getSignedMaxValue();
7326 Op1Min = Op1Known.getSignedMinValue();
7327 Op1Max = Op1Known.getSignedMaxValue();
7328 } else {
7329 Op0Min = Op0Known.getMinValue();
7330 Op0Max = Op0Known.getMaxValue();
7331 Op1Min = Op1Known.getMinValue();
7332 Op1Max = Op1Known.getMaxValue();
7333 }
7334
7335 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7336 // min/max canonical compare with some other compare. That could lead to
7337 // conflict with select canonicalization and infinite looping.
7338 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7339 auto isMinMaxCmp = [&](Instruction &Cmp) {
7340 if (!Cmp.hasOneUse())
7341 return false;
7342 Value *A, *B;
7343 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7345 return false;
7346 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7347 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7348 };
7349 if (!isMinMaxCmp(I)) {
7350 switch (Pred) {
7351 default:
7352 break;
7353 case ICmpInst::ICMP_ULT: {
7354 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7355 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7356 const APInt *CmpC;
7357 if (match(Op1, m_APInt(CmpC))) {
7358 // A <u C -> A == C-1 if min(A)+1 == C
7359 if (*CmpC == Op0Min + 1)
7360 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7361 ConstantInt::get(Op1->getType(), *CmpC - 1));
7362 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7363 // exceeds the log2 of C.
7364 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7365 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7366 Constant::getNullValue(Op1->getType()));
7367 }
7368 break;
7369 }
7370 case ICmpInst::ICMP_UGT: {
7371 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7372 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7373 const APInt *CmpC;
7374 if (match(Op1, m_APInt(CmpC))) {
7375 // A >u C -> A == C+1 if max(a)-1 == C
7376 if (*CmpC == Op0Max - 1)
7377 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7378 ConstantInt::get(Op1->getType(), *CmpC + 1));
7379 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7380 // exceeds the log2 of C.
7381 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7382 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7383 Constant::getNullValue(Op1->getType()));
7384 }
7385 break;
7386 }
7387 case ICmpInst::ICMP_SLT: {
7388 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7389 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7390 const APInt *CmpC;
7391 if (match(Op1, m_APInt(CmpC))) {
7392 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7393 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7394 ConstantInt::get(Op1->getType(), *CmpC - 1));
7395 }
7396 break;
7397 }
7398 case ICmpInst::ICMP_SGT: {
7399 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7400 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7401 const APInt *CmpC;
7402 if (match(Op1, m_APInt(CmpC))) {
7403 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7404 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7405 ConstantInt::get(Op1->getType(), *CmpC + 1));
7406 }
7407 break;
7408 }
7409 }
7410 }
7411
7412 // Based on the range information we know about the LHS, see if we can
7413 // simplify this comparison. For example, (x&4) < 8 is always true.
7414 switch (Pred) {
7415 default:
7416 break;
7417 case ICmpInst::ICMP_EQ:
7418 case ICmpInst::ICMP_NE: {
7419 // If all bits are known zero except for one, then we know at most one bit
7420 // is set. If the comparison is against zero, then this is a check to see if
7421 // *that* bit is set.
7422 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7423 if (Op1Known.isZero()) {
7424 // If the LHS is an AND with the same constant, look through it.
7425 Value *LHS = nullptr;
7426 const APInt *LHSC;
7427 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7428 *LHSC != Op0KnownZeroInverted)
7429 LHS = Op0;
7430
7431 Value *X;
7432 const APInt *C1;
7433 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7434 Type *XTy = X->getType();
7435 unsigned Log2C1 = C1->countr_zero();
7436 APInt C2 = Op0KnownZeroInverted;
7437 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7438 if (C2Pow2.isPowerOf2()) {
7439 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7440 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7441 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7442 unsigned Log2C2 = C2Pow2.countr_zero();
7443 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7444 auto NewPred =
7446 return new ICmpInst(NewPred, X, CmpC);
7447 }
7448 }
7449 }
7450
7451 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7452 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7453 (Op0Known & Op1Known) == Op0Known)
7454 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7455 ConstantInt::getNullValue(Op1->getType()));
7456 break;
7457 }
7458 case ICmpInst::ICMP_SGE:
7459 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7460 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7461 break;
7462 case ICmpInst::ICMP_SLE:
7463 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7464 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7465 break;
7466 case ICmpInst::ICMP_UGE:
7467 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7468 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7469 break;
7470 case ICmpInst::ICMP_ULE:
7471 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7472 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7473 break;
7474 }
7475
7476 // Turn a signed comparison into an unsigned one if both operands are known to
7477 // have the same sign. Set samesign if possible (except for equality
7478 // predicates).
7479 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7480 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7481 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7482 I.setPredicate(I.getUnsignedPredicate());
7483 I.setSameSign();
7484 return &I;
7485 }
7486
7487 return nullptr;
7488}
7489
7490/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7491/// then try to reduce patterns based on that limit.
7493 Value *X, *Y;
7494 CmpPredicate Pred;
7495
7496 // X must be 0 and bool must be true for "ULT":
7497 // X <u (zext i1 Y) --> (X == 0) & Y
7498 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7499 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7500 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7501
7502 // X must be 0 or bool must be true for "ULE":
7503 // X <=u (sext i1 Y) --> (X == 0) | Y
7504 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7505 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7506 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7507
7508 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7509 CmpPredicate Pred1, Pred2;
7510 const APInt *C;
7511 Instruction *ExtI;
7512 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7515 m_APInt(C)))))) &&
7516 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7517 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7518 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7519 auto CreateRangeCheck = [&] {
7520 Value *CmpV1 =
7521 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7522 Value *CmpV2 = Builder.CreateICmp(
7523 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7525 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7526 CmpV1, CmpV2);
7527 };
7528 if (C->isZero()) {
7529 if (Pred2 == ICmpInst::ICMP_EQ) {
7530 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7531 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7532 return replaceInstUsesWith(
7533 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7534 } else if (!IsSExt || HasOneUse) {
7535 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7536 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7537 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7538 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7539 return CreateRangeCheck();
7540 }
7541 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7542 if (Pred2 == ICmpInst::ICMP_NE) {
7543 // icmp eq X, (zext (icmp ne X, 1)) --> false
7544 // icmp ne X, (zext (icmp ne X, 1)) --> true
7545 // icmp eq X, (sext (icmp ne X, -1)) --> false
7546 // icmp ne X, (sext (icmp ne X, -1)) --> true
7547 return replaceInstUsesWith(
7548 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7549 } else if (!IsSExt || HasOneUse) {
7550 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7551 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7552 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7553 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7554 return CreateRangeCheck();
7555 }
7556 } else {
7557 // when C != 0 && C != 1:
7558 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7559 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7560 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7561 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7562 // when C != 0 && C != -1:
7563 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7564 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7565 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7566 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7567 return ICmpInst::Create(
7568 Instruction::ICmp, Pred1, X,
7569 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7570 ? (IsSExt ? -1 : 1)
7571 : 0));
7572 }
7573 }
7574
7575 return nullptr;
7576}
7577
7578/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7579/// it into the appropriate icmp lt or icmp gt instruction. This transform
7580/// allows them to be folded in visitICmpInst.
7582 CmpPredicate Pred = I.getCmpPredicate();
7585 return nullptr;
7586
7587 Value *Op0 = I.getOperand(0);
7588 Value *Op1 = I.getOperand(1);
7589 auto *Op1C = dyn_cast<Constant>(Op1);
7590 if (!Op1C)
7591 return nullptr;
7592
7593 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7594 if (!FlippedStrictness)
7595 return nullptr;
7596
7597 auto *NewCmp =
7598 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7599 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7600 return NewCmp;
7601}
7602
7603/// If we have a comparison with a non-canonical predicate, if we can update
7604/// all the users, invert the predicate and adjust all the users.
7606 // Is the predicate already canonical?
7607 CmpInst::Predicate Pred = I.getPredicate();
7609 return nullptr;
7610
7611 // Can all users be adjusted to predicate inversion?
7612 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7613 return nullptr;
7614
7615 // Ok, we can canonicalize comparison!
7616 // Let's first invert the comparison's predicate.
7617 I.setPredicate(CmpInst::getInversePredicate(Pred));
7618 I.setName(I.getName() + ".not");
7619
7620 // And, adapt users.
7622
7623 return &I;
7624}
7625
7626/// Integer compare with boolean values can always be turned into bitwise ops.
7628 InstCombiner::BuilderTy &Builder) {
7629 Value *A = I.getOperand(0), *B = I.getOperand(1);
7630 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7631
7632 // A boolean compared to true/false can be simplified to Op0/true/false in
7633 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7634 // Cases not handled by InstSimplify are always 'not' of Op0.
7635 if (match(B, m_Zero())) {
7636 switch (I.getPredicate()) {
7637 case CmpInst::ICMP_EQ: // A == 0 -> !A
7638 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7639 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7641 default:
7642 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7643 }
7644 } else if (match(B, m_One())) {
7645 switch (I.getPredicate()) {
7646 case CmpInst::ICMP_NE: // A != 1 -> !A
7647 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7648 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7650 default:
7651 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7652 }
7653 }
7654
7655 switch (I.getPredicate()) {
7656 default:
7657 llvm_unreachable("Invalid icmp instruction!");
7658 case ICmpInst::ICMP_EQ:
7659 // icmp eq i1 A, B -> ~(A ^ B)
7660 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7661
7662 case ICmpInst::ICMP_NE:
7663 // icmp ne i1 A, B -> A ^ B
7664 return BinaryOperator::CreateXor(A, B);
7665
7666 case ICmpInst::ICMP_UGT:
7667 // icmp ugt -> icmp ult
7668 std::swap(A, B);
7669 [[fallthrough]];
7670 case ICmpInst::ICMP_ULT:
7671 // icmp ult i1 A, B -> ~A & B
7672 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7673
7674 case ICmpInst::ICMP_SGT:
7675 // icmp sgt -> icmp slt
7676 std::swap(A, B);
7677 [[fallthrough]];
7678 case ICmpInst::ICMP_SLT:
7679 // icmp slt i1 A, B -> A & ~B
7680 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7681
7682 case ICmpInst::ICMP_UGE:
7683 // icmp uge -> icmp ule
7684 std::swap(A, B);
7685 [[fallthrough]];
7686 case ICmpInst::ICMP_ULE:
7687 // icmp ule i1 A, B -> ~A | B
7688 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7689
7690 case ICmpInst::ICMP_SGE:
7691 // icmp sge -> icmp sle
7692 std::swap(A, B);
7693 [[fallthrough]];
7694 case ICmpInst::ICMP_SLE:
7695 // icmp sle i1 A, B -> A | ~B
7696 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7697 }
7698}
7699
7700// Transform pattern like:
7701// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7702// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7703// Into:
7704// (X l>> Y) != 0
7705// (X l>> Y) == 0
7707 InstCombiner::BuilderTy &Builder) {
7708 CmpPredicate Pred, NewPred;
7709 Value *X, *Y;
7710 if (match(&Cmp,
7712 switch (Pred) {
7713 case ICmpInst::ICMP_ULE:
7714 NewPred = ICmpInst::ICMP_NE;
7715 break;
7716 case ICmpInst::ICMP_UGT:
7717 NewPred = ICmpInst::ICMP_EQ;
7718 break;
7719 default:
7720 return nullptr;
7721 }
7722 } else if (match(&Cmp, m_c_ICmp(Pred,
7725 m_Add(m_Shl(m_One(), m_Value(Y)),
7726 m_AllOnes()))),
7727 m_Value(X)))) {
7728 // The variant with 'add' is not canonical, (the variant with 'not' is)
7729 // we only get it because it has extra uses, and can't be canonicalized,
7730
7731 switch (Pred) {
7732 case ICmpInst::ICMP_ULT:
7733 NewPred = ICmpInst::ICMP_NE;
7734 break;
7735 case ICmpInst::ICMP_UGE:
7736 NewPred = ICmpInst::ICMP_EQ;
7737 break;
7738 default:
7739 return nullptr;
7740 }
7741 } else
7742 return nullptr;
7743
7744 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7746 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7747}
7748
7750 InstCombiner::BuilderTy &Builder) {
7751 const CmpInst::Predicate Pred = Cmp.getPredicate();
7752 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7753 Value *V1, *V2;
7754
7755 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7756 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7757 if (auto *I = dyn_cast<Instruction>(V))
7758 I->copyIRFlags(&Cmp);
7759 Module *M = Cmp.getModule();
7761 M, Intrinsic::vector_reverse, V->getType());
7762 return CallInst::Create(F, V);
7763 };
7764
7765 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7766 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7767 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7768 (LHS->hasOneUse() || RHS->hasOneUse()))
7769 return createCmpReverse(Pred, V1, V2);
7770
7771 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7772 if (LHS->hasOneUse() && isSplatValue(RHS))
7773 return createCmpReverse(Pred, V1, RHS);
7774 }
7775 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7776 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7777 return createCmpReverse(Pred, LHS, V2);
7778
7779 ArrayRef<int> M;
7780 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7781 return nullptr;
7782
7783 // If both arguments of the cmp are shuffles that use the same mask and
7784 // shuffle within a single vector, move the shuffle after the cmp:
7785 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7786 Type *V1Ty = V1->getType();
7787 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7788 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7789 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7790 return new ShuffleVectorInst(NewCmp, M);
7791 }
7792
7793 // Try to canonicalize compare with splatted operand and splat constant.
7794 // TODO: We could generalize this for more than splats. See/use the code in
7795 // InstCombiner::foldVectorBinop().
7796 Constant *C;
7797 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7798 return nullptr;
7799
7800 // Length-changing splats are ok, so adjust the constants as needed:
7801 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7802 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7803 int MaskSplatIndex;
7804 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7805 // We allow poison in matching, but this transform removes it for safety.
7806 // Demanded elements analysis should be able to recover some/all of that.
7807 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7808 ScalarC);
7809 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7810 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7811 return new ShuffleVectorInst(NewCmp, NewM);
7812 }
7813
7814 return nullptr;
7815}
7816
7817// extract(uadd.with.overflow(A, B), 0) ult A
7818// -> extract(uadd.with.overflow(A, B), 1)
7820 CmpInst::Predicate Pred = I.getPredicate();
7821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7822
7823 Value *UAddOv;
7824 Value *A, *B;
7825 auto UAddOvResultPat = m_ExtractValue<0>(
7827 if (match(Op0, UAddOvResultPat) &&
7828 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7829 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7830 (match(A, m_One()) || match(B, m_One()))) ||
7831 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7832 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7833 // extract(uadd.with.overflow(A, B), 0) < A
7834 // extract(uadd.with.overflow(A, 1), 0) == 0
7835 // extract(uadd.with.overflow(A, -1), 0) != -1
7836 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7837 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7838 (Op0 == A || Op0 == B))
7839 // A > extract(uadd.with.overflow(A, B), 0)
7840 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7841 else
7842 return nullptr;
7843
7844 return ExtractValueInst::Create(UAddOv, 1);
7845}
7846
7848 if (!I.getOperand(0)->getType()->isPointerTy() ||
7850 I.getParent()->getParent(),
7851 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7852 return nullptr;
7853 }
7854 Value *Ptr;
7855 if (match(I.getOperand(0),
7857 match(I.getOperand(1), m_Zero())) {
7858 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(), Ptr,
7859 I.getOperand(1));
7860 }
7861 return nullptr;
7862}
7863
7865 IRBuilderBase &Builder) {
7866 if (!ICmpInst::isEquality(I.getPredicate()))
7867 return nullptr;
7868
7869 // The caller puts constants after non-constants.
7870 Value *Op = I.getOperand(0);
7871 Value *Const = I.getOperand(1);
7872
7873 // For Cond an equality condition, fold
7874 //
7875 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7876 // icmp (eq|ne) Op, (Zero|AllOnes)
7877 //
7878 // with a bitcast.
7879 Value *Vec;
7880 if ((match(Const, m_ZeroInt()) &&
7882 m_Value(Vec))))) ||
7883 (match(Const, m_AllOnes()) &&
7885 m_Value(Vec)))))) {
7886 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7887 if (!VecTy)
7888 return nullptr;
7889 Type *VecEltTy = VecTy->getElementType();
7890 unsigned ScalarBW =
7891 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7892 if (!DL.fitsInLegalInteger(ScalarBW))
7893 return nullptr;
7894 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7895 Value *NewConst = match(Const, m_ZeroInt())
7896 ? ConstantInt::get(ScalarTy, 0)
7897 : ConstantInt::getAllOnesValue(ScalarTy);
7898 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7899 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7900 }
7901 return nullptr;
7902}
7903
7904/// This function folds patterns produced by lowering of reduce idioms, such as
7905/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7906/// attempts to generate fewer number of scalar comparisons instead of vector
7907/// comparisons when possible.
7909 InstCombiner::BuilderTy &Builder,
7910 const DataLayout &DL) {
7911 if (I.getType()->isVectorTy())
7912 return nullptr;
7913 CmpPredicate OuterPred, InnerPred;
7914 Value *LHS, *RHS;
7915
7916 // Match lowering of @llvm.vector.reduce.and. Turn
7917 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7918 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7919 /// %res = icmp <pred> i8 %scalar_ne, 0
7920 ///
7921 /// into
7922 ///
7923 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7924 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7925 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7926 ///
7927 /// for <pred> in {ne, eq}.
7928 if (!match(&I, m_ICmp(OuterPred,
7930 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7931 m_Zero())))
7932 return nullptr;
7933 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7934 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7935 return nullptr;
7936 unsigned NumBits =
7937 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7938 // TODO: Relax this to "not wider than max legal integer type"?
7939 if (!DL.isLegalInteger(NumBits))
7940 return nullptr;
7941
7942 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7943 auto *ScalarTy = Builder.getIntNTy(NumBits);
7944 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7945 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7946 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7947 I.getName());
7948 }
7949
7950 return nullptr;
7951}
7952
7953// This helper will be called with icmp operands in both orders.
7955 Value *Op0, Value *Op1,
7956 ICmpInst &CtxI) {
7957 // Each fold below requires Op0 to be a particular operator, so dispatch on
7958 // its opcode and only try the folds that can apply.
7959 switch (Operator::getOpcode(Op0)) {
7960 default:
7961 return nullptr;
7962
7963 case Instruction::GetElementPtr:
7964 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7965 return foldGEPICmp(cast<GEPOperator>(Op0), Op1, Pred, CtxI);
7966
7967 case Instruction::Select:
7968 return foldSelectICmp(Pred, cast<SelectInst>(Op0), Op1, CtxI);
7969
7970 case Instruction::Call: {
7971 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7972 if (Instruction *Res = foldICmpWithMinMax(CtxI, MinMax, Op1, Pred))
7973 return Res;
7974
7975 if (Instruction *Res = foldICmpWithClamp(CtxI, Op1, MinMax))
7976 return Res;
7977 }
7978
7979 // abs(X) >= X --> true
7980 // abs(X) u<= X --> true
7981 // abs(X) < X --> false
7982 // abs(X) u> X --> false
7983 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7984 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7985 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7986 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7987 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7988 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7989 Value *X;
7990 Constant *C;
7992 match(Op1, m_Specific(X))) {
7993 Value *NullValue = Constant::getNullValue(X->getType());
7994 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7995 const APInt SMin =
7996 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7997 bool IsIntMinPosion = C->isAllOnesValue();
7998 switch (Pred) {
7999 case CmpInst::ICMP_ULE:
8000 case CmpInst::ICMP_SGE:
8001 return replaceInstUsesWith(CtxI, ConstantInt::getTrue(CtxI.getType()));
8002 case CmpInst::ICMP_UGT:
8003 case CmpInst::ICMP_SLT:
8005 case CmpInst::ICMP_UGE:
8006 case CmpInst::ICMP_SLE:
8007 case CmpInst::ICMP_EQ: {
8008 return replaceInstUsesWith(
8009 CtxI, IsIntMinPosion
8010 ? Builder.CreateICmpSGT(X, AllOnesValue)
8011 : Builder.CreateICmpULT(
8012 X, ConstantInt::get(X->getType(), SMin + 1)));
8013 }
8014 case CmpInst::ICMP_ULT:
8015 case CmpInst::ICMP_SGT:
8016 case CmpInst::ICMP_NE: {
8017 return replaceInstUsesWith(
8018 CtxI, IsIntMinPosion
8019 ? Builder.CreateICmpSLT(X, NullValue)
8020 : Builder.CreateICmpUGT(
8021 X, ConstantInt::get(X->getType(), SMin)));
8022 }
8023 default:
8024 llvm_unreachable("Invalid predicate!");
8025 }
8026 }
8027
8028 // For a nonzero constant C:
8029 // usub.sat(X, C) == X --> X == 0
8030 // usub.sat(X, C) != X --> X != 0
8031 // usub.sat(X, C) < X --> X != 0
8033 m_NonZeroInt())) &&
8034 (CmpInst::isEquality(Pred) || Pred == ICmpInst::ICMP_ULT)) {
8035 ICmpInst::Predicate NewPred =
8036 CmpInst::isEquality(Pred) ? Pred.dropSameSign() : ICmpInst::ICMP_NE;
8037 return new ICmpInst(NewPred, Op1, Constant::getNullValue(Op1->getType()));
8038 }
8039 return nullptr;
8040 }
8041
8042 case Instruction::Add: {
8043 Value *X;
8044 const APInt *C;
8045 // icmp X+Cst, X
8046 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
8047 return foldICmpAddOpConst(X, *C, Pred);
8048 return nullptr;
8049 }
8050
8051 case Instruction::And:
8052 case Instruction::Or: {
8053 const SimplifyQuery Q = SQ.getWithInstruction(&CtxI);
8054 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
8055 return replaceInstUsesWith(CtxI, V);
8056 return nullptr;
8057 }
8058
8059 case Instruction::UDiv:
8060 case Instruction::SDiv: {
8061 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
8062 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
8063 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
8064 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8066 }
8067
8068 if (!ICmpInst::isUnsigned(Pred) &&
8069 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
8070 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8072 }
8073 return nullptr;
8074 }
8075
8076 case Instruction::LShr:
8077 case Instruction::AShr: {
8078 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
8079 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
8080 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
8081 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8083 }
8084
8085 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
8086 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
8087 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8089 }
8090 return nullptr;
8091 }
8092
8093 case Instruction::Shl: {
8094 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
8095 // -> icmp X, (add nsw/nuw Y, K >> L)
8096 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
8097 Value *X;
8098 uint64_t ShAmt;
8099 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
8100 !CtxI.isSigned()) {
8101 if (ShAmt >= X->getType()->getScalarSizeInBits())
8102 return nullptr;
8103 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
8104 ShiftSemantics::Unsigned, &CtxI)) {
8105 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
8107 return new ICmpInst(Pred, X, NewOp1);
8108 }
8109 }
8110
8111 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
8112 !CtxI.isUnsigned()) {
8113 if (ShAmt >= X->getType()->getScalarSizeInBits())
8114 return nullptr;
8115 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
8116 ShiftSemantics::Signed, &CtxI)) {
8117 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
8119 return new ICmpInst(Pred, X, NewOp1);
8120 }
8121 }
8122 return nullptr;
8123 }
8124 }
8125}
8126
8128 bool Changed = false;
8129 const SimplifyQuery Q = SQ.getWithInstruction(&I);
8130 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8131 unsigned Op0Cplxity = getComplexity(Op0);
8132 unsigned Op1Cplxity = getComplexity(Op1);
8133
8134 /// Orders the operands of the compare so that they are listed from most
8135 /// complex to least complex. This puts constants before unary operators,
8136 /// before binary operators.
8137 if (Op0Cplxity < Op1Cplxity) {
8138 I.swapOperands();
8139 std::swap(Op0, Op1);
8140 Changed = true;
8141 }
8142
8143 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
8144 return replaceInstUsesWith(I, V);
8145
8147 return Res;
8148
8149 if (Op0->getType()->isIntOrIntVectorTy(1))
8151 return Res;
8152
8154 return Res;
8155
8157 return Res;
8158
8160 return Res;
8161
8163 return Res;
8164
8166 return Res;
8167
8169 return Res;
8170
8172 return Res;
8173
8174 // Test if the ICmpInst instruction is used exclusively by a select as
8175 // part of a minimum or maximum operation. If so, refrain from doing
8176 // any other folding. This helps out other analyses which understand
8177 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8178 // and CodeGen. And in this case, at least one of the comparison
8179 // operands has at least one user besides the compare (the select),
8180 // which would often largely negate the benefit of folding anyway.
8181 //
8182 // Do the same for the other patterns recognized by matchSelectPattern.
8183 if (I.hasOneUse())
8184 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8185 Value *A, *B;
8187 if (SPR.Flavor != SPF_UNKNOWN)
8188 return nullptr;
8189 }
8190
8191 // Do this after checking for min/max to prevent infinite looping.
8192 if (Instruction *Res = foldICmpWithZero(I))
8193 return Res;
8194
8195 Value *X;
8196 const APInt *C;
8197 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8198 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8199 match(Op1, m_Not(m_Specific(X)))) {
8200 if (C->isNonNegative())
8201 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8202 Constant::getNullValue(X->getType()));
8203 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8204 ConstantInt::get(X->getType(), ~*C));
8205 }
8206
8207 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8208 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8209 match(Op1, m_Not(m_Specific(X)))) {
8210 if (C->isNonNegative())
8211 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8212 Constant::getAllOnesValue(X->getType()));
8213 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8214 ConstantInt::get(X->getType(), ~*C));
8215 }
8216
8217 // FIXME: We only do this after checking for min/max to prevent infinite
8218 // looping caused by a reverse canonicalization of these patterns for min/max.
8219 // FIXME: The organization of folds is a mess. These would naturally go into
8220 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8221 // down here after the min/max restriction.
8222 ICmpInst::Predicate Pred = I.getPredicate();
8223 if (match(Op1, m_APInt(C))) {
8224 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8225 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8227 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8228 }
8229
8230 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8231 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8233 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8234 }
8235 }
8236
8237 // The folds in here may rely on wrapping flags and special constants, so
8238 // they can break up min/max idioms in some cases but not seemingly similar
8239 // patterns.
8240 // FIXME: It may be possible to enhance select folding to make this
8241 // unnecessary. It may also be moot if we canonicalize to min/max
8242 // intrinsics.
8243 if (Instruction *Res = foldICmpBinOp(I, Q))
8244 return Res;
8245
8247 return Res;
8248
8249 // Try to match comparison as a sign bit test. Intentionally do this after
8250 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8251 if (Instruction *New = foldSignBitTest(I))
8252 return New;
8253
8254 if (auto *PN = dyn_cast<PHINode>(Op0))
8255 if (Instruction *NV = foldOpIntoPhi(I, PN))
8256 return NV;
8257 if (auto *PN = dyn_cast<PHINode>(Op1))
8258 if (Instruction *NV = foldOpIntoPhi(I, PN))
8259 return NV;
8260
8262 return Res;
8263
8264 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8265 return Res;
8266 if (Instruction *Res =
8267 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8268 return Res;
8269
8270 if (I.isCommutative()) {
8271 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8272 replaceOperand(I, 0, Pair->first);
8273 replaceOperand(I, 1, Pair->second);
8274 return &I;
8275 }
8276 }
8277
8278 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8279 // when all select arms are constants, via truth table.
8281 return R;
8282
8283 // In case of a comparison with two select instructions having the same
8284 // condition, check whether one of the resulting branches can be simplified.
8285 // If so, just compare the other branch and select the appropriate result.
8286 // For example:
8287 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8288 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8289 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8290 // The icmp will result false for the false value of selects and the result
8291 // will depend upon the comparison of true values of selects if %cmp is
8292 // true. Thus, transform this into:
8293 // %cmp = icmp slt i32 %y, %z
8294 // %sel = select i1 %cond, i1 %cmp, i1 false
8295 // This handles similar cases to transform.
8296 {
8297 Value *Cond, *A, *B, *C, *D;
8298 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8300 (Op0->hasOneUse() || Op1->hasOneUse())) {
8301 // Check whether comparison of TrueValues can be simplified
8302 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8303 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8304 return SelectInst::Create(Cond, Res, NewICMP, /*NameStr=*/"",
8305 /*InsertBefore=*/nullptr,
8306 cast<Instruction>(Op0));
8307 }
8308 // Check whether comparison of FalseValues can be simplified
8309 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8310 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8311 return SelectInst::Create(Cond, NewICMP, Res, /*NameStr=*/"",
8312 /*InsertBefore=*/nullptr,
8313 cast<Instruction>(Op0));
8314 }
8315 }
8316 }
8317
8318 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8319 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8320 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8321 {
8322 Value *A, *B;
8323 CmpPredicate CmpPred;
8324 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8326 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8327 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8328 bool I0NUW = I0->hasNoUnsignedWrap();
8329 bool I1NUW = I1->hasNoUnsignedWrap();
8330 bool I0NSW = I0->hasNoSignedWrap();
8331 bool I1NSW = I1->hasNoSignedWrap();
8332 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8333 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8334 (ICmpInst::isEquality(Pred) &&
8335 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8336 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8337 ConstantInt::get(Op0->getType(), 0));
8338 }
8339 }
8340 }
8341
8342 // Try to optimize equality comparisons against alloca-based pointers.
8343 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8344 assert(Op1->getType()->isPointerTy() &&
8345 "Comparing pointer with non-pointer?");
8346 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8347 if (foldAllocaCmp(Alloca))
8348 return nullptr;
8349 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8350 if (foldAllocaCmp(Alloca))
8351 return nullptr;
8352 }
8353
8354 if (Instruction *Res = foldICmpBitCast(I))
8355 return Res;
8356
8357 // TODO: Hoist this above the min/max bailout.
8359 return R;
8360
8361 // icmp (zext X), (and (trunc Y), Mask) -> icmp X, trunc Y IFF Mask exactly
8362 // covers the bits of X
8363 {
8364 Value *Y;
8365 const APInt *Mask;
8366 if (match(I.getOperand(1), m_ZExt(m_Value(X))) &&
8367 match(I.getOperand(0),
8368 m_OneUse(m_And(m_Trunc(m_Value(Y)), m_APInt(Mask))))) {
8369 Type *SmallType = X->getType();
8370 unsigned SmallWidth = SmallType->getScalarSizeInBits();
8371 if (Mask->isMask(SmallWidth) &&
8372 shouldChangeType(I.getOperand(0)->getType(), SmallType)) {
8373 Value *NewTrunc = Builder.CreateTrunc(Y, SmallType);
8374 return new ICmpInst(I.getUnsignedPredicate(), NewTrunc, X);
8375 }
8376 }
8377 }
8378
8379 {
8380 Value *X, *Y;
8381 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8382 // and (X & ~Y) != 0 --> (X & Y) == 0
8383 // if A is a power of 2.
8384 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8385 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8386 I.isEquality())
8387 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8388 Op1);
8389
8390 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8391 if (Op0->getType()->isIntOrIntVectorTy()) {
8392 bool ConsumesOp0, ConsumesOp1;
8393 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8394 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8395 (ConsumesOp0 || ConsumesOp1)) {
8396 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8397 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8398 assert(InvOp0 && InvOp1 &&
8399 "Mismatch between isFreeToInvert and getFreelyInverted");
8400 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8401 }
8402 }
8403
8404 Instruction *AddI = nullptr;
8406 m_Instruction(AddI))) &&
8407 isa<IntegerType>(X->getType())) {
8408 Value *Result;
8409 Constant *Overflow;
8410 // m_UAddWithOverflow can match patterns that do not include an explicit
8411 // "add" instruction, so check the opcode of the matched op.
8412 if (AddI->getOpcode() == Instruction::Add &&
8413 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8414 Result, Overflow)) {
8415 replaceInstUsesWith(*AddI, Result);
8416 eraseInstFromFunction(*AddI);
8417 return replaceInstUsesWith(I, Overflow);
8418 }
8419 }
8420
8421 // (zext X) + (zext Y) --> add + overflow check.
8422 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8423 if ((match(Op0, m_NUWAdd(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) ||
8424 match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y))))) &&
8425 match(Op1, m_APInt(C))) {
8426 if (Instruction *R = processUZExtIdiom(I, Op0, C, *this))
8427 return R;
8428 }
8429
8430 // Signbit test folds
8431 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8432 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8433 Instruction *ExtI;
8434 if ((I.isUnsigned() || I.isEquality()) &&
8435 match(Op1,
8437 Y->getType()->getScalarSizeInBits() == 1 &&
8438 (Op0->hasOneUse() || Op1->hasOneUse())) {
8439 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8440 Instruction *ShiftI;
8441 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8443 OpWidth - 1))))) {
8444 unsigned ExtOpc = ExtI->getOpcode();
8445 unsigned ShiftOpc = ShiftI->getOpcode();
8446 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8447 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8448 Value *SLTZero =
8449 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8450 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8451 return replaceInstUsesWith(I, Cmp);
8452 }
8453 }
8454 }
8455 }
8456
8457 if (Instruction *Res = foldICmpEquality(I))
8458 return Res;
8459
8461 return Res;
8462
8463 if (Instruction *Res = foldICmpOfUAddOv(I))
8464 return Res;
8465
8467 return Res;
8468
8469 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8470 // an i1 which indicates whether or not we successfully did the swap.
8471 //
8472 // Replace comparisons between the old value and the expected value with the
8473 // indicator that 'cmpxchg' returns.
8474 //
8475 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8476 // spuriously fail. In those cases, the old value may equal the expected
8477 // value but it is possible for the swap to not occur.
8478 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8479 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8480 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8481 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8482 !ACXI->isWeak())
8483 return ExtractValueInst::Create(ACXI, 1);
8484
8486 return Res;
8487
8488 if (I.getType()->isVectorTy())
8489 if (Instruction *Res = foldVectorCmp(I, Builder))
8490 return Res;
8491
8493 return Res;
8494
8496 return Res;
8497
8498 {
8499 Value *A;
8500 const APInt *C1, *C2;
8501 ICmpInst::Predicate Pred = I.getPredicate();
8502 if (ICmpInst::isEquality(Pred)) {
8503 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8504 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8505 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8506 match(Op1, m_APInt(C2))) {
8507 Type *InputTy = A->getType();
8508 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8509 // c2 must be non-negative at the bitwidth of a.
8510 if (C2->getActiveBits() < InputBitWidth) {
8511 APInt TruncC1 = C1->trunc(InputBitWidth);
8512 // Check if there are 1s in C1 high bits of size InputBitWidth.
8513 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8514 TruncC1.setBit(InputBitWidth - 1);
8515 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8516 return new ICmpInst(
8517 Pred, AndInst,
8518 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8519 }
8520 }
8521 }
8522 }
8523
8524 return Changed ? &I : nullptr;
8525}
8526
8527/// Fold fcmp ([us]itofp x, cst) if possible.
8529 Instruction *LHSI,
8530 Constant *RHSC) {
8531 const APFloat *RHS;
8532 if (!match(RHSC, m_APFloat(RHS)))
8533 return nullptr;
8534
8535 // Get the width of the mantissa. We don't want to hack on conversions that
8536 // might lose information from the integer, e.g. "i64 -> float"
8537 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8538 if (MantissaWidth == -1)
8539 return nullptr; // Unknown.
8540
8541 Type *IntTy = LHSI->getOperand(0)->getType();
8542 unsigned IntWidth = IntTy->getScalarSizeInBits();
8543 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8544
8545 if (I.isEquality()) {
8546 FCmpInst::Predicate P = I.getPredicate();
8547 bool IsExact = false;
8548 APSInt RHSCvt(IntWidth, LHSUnsigned);
8549 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8550
8551 // If the floating point constant isn't an integer value, we know if we will
8552 // ever compare equal / not equal to it.
8553 if (!IsExact) {
8554 // TODO: Can never be -0.0 and other non-representable values
8555 APFloat RHSRoundInt(*RHS);
8557 if (*RHS != RHSRoundInt) {
8559 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8560
8562 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8563 }
8564 }
8565
8566 // TODO: If the constant is exactly representable, is it always OK to do
8567 // equality compares as integer?
8568 }
8569
8570 // Check to see that the input is converted from an integer type that is small
8571 // enough that preserves all bits. TODO: check here for "known" sign bits.
8572 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8573
8574 // Following test does NOT adjust IntWidth downwards for signed inputs,
8575 // because the most negative value still requires all the mantissa bits
8576 // to distinguish it from one less than that value.
8577 if ((int)IntWidth > MantissaWidth) {
8578 // Conversion would lose accuracy. Check if loss can impact comparison.
8579 int Exp = ilogb(*RHS);
8580 if (Exp == APFloat::IEK_Inf) {
8581 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8582 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8583 // Conversion could create infinity.
8584 return nullptr;
8585 } else {
8586 // Note that if RHS is zero or NaN, then Exp is negative
8587 // and first condition is trivially false.
8588 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8589 // Conversion could affect comparison.
8590 return nullptr;
8591 }
8592 }
8593
8594 // Otherwise, we can potentially simplify the comparison. We know that it
8595 // will always come through as an integer value and we know the constant is
8596 // not a NAN (it would have been previously simplified).
8597 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8598
8600 switch (I.getPredicate()) {
8601 default:
8602 llvm_unreachable("Unexpected predicate!");
8603 case FCmpInst::FCMP_UEQ:
8604 case FCmpInst::FCMP_OEQ:
8605 Pred = ICmpInst::ICMP_EQ;
8606 break;
8607 case FCmpInst::FCMP_UGT:
8608 case FCmpInst::FCMP_OGT:
8609 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8610 break;
8611 case FCmpInst::FCMP_UGE:
8612 case FCmpInst::FCMP_OGE:
8613 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8614 break;
8615 case FCmpInst::FCMP_ULT:
8616 case FCmpInst::FCMP_OLT:
8617 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8618 break;
8619 case FCmpInst::FCMP_ULE:
8620 case FCmpInst::FCMP_OLE:
8621 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8622 break;
8623 case FCmpInst::FCMP_UNE:
8624 case FCmpInst::FCMP_ONE:
8625 Pred = ICmpInst::ICMP_NE;
8626 break;
8627 case FCmpInst::FCMP_ORD:
8628 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8629 case FCmpInst::FCMP_UNO:
8630 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8631 }
8632
8633 // Now we know that the APFloat is a normal number, zero or inf.
8634
8635 // See if the FP constant is too large for the integer. For example,
8636 // comparing an i8 to 300.0.
8637 if (!LHSUnsigned) {
8638 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8639 // and large values.
8640 APFloat SMax(RHS->getSemantics());
8641 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8643 if (SMax < *RHS) { // smax < 13123.0
8644 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8645 Pred == ICmpInst::ICMP_SLE)
8646 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8647 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8648 }
8649 } else {
8650 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8651 // +INF and large values.
8652 APFloat UMax(RHS->getSemantics());
8653 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8655 if (UMax < *RHS) { // umax < 13123.0
8656 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8657 Pred == ICmpInst::ICMP_ULE)
8658 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8659 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8660 }
8661 }
8662
8663 if (!LHSUnsigned) {
8664 // See if the RHS value is < SignedMin.
8665 APFloat SMin(RHS->getSemantics());
8666 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8668 if (SMin > *RHS) { // smin > 12312.0
8669 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8670 Pred == ICmpInst::ICMP_SGE)
8671 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8672 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8673 }
8674 } else {
8675 // See if the RHS value is < UnsignedMin.
8676 APFloat UMin(RHS->getSemantics());
8677 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8679 if (UMin > *RHS) { // umin > 12312.0
8680 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8681 Pred == ICmpInst::ICMP_UGE)
8682 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8683 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8684 }
8685 }
8686
8687 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8688 // [0, UMAX], but it may still be fractional. Check whether this is the case
8689 // using the IsExact flag.
8690 // Don't do this for zero, because -0.0 is not fractional.
8691 APSInt RHSInt(IntWidth, LHSUnsigned);
8692 bool IsExact;
8693 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8694 if (!RHS->isZero()) {
8695 if (!IsExact) {
8696 // If we had a comparison against a fractional value, we have to adjust
8697 // the compare predicate and sometimes the value. RHSC is rounded towards
8698 // zero at this point.
8699 switch (Pred) {
8700 default:
8701 llvm_unreachable("Unexpected integer comparison!");
8702 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8703 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8704 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8705 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8706 case ICmpInst::ICMP_ULE:
8707 // (float)int <= 4.4 --> int <= 4
8708 // (float)int <= -4.4 --> false
8709 if (RHS->isNegative())
8710 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8711 break;
8712 case ICmpInst::ICMP_SLE:
8713 // (float)int <= 4.4 --> int <= 4
8714 // (float)int <= -4.4 --> int < -4
8715 if (RHS->isNegative())
8716 Pred = ICmpInst::ICMP_SLT;
8717 break;
8718 case ICmpInst::ICMP_ULT:
8719 // (float)int < -4.4 --> false
8720 // (float)int < 4.4 --> int <= 4
8721 if (RHS->isNegative())
8722 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8723 Pred = ICmpInst::ICMP_ULE;
8724 break;
8725 case ICmpInst::ICMP_SLT:
8726 // (float)int < -4.4 --> int < -4
8727 // (float)int < 4.4 --> int <= 4
8728 if (!RHS->isNegative())
8729 Pred = ICmpInst::ICMP_SLE;
8730 break;
8731 case ICmpInst::ICMP_UGT:
8732 // (float)int > 4.4 --> int > 4
8733 // (float)int > -4.4 --> true
8734 if (RHS->isNegative())
8735 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8736 break;
8737 case ICmpInst::ICMP_SGT:
8738 // (float)int > 4.4 --> int > 4
8739 // (float)int > -4.4 --> int >= -4
8740 if (RHS->isNegative())
8741 Pred = ICmpInst::ICMP_SGE;
8742 break;
8743 case ICmpInst::ICMP_UGE:
8744 // (float)int >= -4.4 --> true
8745 // (float)int >= 4.4 --> int > 4
8746 if (RHS->isNegative())
8747 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8748 Pred = ICmpInst::ICMP_UGT;
8749 break;
8750 case ICmpInst::ICMP_SGE:
8751 // (float)int >= -4.4 --> int >= -4
8752 // (float)int >= 4.4 --> int > 4
8753 if (!RHS->isNegative())
8754 Pred = ICmpInst::ICMP_SGT;
8755 break;
8756 }
8757 }
8758 }
8759
8760 // Lower this FP comparison into an appropriate integer version of the
8761 // comparison.
8762 return new ICmpInst(Pred, LHSI->getOperand(0),
8763 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8764}
8765
8766/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8767/// where all true/false values are constants that allow the compare to be
8768/// constant-folded for every combination of C1 and C2.
8769/// We compute a 4-entry truth table and use createLogicFromTable to
8770/// synthesize a boolean expression of C1 and C2.
8772 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8773 Value *C1, *C2;
8774 Constant *TV1, *FV1, *TV2, *FV2;
8775
8776 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8777 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8778 return nullptr;
8779
8780 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8781 return nullptr;
8782
8783 unsigned Pred = I.getPredicate();
8784 const DataLayout &DL = I.getDataLayout();
8785
8786 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8787 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8788 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8789 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8790
8791 if (!Res00 || !Res01 || !Res10 || !Res11)
8792 return nullptr;
8793
8794 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8795 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8796 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8797 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8798 return nullptr;
8799
8800 std::bitset<4> Table;
8801 if (!Res00->isNullValue())
8802 Table.set(0);
8803 if (!Res01->isNullValue())
8804 Table.set(1);
8805 if (!Res10->isNullValue())
8806 Table.set(2);
8807 if (!Res11->isNullValue())
8808 Table.set(3);
8809
8811 Op0->hasOneUse() && Op1->hasOneUse());
8812 if (!Res)
8813 return nullptr;
8814 return replaceInstUsesWith(I, Res);
8815}
8816
8817/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8819 Constant *RHSC) {
8820 // When C is not 0.0 and infinities are not allowed:
8821 // (C / X) < 0.0 is a sign-bit test of X
8822 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8823 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8824 //
8825 // Proof:
8826 // Multiply (C / X) < 0.0 by X * X / C.
8827 // - X is non zero, if it is the flag 'ninf' is violated.
8828 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8829 // the predicate. C is also non zero by definition.
8830 //
8831 // Thus X * X / C is non zero and the transformation is valid. [qed]
8832
8833 FCmpInst::Predicate Pred = I.getPredicate();
8834
8835 // Check that predicates are valid.
8838 return nullptr;
8839
8840 // Check that RHS operand is zero.
8841 if (!match(RHSC, m_AnyZeroFP()))
8842 return nullptr;
8843
8844 // Check fastmath flags ('ninf').
8845 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8846 return nullptr;
8847
8848 // Check the properties of the dividend. It must not be zero to avoid a
8849 // division by zero (see Proof).
8850 const APFloat *C;
8851 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8852 return nullptr;
8853
8854 if (C->isZero())
8855 return nullptr;
8856
8857 // Get swapped predicate if necessary.
8858 if (C->isNegative())
8859 Pred = I.getSwappedPredicate();
8860
8861 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8862}
8863
8864// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8865// Patterns include:
8866// fptrunc(x) < C --> x < ext(C)
8867// fptrunc(x) <= C --> x <= ext(C)
8868// fptrunc(x) > C --> x > ext(C)
8869// fptrunc(x) >= C --> x >= ext(C)
8870// fptrunc(x) ord/uno C --> x ord/uno 0
8871// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8872// due to precision loss.
8874 const Constant &C) {
8875 FCmpInst::Predicate Pred = I.getPredicate();
8876 Type *DestType = FPTrunc.getOperand(0)->getType();
8877
8878 const APFloat *CValue;
8879 // TODO: support vec
8880 if (!match(&C, m_APFloat(CValue)))
8881 return nullptr;
8882
8883 // Handle ord/uno
8885 assert(!CValue->isNaN() &&
8886 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8887 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8888 ConstantFP::getZero(DestType), "", &I);
8889 }
8890
8891 // Handle <, >, <=, >=
8892 bool RoundDown = false;
8893
8896 RoundDown = true;
8897 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8899 RoundDown = false;
8900 else
8901 return nullptr;
8902
8903 if (CValue->isNaN() || CValue->isInfinity())
8904 return nullptr;
8905
8906 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8907 bool LosesInfo;
8908 APFloat Dest = Src;
8909 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8910 return Dest;
8911 };
8912
8913 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8914 APFloat NextValue = Value;
8915 NextValue.next(RoundDown);
8916 return NextValue;
8917 };
8918
8919 APFloat NextCValue = NextValue(*CValue, RoundDown);
8920
8921 const fltSemantics &DestFltSema =
8922 DestType->getScalarType()->getFltSemantics();
8923
8924 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8925 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8926
8927 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8928 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8929 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8930 // value of 'CValue'.
8931 if (NextCValue.isInfinity()) {
8932 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8933 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8934
8935 ExtNextCValue = ExtCValue + Bias;
8936 }
8937
8938 APFloat ExtMidValue =
8939 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8940
8941 const fltSemantics &SrcFltSema =
8942 C.getType()->getScalarType()->getFltSemantics();
8943
8944 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8945 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8946 if (MidValue != *CValue)
8947 ExtMidValue.next(!RoundDown);
8948
8949 // Check whether 'ExtMidValue' is a valid result since the assumption on
8950 // imaged 'NextCValue' might not hold for new float types.
8951 // ppc_fp128 can't pass here when converting from max float because of
8952 // APFloat implementation.
8953 if (NextCValue.isInfinity()) {
8954 // ExtMidValue --- narrowed ---> Finite
8955 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8956 return nullptr;
8957
8958 // NextExtMidValue --- narrowed ---> Infinity
8959 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8960 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8961 return nullptr;
8962 }
8963
8964 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8965 ConstantFP::get(DestType, ExtMidValue), "", &I);
8966}
8967
8968/// Optimize fabs(X) compared with zero.
8970 Value *X;
8971 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8972 return nullptr;
8973
8974 const APFloat *C;
8975 if (!match(I.getOperand(1), m_APFloat(C)))
8976 return nullptr;
8977
8978 if (!C->isPosZero()) {
8979 if (!C->isSmallestNormalized())
8980 return nullptr;
8981
8982 const Function *F = I.getFunction();
8983 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8984 if (Mode.Input == DenormalMode::PreserveSign ||
8986
8987 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8988 Constant *Zero = ConstantFP::getZero(X->getType());
8989 return new FCmpInst(P, X, Zero, "", I);
8990 };
8991
8992 switch (I.getPredicate()) {
8993 case FCmpInst::FCMP_OLT:
8994 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8995 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8996 case FCmpInst::FCMP_UGE:
8997 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8998 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8999 case FCmpInst::FCMP_OGE:
9000 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
9001 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
9002 case FCmpInst::FCMP_ULT:
9003 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
9004 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
9005 default:
9006 break;
9007 }
9008 }
9009
9010 return nullptr;
9011 }
9012
9013 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
9014 I->setPredicate(P);
9015 return IC.replaceOperand(*I, 0, X);
9016 };
9017
9018 switch (I.getPredicate()) {
9019 case FCmpInst::FCMP_UGE:
9020 case FCmpInst::FCMP_OLT:
9021 // fabs(X) >= 0.0 --> true
9022 // fabs(X) < 0.0 --> false
9023 llvm_unreachable("fcmp should have simplified");
9024
9025 case FCmpInst::FCMP_OGT:
9026 // fabs(X) > 0.0 --> X != 0.0
9027 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
9028
9029 case FCmpInst::FCMP_UGT:
9030 // fabs(X) u> 0.0 --> X u!= 0.0
9031 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
9032
9033 case FCmpInst::FCMP_OLE:
9034 // fabs(X) <= 0.0 --> X == 0.0
9035 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
9036
9037 case FCmpInst::FCMP_ULE:
9038 // fabs(X) u<= 0.0 --> X u== 0.0
9039 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
9040
9041 case FCmpInst::FCMP_OGE:
9042 // fabs(X) >= 0.0 --> !isnan(X)
9043 assert(!I.hasNoNaNs() && "fcmp should have simplified");
9044 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
9045
9046 case FCmpInst::FCMP_ULT:
9047 // fabs(X) u< 0.0 --> isnan(X)
9048 assert(!I.hasNoNaNs() && "fcmp should have simplified");
9049 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
9050
9051 case FCmpInst::FCMP_OEQ:
9052 case FCmpInst::FCMP_UEQ:
9053 case FCmpInst::FCMP_ONE:
9054 case FCmpInst::FCMP_UNE:
9055 case FCmpInst::FCMP_ORD:
9056 case FCmpInst::FCMP_UNO:
9057 // Look through the fabs() because it doesn't change anything but the sign.
9058 // fabs(X) == 0.0 --> X == 0.0,
9059 // fabs(X) != 0.0 --> X != 0.0
9060 // isnan(fabs(X)) --> isnan(X)
9061 // !isnan(fabs(X) --> !isnan(X)
9062 return replacePredAndOp0(&I, I.getPredicate(), X);
9063
9064 default:
9065 return nullptr;
9066 }
9067}
9068
9069/// Optimize sqrt(X) compared with zero.
9071 Value *X;
9072 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
9073 return nullptr;
9074
9075 if (!match(I.getOperand(1), m_PosZeroFP()))
9076 return nullptr;
9077
9078 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
9079 I.setPredicate(P);
9080 return IC.replaceOperand(I, 0, X);
9081 };
9082
9083 // Clear ninf flag if sqrt doesn't have it.
9084 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
9085 I.setHasNoInfs(false);
9086
9087 switch (I.getPredicate()) {
9088 case FCmpInst::FCMP_OLT:
9089 case FCmpInst::FCMP_UGE:
9090 // sqrt(X) < 0.0 --> false
9091 // sqrt(X) u>= 0.0 --> true
9092 llvm_unreachable("fcmp should have simplified");
9093 case FCmpInst::FCMP_ULT:
9094 case FCmpInst::FCMP_ULE:
9095 case FCmpInst::FCMP_OGT:
9096 case FCmpInst::FCMP_OGE:
9097 case FCmpInst::FCMP_OEQ:
9098 case FCmpInst::FCMP_UNE:
9099 // sqrt(X) u< 0.0 --> X u< 0.0
9100 // sqrt(X) u<= 0.0 --> X u<= 0.0
9101 // sqrt(X) > 0.0 --> X > 0.0
9102 // sqrt(X) >= 0.0 --> X >= 0.0
9103 // sqrt(X) == 0.0 --> X == 0.0
9104 // sqrt(X) u!= 0.0 --> X u!= 0.0
9105 return IC.replaceOperand(I, 0, X);
9106
9107 case FCmpInst::FCMP_OLE:
9108 // sqrt(X) <= 0.0 --> X == 0.0
9109 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
9110 case FCmpInst::FCMP_UGT:
9111 // sqrt(X) u> 0.0 --> X u!= 0.0
9112 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
9113 case FCmpInst::FCMP_UEQ:
9114 // sqrt(X) u== 0.0 --> X u<= 0.0
9115 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
9116 case FCmpInst::FCMP_ONE:
9117 // sqrt(X) != 0.0 --> X > 0.0
9118 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
9119 case FCmpInst::FCMP_ORD:
9120 // !isnan(sqrt(X)) --> X >= 0.0
9121 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
9122 case FCmpInst::FCMP_UNO:
9123 // isnan(sqrt(X)) --> X u< 0.0
9124 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
9125 default:
9126 llvm_unreachable("Unexpected predicate!");
9127 }
9128}
9129
9131 CmpInst::Predicate Pred = I.getPredicate();
9132 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9133
9134 // Canonicalize fneg as Op1.
9135 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
9136 if (match(Op0, m_FNegOrFSubNegZero(m_Value())) &&
9137 !match(Op1, m_FNegOrFSubNegZero(m_Value()))) {
9138 std::swap(Op0, Op1);
9139 Pred = I.getSwappedPredicate();
9140 }
9141
9142 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
9143 if (!match(Op1, m_FNegOrFSubNegZero(m_Specific(Op0))))
9144 return nullptr;
9145
9146 // Replace the negated operand with 0.0:
9147 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
9149 return new FCmpInst(Pred, Op0, Zero, "", &I);
9150}
9151
9153 Constant *RHSC, InstCombinerImpl &CI) {
9154 const CmpInst::Predicate Pred = I.getPredicate();
9155 Value *X = LHSI->getOperand(0);
9156 Value *Y = LHSI->getOperand(1);
9157 switch (Pred) {
9158 default:
9159 break;
9160 case FCmpInst::FCMP_UGT:
9161 case FCmpInst::FCMP_ULT:
9162 case FCmpInst::FCMP_UNE:
9163 case FCmpInst::FCMP_OEQ:
9164 case FCmpInst::FCMP_OGE:
9165 case FCmpInst::FCMP_OLE:
9166 // The optimization is not valid if X and Y are infinities of the same
9167 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
9168 // flag then we can assume we do not have that case. Otherwise we might be
9169 // able to prove that either X or Y is not infinity.
9170 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
9174 break;
9175
9176 [[fallthrough]];
9177 case FCmpInst::FCMP_OGT:
9178 case FCmpInst::FCMP_OLT:
9179 case FCmpInst::FCMP_ONE:
9180 case FCmpInst::FCMP_UEQ:
9181 case FCmpInst::FCMP_UGE:
9182 case FCmpInst::FCMP_ULE:
9183 // fcmp pred (x - y), 0 --> fcmp pred x, y
9184 if (match(RHSC, m_AnyZeroFP()) &&
9185 I.getFunction()->getDenormalMode(
9186 LHSI->getType()->getScalarType()->getFltSemantics()) ==
9188 CI.replaceOperand(I, 0, X);
9189 CI.replaceOperand(I, 1, Y);
9190 I.setHasNoInfs(LHSI->hasNoInfs());
9191 if (LHSI->hasNoNaNs())
9192 I.setHasNoNaNs(true);
9193 return &I;
9194 }
9195 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9196 // where C and Y can't be arbitrary floating-point values.
9197 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9198 // to `1.0f`, so the source compare is false while the rewritten compare is
9199 // true.
9200 // We need to make sure (C - Y) never rounds back to C
9201 const APFloat *C;
9202 Value *IntSrc;
9203 if (match(RHSC, m_APFloat(C)) &&
9204 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
9205 C->isNormal()) {
9206 // Requirements on C and Y:
9207 // 1. C is finite, nonzero, normal.
9208 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9209 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9210 // must be integer-valued with an absolute value of at least 1;
9211 // as long as the step size near C does not exceed 1,
9212 // C - Y cannot be rounded back to C when Y != 0.
9213 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9214 // 0, 0` for ordered and unordered predicates as long as C is finite and
9215 // nonzero.
9216 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9217 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
9218 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
9219 I.setPredicate(I.getSwappedPredicate());
9220 CI.replaceOperand(I, 0, Y);
9221 CI.replaceOperand(I, 1, ZeroC);
9222 return &I;
9223 }
9224 }
9225 break;
9226 }
9227
9228 return nullptr;
9229}
9230
9231/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9232/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9233/// float when the uitofp casts are exact and C is in the valid range.
9234///
9235/// Since exact uitofp means distinct integers map to distinct floats, the only
9236/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9237/// There are no values in the open interval (0, 1), so:
9238/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9239// fabs(..) >= C where C >= 1.0 -> a != b
9240///
9241/// The same logic applies to sitofp.
9243 Value *FAbsArg;
9244 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
9245 return nullptr;
9246
9247 const APFloat *C;
9248 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
9249 return nullptr;
9250
9251 FCmpInst::Predicate Pred = I.getPredicate();
9252 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9253 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9254 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9255 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9256 if (!IsStrictLt && !IsStrictGt && !IsGe)
9257 return nullptr;
9258
9259 APFloat One = APFloat::getOne(C->getSemantics());
9260 APFloat::cmpResult Cmp = C->compare(One);
9261
9262 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9263 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9264 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9265 return nullptr;
9266 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9267 return nullptr;
9268 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9269 return nullptr;
9270 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9271 return nullptr;
9272
9273 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9274 Value *A, *B;
9275 bool IsSigned;
9276 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
9277 IsSigned = false;
9278 } else if (match(FAbsArg,
9280 IsSigned = true;
9281 } else {
9282 return nullptr;
9283 }
9284
9285 // A and B must have the same integer type
9286 if (A->getType() != B->getType())
9287 return nullptr;
9288
9289 Type *FPTy = FAbsArg->getType();
9290 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
9291 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
9292 return nullptr;
9293 ICmpInst::Predicate ResultPred =
9294 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9295 return new ICmpInst(ResultPred, A, B);
9296}
9297
9299 InstCombinerImpl &IC) {
9300 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9301 Type *OpType = LHS->getType();
9302 CmpInst::Predicate Pred = I.getPredicate();
9303
9306
9307 if (!FloorX && !CeilX) {
9310 std::swap(LHS, RHS);
9311 Pred = I.getSwappedPredicate();
9312 }
9313 }
9314
9315 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9316 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9317 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9318 // where pred is oeq, one, ord, ueq, une, uno.
9319 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
9320 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9321 }
9322
9323 switch (Pred) {
9324 case FCmpInst::FCMP_OLE:
9325 // fcmp ole floor(x), x => fcmp ord x, 0
9326 if (FloorX)
9328 "", &I);
9329 break;
9330 case FCmpInst::FCMP_OGT:
9331 // fcmp ogt floor(x), x => false
9332 if (FloorX)
9333 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9334 break;
9335 case FCmpInst::FCMP_OGE:
9336 // fcmp oge ceil(x), x => fcmp ord x, 0
9337 if (CeilX)
9339 "", &I);
9340 break;
9341 case FCmpInst::FCMP_OLT:
9342 // fcmp olt ceil(x), x => false
9343 if (CeilX)
9344 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9345 break;
9346 case FCmpInst::FCMP_ULE:
9347 // fcmp ule floor(x), x => true
9348 if (FloorX)
9349 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9350 break;
9351 case FCmpInst::FCMP_UGT:
9352 // fcmp ugt floor(x), x => fcmp uno x, 0
9353 if (FloorX)
9355 "", &I);
9356 break;
9357 case FCmpInst::FCMP_UGE:
9358 // fcmp uge ceil(x), x => true
9359 if (CeilX)
9360 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9361 break;
9362 case FCmpInst::FCMP_ULT:
9363 // fcmp ult ceil(x), x => fcmp uno x, 0
9364 if (CeilX)
9366 "", &I);
9367 break;
9368 default:
9369 break;
9370 }
9371
9372 return nullptr;
9373}
9374
9375/// Returns true if a select that implements a min/max is redundant and
9376/// select result can be replaced with its non-constant operand, e.g.,
9377/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9378/// where C is the FP constant equal to the minimum integer value
9379/// representable by A.
9381 Value *B) {
9382 const APFloat *APF;
9383 if (!match(B, m_APFloat(APF)))
9384 return false;
9385
9386 auto *I = dyn_cast<Instruction>(A);
9387 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9388 I->getOpcode() == Instruction::UIToFP))
9389 return false;
9390
9391 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9392 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9393 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9394 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9395 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9396 APSInt ConvertedInt(BitWidth, IsUnsigned);
9397 bool IsExact;
9399 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9400 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9401}
9402
9404 bool Changed = false;
9405
9406 /// Orders the operands of the compare so that they are listed from most
9407 /// complex to least complex. This puts constants before unary operators,
9408 /// before binary operators.
9409 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9410 I.swapOperands();
9411 Changed = true;
9412 }
9413
9414 const CmpInst::Predicate Pred = I.getPredicate();
9415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9416 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9417 SQ.getWithInstruction(&I)))
9418 return replaceInstUsesWith(I, V);
9419
9420 // Simplify 'fcmp pred X, X'
9421 Type *OpType = Op0->getType();
9422 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9423 if (Op0 == Op1) {
9424 switch (Pred) {
9425 default:
9426 break;
9427 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9428 case FCmpInst::FCMP_ULT: // True if unordered or less than
9429 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9430 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9431 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9432 I.setPredicate(FCmpInst::FCMP_UNO);
9433 I.setOperand(1, Constant::getNullValue(OpType));
9434 return &I;
9435
9436 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9437 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9438 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9439 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9440 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9441 I.setPredicate(FCmpInst::FCMP_ORD);
9442 I.setOperand(1, Constant::getNullValue(OpType));
9443 return &I;
9444 }
9445 }
9446
9447 if (I.isCommutative()) {
9448 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9449 replaceOperand(I, 0, Pair->first);
9450 replaceOperand(I, 1, Pair->second);
9451 return &I;
9452 }
9453 }
9454
9455 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9456 // then canonicalize the operand to 0.0.
9457 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9458 if (!match(Op0, m_PosZeroFP()) &&
9459 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9460 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9461
9462 if (!match(Op1, m_PosZeroFP()) &&
9463 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9464 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9465 }
9466
9467 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9468 Value *X, *Y;
9469 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
9470 if (match(Op0, m_FNegOrFSubNegZero(m_Value(X))) &&
9472 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9473
9475 return R;
9476
9477 // Test if the FCmpInst instruction is used exclusively by a select as
9478 // part of a minimum or maximum operation. If so, refrain from doing
9479 // any other folding. This helps out other analyses which understand
9480 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9481 // and CodeGen. And in this case, at least one of the comparison
9482 // operands has at least one user besides the compare (the select),
9483 // which would often largely negate the benefit of folding anyway.
9484 if (I.hasOneUse())
9485 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9486 Value *A, *B;
9488 bool IsRedundantMinMaxClamp =
9489 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9491 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9492 return nullptr;
9493 }
9494
9495 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9496 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9497 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9498 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9499
9500 // Canonicalize:
9501 // fcmp olt X, +inf -> fcmp one X, +inf
9502 // fcmp ole X, +inf -> fcmp ord X, 0
9503 // fcmp ogt X, +inf -> false
9504 // fcmp oge X, +inf -> fcmp oeq X, +inf
9505 // fcmp ult X, +inf -> fcmp une X, +inf
9506 // fcmp ule X, +inf -> true
9507 // fcmp ugt X, +inf -> fcmp uno X, 0
9508 // fcmp uge X, +inf -> fcmp ueq X, +inf
9509 // fcmp olt X, -inf -> false
9510 // fcmp ole X, -inf -> fcmp oeq X, -inf
9511 // fcmp ogt X, -inf -> fcmp one X, -inf
9512 // fcmp oge X, -inf -> fcmp ord X, 0
9513 // fcmp ult X, -inf -> fcmp uno X, 0
9514 // fcmp ule X, -inf -> fcmp ueq X, -inf
9515 // fcmp ugt X, -inf -> fcmp une X, -inf
9516 // fcmp uge X, -inf -> true
9517 const APFloat *C;
9518 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9519 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9520 default:
9521 break;
9522 case FCmpInst::FCMP_ORD:
9523 case FCmpInst::FCMP_UNO:
9526 case FCmpInst::FCMP_OGT:
9527 case FCmpInst::FCMP_ULE:
9528 llvm_unreachable("Should be simplified by InstSimplify");
9529 case FCmpInst::FCMP_OLT:
9530 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9531 case FCmpInst::FCMP_OLE:
9532 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9533 "", &I);
9534 case FCmpInst::FCMP_OGE:
9535 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9536 case FCmpInst::FCMP_ULT:
9537 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9538 case FCmpInst::FCMP_UGT:
9539 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9540 "", &I);
9541 case FCmpInst::FCMP_UGE:
9542 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9543 }
9544 }
9545
9546 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9547 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9548 if (match(Op1, m_PosZeroFP()) &&
9550 X->getType()->isIntOrIntVectorTy() &&
9551 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9552 .inputsMayBeZero()) {
9554 if (Pred == FCmpInst::FCMP_OEQ)
9555 IntPred = ICmpInst::ICMP_EQ;
9556 else if (Pred == FCmpInst::FCMP_UNE)
9557 IntPred = ICmpInst::ICMP_NE;
9558
9559 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9560 Type *IntTy = X->getType();
9561 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9562 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9563 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9564 }
9565 }
9566
9567 // Handle fcmp with instruction LHS and constant RHS.
9568 Instruction *LHSI;
9569 Constant *RHSC;
9570 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9571 switch (LHSI->getOpcode()) {
9572 case Instruction::Select:
9573 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9574 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
9575 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9576 match(LHSI,
9578 return replaceOperand(I, 0, X);
9580 return NV;
9581 break;
9582 case Instruction::FSub:
9583 if (LHSI->hasOneUse())
9584 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9585 return NV;
9586 break;
9587 case Instruction::PHI:
9588 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9589 return NV;
9590 break;
9591 case Instruction::SIToFP:
9592 case Instruction::UIToFP:
9593 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9594 return NV;
9595 break;
9596 case Instruction::FDiv:
9597 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9598 return NV;
9599 break;
9600 case Instruction::Load:
9602 cast<LoadInst>(LHSI), I.getPredicate(), RHSC, I))
9603 return Res;
9604 break;
9605 case Instruction::FPTrunc:
9606 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9607 return NV;
9608 break;
9609 }
9610 }
9611
9612 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9613 return R;
9614
9615 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9616 return R;
9617
9618 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9619 return R;
9620
9621 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9622 return R;
9623
9625 return R;
9626
9627 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
9628 if (match(Op0, m_FNegOrFSubNegZero(m_Value(X)))) {
9629 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9630 Constant *C;
9631 if (match(Op1, m_Constant(C)))
9632 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9633 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9634 }
9635
9636 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9637 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9638 return new FCmpInst(Pred, X, Op1, "", &I);
9639
9640 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9641 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9642 return new FCmpInst(Pred, Op0, Y, "", &I);
9643
9644 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9645 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9646 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9647 X->getType() == Y->getType())
9648 return new FCmpInst(Pred, X, Y, "", &I);
9649
9650 if (match(Op0, m_FPExt(m_Value(X)))) {
9651 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9652 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9653 return new FCmpInst(Pred, X, Y, "", &I);
9654
9655 const APFloat *C;
9656 if (match(Op1, m_APFloat(C))) {
9657 const fltSemantics &FPSem =
9658 X->getType()->getScalarType()->getFltSemantics();
9659 bool Lossy;
9660 APFloat TruncC = *C;
9662
9663 if (Lossy) {
9664 // X can't possibly equal the higher-precision constant, so reduce any
9665 // equality comparison.
9666 // TODO: Other predicates can be handled via getFCmpCode().
9667 switch (Pred) {
9668 case FCmpInst::FCMP_OEQ:
9669 // X is ordered and equal to an impossible constant --> false
9670 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9671 case FCmpInst::FCMP_ONE:
9672 // X is ordered and not equal to an impossible constant --> ordered
9673 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9674 ConstantFP::getZero(X->getType()));
9675 case FCmpInst::FCMP_UEQ:
9676 // X is unordered or equal to an impossible constant --> unordered
9677 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9678 ConstantFP::getZero(X->getType()));
9679 case FCmpInst::FCMP_UNE:
9680 // X is unordered or not equal to an impossible constant --> true
9681 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9682 default:
9683 break;
9684 }
9685 }
9686
9687 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9688 // Avoid lossy conversions and denormals.
9689 // Zero is a special case that's OK to convert.
9690 APFloat Fabs = TruncC;
9691 Fabs.clearSign();
9692 if (!Lossy &&
9693 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9694 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9695 return new FCmpInst(Pred, X, NewC, "", &I);
9696 }
9697 }
9698 }
9699
9700 // Convert a sign-bit test of an FP value into a cast and integer compare.
9701 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9702 // TODO: Handle non-zero compare constants.
9703 // TODO: Handle other predicates.
9705 m_Value(X)))) &&
9706 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9707 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9708 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9709 IntType = VectorType::get(IntType, VecTy->getElementCount());
9710
9711 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9712 if (Pred == FCmpInst::FCMP_OLT) {
9713 Value *IntX = Builder.CreateBitCast(X, IntType);
9714 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9715 ConstantInt::getNullValue(IntType));
9716 }
9717 }
9718
9719 {
9720 Value *CanonLHS = nullptr;
9722 // (canonicalize(x) == x) => (x == x)
9723 if (CanonLHS == Op1)
9724 return new FCmpInst(Pred, Op1, Op1, "", &I);
9725
9726 Value *CanonRHS = nullptr;
9728 // (x == canonicalize(x)) => (x == x)
9729 if (CanonRHS == Op0)
9730 return new FCmpInst(Pred, Op0, Op0, "", &I);
9731
9732 // (canonicalize(x) == canonicalize(y)) => (x == y)
9733 if (CanonLHS && CanonRHS)
9734 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9735 }
9736
9737 if (I.getType()->isVectorTy())
9738 if (Instruction *Res = foldVectorCmp(I, Builder))
9739 return Res;
9740
9741 return Changed ? &I : nullptr;
9742}
SDValue Pred
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 a class to represent arbitrary precision integral constant values and operations...
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:665
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 bool hasNoWrapProblem(const BinaryOperator &BO, CmpInst::Predicate Pred, bool &HasNSW, bool &HasNUW)
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:550
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
#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)
int64_t C1
int64_t C0
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:170
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:369
static constexpr roundingMode rmTowardZero
Definition APFloat.h:383
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:613
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
void clearSign()
Definition APFloat.h:1435
bool isNaN() const
Definition APFloat.h:1614
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1225
bool isZero() const
Definition APFloat.h:1612
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1295
APInt bitcastToAPInt() const
Definition APFloat.h:1508
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1275
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1469
opStatus next(bool nextDown)
Definition APFloat.h:1391
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1235
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:6032
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1385
bool isInfinity() const
Definition APFloat.h:1613
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:61
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:236
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 std::optional< ConstGlobalLoad > fromLoadInst(LoadInst *LI)
Analyze a load instruction to a linear expression that loads from a constant global.
Definition Loads.cpp:1073
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 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 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:44
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:65
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:62
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:63
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
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
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
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:111
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Definition IRBuilder.h:2568
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1572
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:486
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:2990
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 * foldCmpLoadFromIndexedGlobal(LoadInst *LI, CmpPredicate Pred, Constant *RHSC, Instruction &CtxI, ConstantInt *AndCst=nullptr)
Try to fold cmp pred (load (gep GV, ...)), cmpcst where GV is a global variable with a constant initi...
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 * 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 matchCommonBinOpOperands(Value *Op0, Value *Op1, CmpInst::Predicate Pred, Value *&LHS, Value *&RHS, const SimplifyQuery &Q)
Match Op0 Pred Op1 on binops with a removable common operand.
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 * foldICmpAddLikeConstant(ICmpInst &Cmp, Value *X, const APInt &C2, bool HasNUW, bool HasNSW, const APInt &C)
Fold icmp pred (add X, C2), C using the no-wrap flags of the add.
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
Module & getModule() 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:333
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.
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
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
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.
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
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
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
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:222
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:150
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:707
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:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
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:201
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#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:2810
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:2828
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)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
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)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
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)
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.
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 isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
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:1740
LLVM_ABI bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
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.
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 isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
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:1749
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 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.
@ 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
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
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:881
#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 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
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:344
Capture information for a specific Use.