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) {
87 if (!ICmpInst::isSigned(Pred))
88 return false;
89
90 if (C.isZero())
91 return ICmpInst::isRelational(Pred);
92
93 if (C.isOne()) {
94 if (Pred == ICmpInst::ICMP_SLT) {
95 Pred = ICmpInst::ICMP_SLE;
96 return true;
97 }
98 } else if (C.isAllOnes()) {
99 if (Pred == ICmpInst::ICMP_SGT) {
100 Pred = ICmpInst::ICMP_SGE;
101 return true;
102 }
103 }
104
105 return false;
106}
107
108/// This is called when we see this pattern:
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.
123 Instruction &CtxI, ConstantInt *AndCst) {
125 if (LI->isVolatile() || !GV || !GV->isConstant() ||
126 !GV->hasDefinitiveInitializer())
127 return nullptr;
128
129 Type *EltTy = LI->getType();
130 TypeSize EltSize = DL.getTypeStoreSize(EltTy);
131 if (EltSize.isScalable())
132 return nullptr;
133
135 if (!Expr.Index || Expr.BasePtr != GV || Expr.Offset.getBitWidth() > 64)
136 return nullptr;
137
138 Constant *Init = GV->getInitializer();
139 TypeSize GlobalSize = DL.getTypeAllocSize(Init->getType());
140
141 Value *Idx = Expr.Index;
142 const APInt &Stride = Expr.Scale;
143 const APInt &ConstOffset = Expr.Offset;
144
145 // Allow an additional context offset, but only within the stride.
146 if (!ConstOffset.ult(Stride))
147 return nullptr;
148
149 // Don't handle overlapping loads for now.
150 if (!Stride.uge(EltSize.getFixedValue()))
151 return nullptr;
152
153 // With nusw (implied by inbounds), Idx * Stride does not wrap as a signed
154 // quantity, and the following enumeration over ArrayElementCount is valid so
155 // long as the stride is positive. Conversely, without nusw, Idx * Stride is
156 // computed modulo 2^N (see MaskIdx below), and the masking in MaskIdx below
157 // is only exact when the stride is a power of two.
158 bool StrideIsValid = Expr.Flags.hasNoUnsignedSignedWrap()
159 ? !Stride.isNegative()
160 : Stride.isPowerOf2();
161 if (!StrideIsValid)
162 return nullptr;
163
164 // Don't blow up on huge arrays.
165 uint64_t ArrayElementCount =
166 divideCeil((GlobalSize.getFixedValue() - ConstOffset.getZExtValue()),
167 Stride.getZExtValue());
168 if (ArrayElementCount > CLOpts.maxarray_size)
169 return nullptr;
170
171 enum { Overdefined = -3, Undefined = -2 };
172
173 // Variables for our state machines.
174
175 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
176 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
177 // and 87 is the second (and last) index. FirstTrueElement is -2 when
178 // undefined, otherwise set to the first true element. SecondTrueElement is
179 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
180 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
181
182 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
183 // form "i != 47 & i != 87". Same state transitions as for true elements.
184 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
185
186 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
187 /// define a state machine that triggers for ranges of values that the index
188 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
189 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
190 /// index in the range (inclusive). We use -2 for undefined here because we
191 /// use relative comparisons and don't want 0-1 to match -1.
192 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
193
194 // MagicBitvector - This is a magic bitvector where we set a bit if the
195 // comparison is true for element 'i'. If there are 64 elements or less in
196 // the array, this will fully represent all the comparison results.
197 uint64_t MagicBitvector = 0;
198
199 // Scan the array and see if one of our patterns matches.
200 APInt Offset = ConstOffset;
201 for (unsigned i = 0, e = ArrayElementCount; i != e; ++i, Offset += Stride) {
203 if (!Elt)
204 return nullptr;
205
206 // If the element is masked, handle it.
207 if (AndCst) {
208 Elt = ConstantFoldBinaryOpOperands(Instruction::And, Elt, AndCst, DL);
209 if (!Elt)
210 return nullptr;
211 }
212
213 // Find out if the comparison would be true or false for the i'th element.
214 Constant *C = ConstantFoldCompareInstOperands(Pred, Elt, RHSC, DL, &TLI);
215 if (!C)
216 return nullptr;
217
218 // If the result is undef for this element, ignore it.
219 if (isa<UndefValue>(C)) {
220 // Extend range state machines to cover this element in case there is an
221 // undef in the middle of the range.
222 if (TrueRangeEnd == (int)i - 1)
223 TrueRangeEnd = i;
224 if (FalseRangeEnd == (int)i - 1)
225 FalseRangeEnd = i;
226 continue;
227 }
228
229 // If we can't compute the result for any of the elements, we have to give
230 // up evaluating the entire conditional.
231 if (!isa<ConstantInt>(C))
232 return nullptr;
233
234 // Otherwise, we know if the comparison is true or false for this element,
235 // update our state machines.
236 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
237
238 // State machine for single/double/range index comparison.
239 if (IsTrueForElt) {
240 // Update the TrueElement state machine.
241 if (FirstTrueElement == Undefined)
242 FirstTrueElement = TrueRangeEnd = i; // First true element.
243 else {
244 // Update double-compare state machine.
245 if (SecondTrueElement == Undefined)
246 SecondTrueElement = i;
247 else
248 SecondTrueElement = Overdefined;
249
250 // Update range state machine.
251 if (TrueRangeEnd == (int)i - 1)
252 TrueRangeEnd = i;
253 else
254 TrueRangeEnd = Overdefined;
255 }
256 } else {
257 // Update the FalseElement state machine.
258 if (FirstFalseElement == Undefined)
259 FirstFalseElement = FalseRangeEnd = i; // First false element.
260 else {
261 // Update double-compare state machine.
262 if (SecondFalseElement == Undefined)
263 SecondFalseElement = i;
264 else
265 SecondFalseElement = Overdefined;
266
267 // Update range state machine.
268 if (FalseRangeEnd == (int)i - 1)
269 FalseRangeEnd = i;
270 else
271 FalseRangeEnd = Overdefined;
272 }
273 }
274
275 // If this element is in range, update our magic bitvector.
276 if (i < 64 && IsTrueForElt)
277 MagicBitvector |= 1ULL << i;
278
279 // If all of our states become overdefined, bail out early. Since the
280 // predicate is expensive, only check it every 8 elements. This is only
281 // really useful for really huge arrays.
282 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
283 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
284 FalseRangeEnd == Overdefined)
285 return nullptr;
286 }
287
288 // Now that we've scanned the entire array, emit our new comparison(s). We
289 // order the state machines in complexity of the generated code.
290
291 // If inbounds keyword is not present, Idx * Stride can overflow.
292 // Let's assume that Stride is 2 and the wanted value is at offset 0.
293 // Then, there are two possible values for Idx to match offset 0:
294 // 0x00..00, 0x80..00.
295 // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
296 // comparison is false if Idx was 0x80..00.
297 // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
298 auto MaskIdx = [&](Value *Idx) {
299 if (!Expr.Flags.isInBounds() && Stride.countr_zero() != 0) {
300 Value *Mask = Constant::getAllOnesValue(Idx->getType());
301 Mask = Builder.CreateLShr(Mask, Stride.countr_zero());
302 Idx = Builder.CreateAnd(Idx, Mask);
303 }
304 return Idx;
305 };
306
307 // If the comparison is only true for one or two elements, emit direct
308 // comparisons.
309 if (SecondTrueElement != Overdefined) {
310 Idx = MaskIdx(Idx);
311 // None true -> false.
312 if (FirstTrueElement == Undefined)
313 return replaceInstUsesWith(CtxI, Builder.getFalse());
314
315 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
316
317 // True for one element -> 'i == 47'.
318 if (SecondTrueElement == Undefined)
319 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
320
321 // True for two elements -> 'i == 47 | i == 72'.
322 Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
323 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
324 Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
325 return BinaryOperator::CreateOr(C1, C2);
326 }
327
328 // If the comparison is only false for one or two elements, emit direct
329 // comparisons.
330 if (SecondFalseElement != Overdefined) {
331 Idx = MaskIdx(Idx);
332 // None false -> true.
333 if (FirstFalseElement == Undefined)
334 return replaceInstUsesWith(CtxI, Builder.getTrue());
335
336 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
337
338 // False for one element -> 'i != 47'.
339 if (SecondFalseElement == Undefined)
340 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
341
342 // False for two elements -> 'i != 47 & i != 72'.
343 Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
344 Value *SecondFalseIdx =
345 ConstantInt::get(Idx->getType(), SecondFalseElement);
346 Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
347 return BinaryOperator::CreateAnd(C1, C2);
348 }
349
350 // If the comparison can be replaced with a range comparison for the elements
351 // where it is true, emit the range check.
352 if (TrueRangeEnd != Overdefined) {
353 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
354 Idx = MaskIdx(Idx);
355
356 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
357 if (FirstTrueElement) {
358 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstTrueElement);
359 Idx = Builder.CreateAdd(Idx, Offs);
360 }
361
362 Value *End =
363 ConstantInt::get(Idx->getType(), TrueRangeEnd - FirstTrueElement + 1);
364 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
365 }
366
367 // False range check.
368 if (FalseRangeEnd != Overdefined) {
369 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
370 Idx = MaskIdx(Idx);
371 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
372 if (FirstFalseElement) {
373 Value *Offs = ConstantInt::getSigned(Idx->getType(), -FirstFalseElement);
374 Idx = Builder.CreateAdd(Idx, Offs);
375 }
376
377 Value *End =
378 ConstantInt::get(Idx->getType(), FalseRangeEnd - FirstFalseElement);
379 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
380 }
381
382 // If a magic bitvector captures the entire comparison state
383 // of this load, replace it with computation that does:
384 // ((magic_cst >> i) & 1) != 0
385 {
386 Type *Ty = nullptr;
387
388 // Look for an appropriate type:
389 // - The type of Idx if the magic fits
390 // - The smallest fitting legal type
391 if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
392 Ty = Idx->getType();
393 else
394 Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
395
396 if (Ty) {
397 Idx = MaskIdx(Idx);
398 Value *V = Builder.CreateIntCast(Idx, Ty, false);
399 V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
400 V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
401 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
402 }
403 }
404
405 return nullptr;
406}
407
408/// Returns true if we can rewrite Start as a GEP with pointer Base
409/// and some integer offset. The nodes that need to be re-written
410/// for this transformation will be added to Explored.
412 const DataLayout &DL,
413 SetVector<Value *> &Explored) {
414 SmallVector<Value *, 16> WorkList(1, Start);
415 Explored.insert(Base);
416
417 // The following traversal gives us an order which can be used
418 // when doing the final transformation. Since in the final
419 // transformation we create the PHI replacement instructions first,
420 // we don't have to get them in any particular order.
421 //
422 // However, for other instructions we will have to traverse the
423 // operands of an instruction first, which means that we have to
424 // do a post-order traversal.
425 while (!WorkList.empty()) {
427
428 while (!WorkList.empty()) {
429 if (Explored.size() >= 100)
430 return false;
431
432 Value *V = WorkList.back();
433
434 if (Explored.contains(V)) {
435 WorkList.pop_back();
436 continue;
437 }
438
440 // We've found some value that we can't explore which is different from
441 // the base. Therefore we can't do this transformation.
442 return false;
443
444 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
445 // Only allow inbounds GEPs with at most one variable offset.
446 auto IsNonConst = [](Value *V) { return !isa<ConstantInt>(V); };
447 if (!GEP->isInBounds() || count_if(GEP->indices(), IsNonConst) > 1)
448 return false;
449
450 NW = NW.intersectForOffsetAdd(GEP->getNoWrapFlags());
451 if (!Explored.contains(GEP->getOperand(0)))
452 WorkList.push_back(GEP->getOperand(0));
453 }
454
455 if (WorkList.back() == V) {
456 WorkList.pop_back();
457 // We've finished visiting this node, mark it as such.
458 Explored.insert(V);
459 }
460
461 if (auto *PN = dyn_cast<PHINode>(V)) {
462 // We cannot transform PHIs on unsplittable basic blocks.
463 if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
464 return false;
465 Explored.insert(PN);
466 PHIs.insert(PN);
467 }
468 }
469
470 // Explore the PHI nodes further.
471 for (auto *PN : PHIs)
472 for (Value *Op : PN->incoming_values())
473 if (!Explored.contains(Op))
474 WorkList.push_back(Op);
475 }
476
477 // Make sure that we can do this. Since we can't insert GEPs in a basic
478 // block before a PHI node, we can't easily do this transformation if
479 // we have PHI node users of transformed instructions.
480 for (Value *Val : Explored) {
481 for (Value *Use : Val->uses()) {
482
483 auto *PHI = dyn_cast<PHINode>(Use);
484 auto *Inst = dyn_cast<Instruction>(Val);
485
486 if (Inst == Base || Inst == PHI || !Inst || !PHI ||
487 !Explored.contains(PHI))
488 continue;
489
490 if (PHI->getParent() == Inst->getParent())
491 return false;
492 }
493 }
494 return true;
495}
496
497// Sets the appropriate insert point on Builder where we can add
498// a replacement Instruction for V (if that is possible).
499static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
500 bool Before = true) {
501 if (auto *PHI = dyn_cast<PHINode>(V)) {
502 BasicBlock *Parent = PHI->getParent();
503 Builder.SetInsertPoint(Parent->getFirstInsertionPt());
504 return;
505 }
506 if (auto *I = dyn_cast<Instruction>(V)) {
507 if (!Before)
508 I = &*std::next(I->getIterator());
509 Builder.SetInsertPoint(I);
510 return;
511 }
512 if (auto *A = dyn_cast<Argument>(V)) {
513 // Set the insertion point in the entry block.
514 BasicBlock &Entry = A->getParent()->getEntryBlock();
515 Builder.SetInsertPoint(Entry.getFirstInsertionPt());
516 return;
517 }
518 // Otherwise, this is a constant and we don't need to set a new
519 // insertion point.
520 assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
521}
522
523/// Returns a re-written value of Start as an indexed GEP using Base as a
524/// pointer.
526 const DataLayout &DL,
527 SetVector<Value *> &Explored,
528 InstCombiner &IC) {
529 // Perform all the substitutions. This is a bit tricky because we can
530 // have cycles in our use-def chains.
531 // 1. Create the PHI nodes without any incoming values.
532 // 2. Create all the other values.
533 // 3. Add the edges for the PHI nodes.
534 // 4. Emit GEPs to get the original pointers.
535 // 5. Remove the original instructions.
536 Type *IndexType = IntegerType::get(
537 Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
538
540 NewInsts[Base] = ConstantInt::getNullValue(IndexType);
541
542 // Create the new PHI nodes, without adding any incoming values.
543 for (Value *Val : Explored) {
544 if (Val == Base)
545 continue;
546 // Create empty phi nodes. This avoids cyclic dependencies when creating
547 // the remaining instructions.
548 if (auto *PHI = dyn_cast<PHINode>(Val))
549 NewInsts[PHI] =
550 PHINode::Create(IndexType, PHI->getNumIncomingValues(),
551 PHI->getName() + ".idx", PHI->getIterator());
552 }
553 IRBuilder<> Builder(IC.getModule());
554
555 // Create all the other instructions.
556 for (Value *Val : Explored) {
557 if (NewInsts.contains(Val))
558 continue;
559
560 if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
561 setInsertionPoint(Builder, GEP);
562 Value *Op = NewInsts[GEP->getOperand(0)];
563 Value *OffsetV = emitGEPOffset(&Builder, DL, GEP);
565 NewInsts[GEP] = OffsetV;
566 else
567 NewInsts[GEP] = Builder.CreateAdd(
568 Op, OffsetV, GEP->getOperand(0)->getName() + ".add",
569 /*NUW=*/NW.hasNoUnsignedWrap(),
570 /*NSW=*/NW.hasNoUnsignedSignedWrap());
571 continue;
572 }
573 if (isa<PHINode>(Val))
574 continue;
575
576 llvm_unreachable("Unexpected instruction type");
577 }
578
579 // Add the incoming values to the PHI nodes.
580 for (Value *Val : Explored) {
581 if (Val == Base)
582 continue;
583 // All the instructions have been created, we can now add edges to the
584 // phi nodes.
585 if (auto *PHI = dyn_cast<PHINode>(Val)) {
586 PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
587 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
588 Value *NewIncoming = PHI->getIncomingValue(I);
589
590 auto It = NewInsts.find(NewIncoming);
591 if (It != NewInsts.end())
592 NewIncoming = It->second;
593
594 NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
595 }
596 }
597 }
598
599 for (Value *Val : Explored) {
600 if (Val == Base)
601 continue;
602
603 setInsertionPoint(Builder, Val, false);
604 // Create GEP for external users.
605 Value *NewVal = Builder.CreateGEP(Builder.getInt8Ty(), Base, NewInsts[Val],
606 Val->getName() + ".ptr", NW);
607 IC.replaceInstUsesWith(*cast<Instruction>(Val), NewVal);
608 // Add old instruction to worklist for DCE. We don't directly remove it
609 // here because the original compare is one of the users.
611 }
612
613 return NewInsts[Start];
614}
615
616/// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
617/// We can look through PHIs, GEPs and casts in order to determine a common base
618/// between GEPLHS and RHS.
621 const DataLayout &DL,
622 InstCombiner &IC) {
623 // FIXME: Support vector of pointers.
624 if (GEPLHS->getType()->isVectorTy())
625 return nullptr;
626
627 if (!GEPLHS->hasAllConstantIndices())
628 return nullptr;
629
630 APInt Offset(DL.getIndexTypeSizeInBits(GEPLHS->getType()), 0);
631 Value *PtrBase =
633 /*AllowNonInbounds*/ false);
634
635 // Bail if we looked through addrspacecast.
636 if (PtrBase->getType() != GEPLHS->getType())
637 return nullptr;
638
639 // The set of nodes that will take part in this transformation.
640 SetVector<Value *> Nodes;
641 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags();
642 if (!canRewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes))
643 return nullptr;
644
645 // We know we can re-write this as
646 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
647 // Since we've only looked through inbouds GEPs we know that we
648 // can't have overflow on either side. We can therefore re-write
649 // this as:
650 // OFFSET1 cmp OFFSET2
651 Value *NewRHS = rewriteGEPAsOffset(RHS, PtrBase, NW, DL, Nodes, IC);
652
653 // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
654 // GEP having PtrBase as the pointer base, and has returned in NewRHS the
655 // offset. Since Index is the offset of LHS to the base pointer, we will now
656 // compare the offsets instead of comparing the pointers.
658 IC.Builder.getInt(Offset), NewRHS);
659}
660
661/// Fold comparisons between a GEP instruction and something else. At this point
662/// we know that the GEP is on the LHS of the comparison.
665 // Don't transform signed compares of GEPs into index compares. Even if the
666 // GEP is inbounds, the final add of the base pointer can have signed overflow
667 // and would change the result of the icmp.
668 // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
669 // the maximum signed value for the pointer type.
671 return nullptr;
672
673 // Look through bitcasts and addrspacecasts. We do not however want to remove
674 // 0 GEPs.
675 if (!isa<GetElementPtrInst>(RHS))
676 RHS = RHS->stripPointerCasts();
677
678 auto CanFold = [Cond](GEPNoWrapFlags NW) {
680 return true;
681
682 // Unsigned predicates can be folded if the GEPs have *any* nowrap flags.
684 return NW != GEPNoWrapFlags::none();
685 };
686
687 auto NewICmp = [Cond](GEPNoWrapFlags NW, Value *Op1, Value *Op2) {
688 if (!NW.hasNoUnsignedWrap()) {
689 // Convert signed to unsigned comparison.
690 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Op1, Op2);
691 }
692
693 auto *I = new ICmpInst(Cond, Op1, Op2);
694 I->setSameSign(NW.hasNoUnsignedSignedWrap());
695 return I;
696 };
697
699 if (Base.Ptr == RHS && CanFold(Base.LHSNW) && !Base.isExpensive()) {
700 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
701 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
702 Value *Offset =
703 EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, /*RewriteGEPs=*/true);
704 return NewICmp(Base.LHSNW, Offset,
705 Constant::getNullValue(Offset->getType()));
706 }
707
708 if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
710 !NullPointerIsDefined(I.getFunction(),
711 RHS->getType()->getPointerAddressSpace())) {
712 // For most address spaces, an allocation can't be placed at null, but null
713 // itself is treated as a 0 size allocation in the in bounds rules. Thus,
714 // the only valid inbounds address derived from null, is null itself.
715 // Thus, we have four cases to consider:
716 // 1) Base == nullptr, Offset == 0 -> inbounds, null
717 // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
718 // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
719 // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
720 //
721 // (Note if we're indexing a type of size 0, that simply collapses into one
722 // of the buckets above.)
723 //
724 // In general, we're allowed to make values less poison (i.e. remove
725 // sources of full UB), so in this case, we just select between the two
726 // non-poison cases (1 and 4 above).
727 //
728 // For vectors, we apply the same reasoning on a per-lane basis.
729 auto *Base = GEPLHS->getPointerOperand();
730 if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
731 auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
732 Base = Builder.CreateVectorSplat(EC, Base);
733 }
734 return new ICmpInst(Cond, Base,
736 cast<Constant>(RHS), Base->getType()));
737 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
738 GEPNoWrapFlags NW = GEPLHS->getNoWrapFlags() & GEPRHS->getNoWrapFlags();
739
740 // If the base pointers are different, but the indices are the same, just
741 // compare the base pointer.
742 if (GEPLHS->getOperand(0) != GEPRHS->getOperand(0)) {
743 bool IndicesTheSame =
744 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
745 GEPLHS->getPointerOperand()->getType() ==
746 GEPRHS->getPointerOperand()->getType() &&
747 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
748 if (IndicesTheSame)
749 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
750 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
751 IndicesTheSame = false;
752 break;
753 }
754
755 // If all indices are the same, just compare the base pointers.
756 Type *BaseType = GEPLHS->getOperand(0)->getType();
757 if (IndicesTheSame &&
758 CmpInst::makeCmpResultType(BaseType) == I.getType() && CanFold(NW))
759 return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
760
761 // If we're comparing GEPs with two base pointers that only differ in type
762 // and both GEPs have only constant indices or just one use, then fold
763 // the compare with the adjusted indices.
764 // FIXME: Support vector of pointers.
765 if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
766 (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
767 (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
768 GEPLHS->getOperand(0)->stripPointerCasts() ==
769 GEPRHS->getOperand(0)->stripPointerCasts() &&
770 !GEPLHS->getType()->isVectorTy()) {
771 Value *LOffset = EmitGEPOffset(GEPLHS);
772 Value *ROffset = EmitGEPOffset(GEPRHS);
773
774 // If we looked through an addrspacecast between different sized address
775 // spaces, the LHS and RHS pointers are different sized
776 // integers. Truncate to the smaller one.
777 Type *LHSIndexTy = LOffset->getType();
778 Type *RHSIndexTy = ROffset->getType();
779 if (LHSIndexTy != RHSIndexTy) {
780 if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
781 RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
782 ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
783 } else
784 LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
785 }
786
788 LOffset, ROffset);
789 return replaceInstUsesWith(I, Cmp);
790 }
791 }
792
793 if (GEPLHS->getOperand(0) == GEPRHS->getOperand(0) &&
794 GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
795 GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
796 // If the GEPs only differ by one index, compare it.
797 unsigned NumDifferences = 0; // Keep track of # differences.
798 unsigned DiffOperand = 0; // The operand that differs.
799 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
800 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
801 Type *LHSType = GEPLHS->getOperand(i)->getType();
802 Type *RHSType = GEPRHS->getOperand(i)->getType();
803 // FIXME: Better support for vector of pointers.
804 if (LHSType->getPrimitiveSizeInBits() !=
805 RHSType->getPrimitiveSizeInBits() ||
806 (GEPLHS->getType()->isVectorTy() &&
807 (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
808 // Irreconcilable differences.
809 NumDifferences = 2;
810 break;
811 }
812
813 if (NumDifferences++)
814 break;
815 DiffOperand = i;
816 }
817
818 if (NumDifferences == 0) // SAME GEP?
819 return replaceInstUsesWith(
820 I, // No comparison is needed here.
821 ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
822 // If two GEPs only differ by an index, compare them.
823 // Note that nowrap flags are always needed when comparing two indices.
824 else if (NumDifferences == 1 && NW != GEPNoWrapFlags::none()) {
825 Value *LHSV = GEPLHS->getOperand(DiffOperand);
826 Value *RHSV = GEPRHS->getOperand(DiffOperand);
827 return NewICmp(NW, LHSV, RHSV);
828 }
829 }
830
831 if (Base.Ptr && !Base.isExpensive()) {
832 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
833 bool DoFold = CanFold(Base.LHSNW & Base.RHSNW);
834
835 if (!DoFold && Base.Ptr->getType()->isPointerTy()) {
836 // Without the flags, we can still fold if the offsets are constant and
837 // they cross the base's alignment boundary the same number of times, so
838 // either both arguments will wrap, or none of them will.
839 unsigned BW = DL.getIndexTypeSizeInBits(GEPLHS->getType());
840 APInt Alignment = APInt(BW, Base.Ptr->getPointerAlignment(DL).value());
841 APInt LOff(BW, 0);
842 APInt ROff(BW, 0);
844 DL, LOff, /*AllowNonInbounds=*/true) == Base.Ptr &&
845 RHS->stripAndAccumulateConstantOffsets(
846 DL, ROff, /*AllowNonInbounds=*/true) == Base.Ptr)
847 DoFold =
850 }
851
852 if (DoFold) {
853 Type *IdxTy = DL.getIndexType(GEPLHS->getType());
854 Value *L = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy,
855 /*RewriteGEP=*/true);
856 Value *R = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy,
857 /*RewriteGEP=*/true);
858 return NewICmp(Base.LHSNW & Base.RHSNW, L, R);
859 }
860 }
861 }
862
863 // Try convert this to an indexed compare by looking through PHIs/casts as a
864 // last resort.
865 return transformToIndexedCompare(GEPLHS, RHS, Cond, DL, *this);
866}
867
869 // It would be tempting to fold away comparisons between allocas and any
870 // pointer not based on that alloca (e.g. an argument). However, even
871 // though such pointers cannot alias, they can still compare equal.
872 //
873 // But LLVM doesn't specify where allocas get their memory, so if the alloca
874 // doesn't escape we can argue that it's impossible to guess its value, and we
875 // can therefore act as if any such guesses are wrong.
876 //
877 // However, we need to ensure that this folding is consistent: We can't fold
878 // one comparison to false, and then leave a different comparison against the
879 // same value alone (as it might evaluate to true at runtime, leading to a
880 // contradiction). As such, this code ensures that all comparisons are folded
881 // at the same time, and there are no other escapes.
882
883 struct CmpCaptureTracker : public CaptureTracker {
884 AllocaInst *Alloca;
885 bool Captured = false;
886 /// The value of the map is a bit mask of which icmp operands the alloca is
887 /// used in.
889
890 CmpCaptureTracker(AllocaInst *Alloca) : Alloca(Alloca) {}
891
892 void tooManyUses() override { Captured = true; }
893
894 Action captured(const Use *U, UseCaptureInfo CI) override {
895 // TODO(captures): Use UseCaptureInfo.
896 auto *ICmp = dyn_cast<ICmpInst>(U->getUser());
897 // We need to check that U is based *only* on the alloca, and doesn't
898 // have other contributions from a select/phi operand.
899 // TODO: We could check whether getUnderlyingObjects() reduces to one
900 // object, which would allow looking through phi nodes.
901 if (ICmp && ICmp->isEquality() && getUnderlyingObject(*U) == Alloca) {
902 // Collect equality icmps of the alloca, and don't treat them as
903 // captures.
904 ICmps[ICmp] |= 1u << U->getOperandNo();
905 return Continue;
906 }
907
908 Captured = true;
909 return Stop;
910 }
911 };
912
913 CmpCaptureTracker Tracker(Alloca);
914 PointerMayBeCaptured(Alloca, &Tracker);
915 if (Tracker.Captured)
916 return false;
917
918 bool Changed = false;
919 for (auto [ICmp, Operands] : Tracker.ICmps) {
920 switch (Operands) {
921 case 1:
922 case 2: {
923 // The alloca is only used in one icmp operand. Assume that the
924 // equality is false.
925 auto *Res = ConstantInt::get(ICmp->getType(),
926 ICmp->getPredicate() == ICmpInst::ICMP_NE);
927 replaceInstUsesWith(*ICmp, Res);
929 Changed = true;
930 break;
931 }
932 case 3:
933 // Both icmp operands are based on the alloca, so this is comparing
934 // pointer offsets, without leaking any information about the address
935 // of the alloca. Ignore such comparisons.
936 break;
937 default:
938 llvm_unreachable("Cannot happen");
939 }
940 }
941
942 return Changed;
943}
944
945/// Fold "icmp pred (X+C), X".
947 CmpPredicate Pred) {
948 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
949 // so the values can never be equal. Similarly for all other "or equals"
950 // operators.
951 assert(!!C && "C should not be zero!");
952
953 // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
954 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
955 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
956 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
957 Constant *R =
958 ConstantInt::get(X->getType(), APInt::getMaxValue(C.getBitWidth()) - C);
959 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
960 }
961
962 // (X+1) >u X --> X <u (0-1) --> X != 255
963 // (X+2) >u X --> X <u (0-2) --> X <u 254
964 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
965 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
966 return new ICmpInst(ICmpInst::ICMP_ULT, X,
967 ConstantInt::get(X->getType(), -C));
968
969 APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
970
971 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
972 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
973 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
974 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
975 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
976 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
977 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
978 return new ICmpInst(ICmpInst::ICMP_SGT, X,
979 ConstantInt::get(X->getType(), SMax - C));
980
981 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
982 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
983 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
984 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
985 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
986 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
987
988 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
989 return new ICmpInst(ICmpInst::ICMP_SLT, X,
990 ConstantInt::get(X->getType(), SMax - (C - 1)));
991}
992
993/// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
994/// (icmp eq/ne A, Log2(AP2/AP1)) ->
995/// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
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 bool IsAShr = isa<AShrOperator>(I.getOperand(0));
1012 if (IsAShr) {
1013 if (AP2.isAllOnes())
1014 return nullptr;
1015 if (AP2.isNegative() != AP1.isNegative())
1016 return nullptr;
1017 if (AP2.sgt(AP1))
1018 return nullptr;
1019 }
1020
1021 if (!AP1)
1022 // 'A' must be large enough to shift out the highest set bit.
1023 return getICmp(I.ICMP_UGT, A,
1024 ConstantInt::get(A->getType(), AP2.logBase2()));
1025
1026 if (AP1 == AP2)
1027 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1028
1029 int Shift;
1030 if (IsAShr && AP1.isNegative())
1031 Shift = AP1.countl_one() - AP2.countl_one();
1032 else
1033 Shift = AP1.countl_zero() - AP2.countl_zero();
1034
1035 if (Shift > 0) {
1036 if (IsAShr && AP1 == AP2.ashr(Shift)) {
1037 // There are multiple solutions if we are comparing against -1 and the LHS
1038 // of the ashr is not a power of two.
1039 if (AP1.isAllOnes() && !AP2.isPowerOf2())
1040 return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
1041 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1042 } else if (AP1 == AP2.lshr(Shift)) {
1043 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1044 }
1045 }
1046
1047 // Shifting const2 will never be equal to const1.
1048 // FIXME: This should always be handled by InstSimplify?
1049 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1050 return replaceInstUsesWith(I, TorF);
1051}
1052
1053/// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
1054/// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
1056 const APInt &AP1,
1057 const APInt &AP2) {
1058 assert(I.isEquality() && "Cannot fold icmp gt/lt");
1059
1060 auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
1061 if (I.getPredicate() == I.ICMP_NE)
1062 Pred = CmpInst::getInversePredicate(Pred);
1063 return new ICmpInst(Pred, LHS, RHS);
1064 };
1065
1066 // Don't bother doing any work for cases which InstSimplify handles.
1067 if (AP2.isZero())
1068 return nullptr;
1069
1070 unsigned AP2TrailingZeros = AP2.countr_zero();
1071
1072 if (!AP1 && AP2TrailingZeros != 0)
1073 return getICmp(
1074 I.ICMP_UGE, A,
1075 ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
1076
1077 if (AP1 == AP2)
1078 return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
1079
1080 // Get the distance between the lowest bits that are set.
1081 int Shift = AP1.countr_zero() - AP2TrailingZeros;
1082
1083 if (Shift > 0 && AP2.shl(Shift) == AP1)
1084 return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
1085
1086 // Shifting const2 will never be equal to const1.
1087 // FIXME: This should always be handled by InstSimplify?
1088 auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
1089 return replaceInstUsesWith(I, TorF);
1090}
1091
1092/// The caller has matched a pattern of the form:
1093/// I = icmp ugt (add (add A, B), CI2), CI1
1094/// If this is of the form:
1095/// sum = a + b
1096/// if (sum+128 >u 255)
1097/// Then replace it with llvm.sadd.with.overflow.i8.
1098///
1100 ConstantInt *CI2, ConstantInt *CI1,
1101 InstCombinerImpl &IC) {
1102 // The transformation we're trying to do here is to transform this into an
1103 // llvm.sadd.with.overflow. To do this, we have to replace the original add
1104 // with a narrower add, and discard the add-with-constant that is part of the
1105 // range check (if we can't eliminate it, this isn't profitable).
1106
1107 // In order to eliminate the add-with-constant, the compare can be its only
1108 // use.
1109 Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
1110 if (!AddWithCst->hasOneUse())
1111 return nullptr;
1112
1113 // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
1114 if (!CI2->getValue().isPowerOf2())
1115 return nullptr;
1116 unsigned NewWidth = CI2->getValue().countr_zero();
1117 if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
1118 return nullptr;
1119
1120 // The width of the new add formed is 1 more than the bias.
1121 ++NewWidth;
1122
1123 // Check to see that CI1 is an all-ones value with NewWidth bits.
1124 if (CI1->getBitWidth() == NewWidth ||
1125 CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
1126 return nullptr;
1127
1128 // This is only really a signed overflow check if the inputs have been
1129 // sign-extended; check for that condition. For example, if CI2 is 2^31 and
1130 // the operands of the add are 64 bits wide, we need at least 33 sign bits.
1131 if (IC.ComputeMaxSignificantBits(A, &I) > NewWidth ||
1132 IC.ComputeMaxSignificantBits(B, &I) > NewWidth)
1133 return nullptr;
1134
1135 // In order to replace the original add with a narrower
1136 // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
1137 // and truncates that discard the high bits of the add. Verify that this is
1138 // the case.
1139 Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
1140 for (User *U : OrigAdd->users()) {
1141 if (U == AddWithCst)
1142 continue;
1143
1144 // Only accept truncates for now. We would really like a nice recursive
1145 // predicate like SimplifyDemandedBits, but which goes downwards the use-def
1146 // chain to see which bits of a value are actually demanded. If the
1147 // original add had another add which was then immediately truncated, we
1148 // could still do the transformation.
1150 if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
1151 return nullptr;
1152 }
1153
1154 // If the pattern matches, truncate the inputs to the narrower type and
1155 // use the sadd_with_overflow intrinsic to efficiently compute both the
1156 // result and the overflow bit.
1157 Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
1159 I.getModule(), Intrinsic::sadd_with_overflow, NewType);
1160
1161 InstCombiner::BuilderTy &Builder = IC.Builder;
1162
1163 // Put the new code above the original add, in case there are any uses of the
1164 // add between the add and the compare.
1165 Builder.SetInsertPoint(OrigAdd);
1166
1167 Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
1168 Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
1169 CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
1170 Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
1171 Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
1172
1173 // The inner add was the result of the narrow add, zero extended to the
1174 // wider type. Replace it with the result computed by the intrinsic.
1175 IC.replaceInstUsesWith(*OrigAdd, ZExt);
1176 IC.eraseInstFromFunction(*OrigAdd);
1177
1178 // The original icmp gets replaced with the overflow value.
1179 return ExtractValueInst::Create(Call, 1, "sadd.overflow");
1180}
1181
1182/// If we have:
1183/// icmp eq/ne (urem/srem %x, %y), 0
1184/// iff %y is a power-of-two, we can replace this with a bit test:
1185/// icmp eq/ne (and %x, (add %y, -1)), 0
1187 // This fold is only valid for equality predicates.
1188 if (!I.isEquality())
1189 return nullptr;
1190 CmpPredicate Pred;
1191 Value *X, *Y, *Zero;
1192 if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
1193 m_CombineAnd(m_Zero(), m_Value(Zero)))))
1194 return nullptr;
1195 if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, &I))
1196 return nullptr;
1197 // This may increase instruction count, we don't enforce that Y is a constant.
1198 Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
1199 Value *Masked = Builder.CreateAnd(X, Mask);
1200 return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
1201}
1202
1203/// Fold equality-comparison between zero and any (maybe truncated) right-shift
1204/// by one-less-than-bitwidth into a sign test on the original value.
1206 Instruction *Val;
1207 CmpPredicate Pred;
1208 if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
1209 return nullptr;
1210
1211 Value *X;
1212 Type *XTy;
1213
1214 Constant *C;
1215 if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
1216 XTy = X->getType();
1217 unsigned XBitWidth = XTy->getScalarSizeInBits();
1219 APInt(XBitWidth, XBitWidth - 1))))
1220 return nullptr;
1221 } else if (isa<BinaryOperator>(Val) &&
1223 cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
1224 /*AnalyzeForSignBitExtraction=*/true))) {
1225 XTy = X->getType();
1226 } else
1227 return nullptr;
1228
1229 return ICmpInst::Create(Instruction::ICmp,
1233}
1234
1235// Handle icmp pred X, 0
1237 CmpInst::Predicate Pred = Cmp.getPredicate();
1238 if (!match(Cmp.getOperand(1), m_Zero()))
1239 return nullptr;
1240
1241 // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
1242 if (Pred == ICmpInst::ICMP_SGT) {
1243 Value *A, *B;
1244 if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
1245 if (isKnownPositive(A, SQ.getWithInstruction(&Cmp)))
1246 return new ICmpInst(Pred, B, Cmp.getOperand(1));
1247 if (isKnownPositive(B, SQ.getWithInstruction(&Cmp)))
1248 return new ICmpInst(Pred, A, Cmp.getOperand(1));
1249 }
1250 }
1251
1253 return New;
1254
1255 // Given:
1256 // icmp eq/ne (urem %x, %y), 0
1257 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
1258 // icmp eq/ne %x, 0
1259 Value *X, *Y;
1260 if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
1261 ICmpInst::isEquality(Pred)) {
1262 KnownBits XKnown = computeKnownBits(X, &Cmp);
1263 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1264 if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
1265 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1266 }
1267
1268 // (icmp eq/ne (mul X Y)) -> (icmp eq/ne X/Y) if we know about whether X/Y are
1269 // odd/non-zero/there is no overflow.
1270 if (match(Cmp.getOperand(0), m_Mul(m_Value(X), m_Value(Y))) &&
1271 ICmpInst::isEquality(Pred)) {
1272
1273 KnownBits XKnown = computeKnownBits(X, &Cmp);
1274 // if X % 2 != 0
1275 // (icmp eq/ne Y)
1276 if (XKnown.countMaxTrailingZeros() == 0)
1277 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1278
1279 KnownBits YKnown = computeKnownBits(Y, &Cmp);
1280 // if Y % 2 != 0
1281 // (icmp eq/ne X)
1282 if (YKnown.countMaxTrailingZeros() == 0)
1283 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1284
1285 auto *BO0 = cast<OverflowingBinaryOperator>(Cmp.getOperand(0));
1286 if (BO0->hasNoUnsignedWrap() || BO0->hasNoSignedWrap()) {
1287 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
1288 // `isKnownNonZero` does more analysis than just `!KnownBits.One.isZero()`
1289 // but to avoid unnecessary work, first just if this is an obvious case.
1290
1291 // if X non-zero and NoOverflow(X * Y)
1292 // (icmp eq/ne Y)
1293 if (!XKnown.One.isZero() || isKnownNonZero(X, Q))
1294 return new ICmpInst(Pred, Y, Cmp.getOperand(1));
1295
1296 // if Y non-zero and NoOverflow(X * Y)
1297 // (icmp eq/ne X)
1298 if (!YKnown.One.isZero() || isKnownNonZero(Y, Q))
1299 return new ICmpInst(Pred, X, Cmp.getOperand(1));
1300 }
1301 // Note, we are skipping cases:
1302 // if Y % 2 != 0 AND X % 2 != 0
1303 // (false/true)
1304 // if X non-zero and Y non-zero and NoOverflow(X * Y)
1305 // (false/true)
1306 // Those can be simplified later as we would have already replaced the (icmp
1307 // eq/ne (mul X, Y)) with (icmp eq/ne X/Y) and if X/Y is known non-zero that
1308 // will fold to a constant elsewhere.
1309 }
1310
1311 // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
1312 // where f(X) == 0 if and only if X == 0
1313 if (ICmpInst::isEquality(Pred))
1314 if (Value *Stripped = stripNullTest(Cmp.getOperand(0)))
1315 return new ICmpInst(Pred, Stripped,
1316 Constant::getNullValue(Stripped->getType()));
1317
1318 return nullptr;
1319}
1320
1321/// Fold icmp eq (num + mask) & ~mask, num
1322/// to
1323/// icmp eq (and num, mask), 0
1324/// Where mask is a low bit mask.
1326 Value *Num;
1327 CmpPredicate Pred;
1328 const APInt *Mask, *Neg;
1329
1330 if (!match(&Cmp,
1331 m_c_ICmp(Pred, m_Value(Num),
1333 m_LowBitMask(Mask))),
1334 m_APInt(Neg))))))
1335 return nullptr;
1336
1337 if (*Neg != ~*Mask)
1338 return nullptr;
1339
1340 if (!ICmpInst::isEquality(Pred))
1341 return nullptr;
1342
1343 // Create new icmp eq (num & mask), 0
1344 auto *NewAnd = Builder.CreateAnd(Num, *Mask);
1345 auto *Zero = Constant::getNullValue(Num->getType());
1346
1347 return new ICmpInst(Pred, NewAnd, Zero);
1348}
1349
1350/// Fold icmp Pred X, C.
1351/// TODO: This code structure does not make sense. The saturating add fold
1352/// should be moved to some other helper and extended as noted below (it is also
1353/// possible that code has been made unnecessary - do we canonicalize IR to
1354/// overflow/saturating intrinsics or not?).
1356 // Match the following pattern, which is a common idiom when writing
1357 // overflow-safe integer arithmetic functions. The source performs an addition
1358 // in wider type and explicitly checks for overflow using comparisons against
1359 // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
1360 //
1361 // TODO: This could probably be generalized to handle other overflow-safe
1362 // operations if we worked out the formulas to compute the appropriate magic
1363 // constants.
1364 //
1365 // sum = a + b
1366 // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
1367 CmpInst::Predicate Pred = Cmp.getPredicate();
1368 Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
1369 Value *A, *B;
1370 ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
1371 if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
1372 match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
1373 if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
1374 return Res;
1375
1376 // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
1378 if (!C)
1379 return nullptr;
1380
1381 if (auto *Phi = dyn_cast<PHINode>(Op0))
1382 if (all_of(Phi->operands(), IsaPred<Constant>)) {
1384 for (Value *V : Phi->incoming_values()) {
1385 Constant *Res =
1387 if (!Res)
1388 return nullptr;
1389 Ops.push_back(Res);
1390 }
1391 Builder.SetInsertPoint(Phi);
1392 PHINode *NewPhi = Builder.CreatePHI(Cmp.getType(), Phi->getNumOperands());
1393 for (auto [V, Pred] : zip(Ops, Phi->blocks()))
1394 NewPhi->addIncoming(V, Pred);
1395 return replaceInstUsesWith(Cmp, NewPhi);
1396 }
1397
1399 return R;
1400
1401 return nullptr;
1402}
1403
1404/// Canonicalize icmp instructions based on dominating conditions.
1406 // We already checked simple implication in InstSimplify, only handle complex
1407 // cases here.
1408 Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
1409 const APInt *C;
1410 if (!match(Y, m_APInt(C)))
1411 return nullptr;
1412
1413 CmpInst::Predicate Pred = Cmp.getPredicate();
1415
1416 auto handleDomCond = [&](ICmpInst::Predicate DomPred,
1417 const APInt *DomC) -> Instruction * {
1418 // We have 2 compares of a variable with constants. Calculate the constant
1419 // ranges of those compares to see if we can transform the 2nd compare:
1420 // DomBB:
1421 // DomCond = icmp DomPred X, DomC
1422 // br DomCond, CmpBB, FalseBB
1423 // CmpBB:
1424 // Cmp = icmp Pred X, C
1425 ConstantRange DominatingCR =
1426 ConstantRange::makeExactICmpRegion(DomPred, *DomC);
1427 ConstantRange Intersection = DominatingCR.intersectWith(CR);
1428 ConstantRange Difference = DominatingCR.difference(CR);
1429 if (Intersection.isEmptySet())
1430 return replaceInstUsesWith(Cmp, Builder.getFalse());
1431 if (Difference.isEmptySet())
1432 return replaceInstUsesWith(Cmp, Builder.getTrue());
1433
1434 // Canonicalizing a sign bit comparison that gets used in a branch,
1435 // pessimizes codegen by generating branch on zero instruction instead
1436 // of a test and branch. So we avoid canonicalizing in such situations
1437 // because test and branch instruction has better branch displacement
1438 // than compare and branch instruction.
1439 bool UnusedBit;
1440 bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
1441 if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
1442 return nullptr;
1443
1444 // Avoid an infinite loop with min/max canonicalization.
1445 // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
1446 if (Cmp.hasOneUse() &&
1447 match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
1448 return nullptr;
1449
1450 if (const APInt *EqC = Intersection.getSingleElement())
1451 return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
1452 if (const APInt *NeC = Difference.getSingleElement())
1453 return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
1454 return nullptr;
1455 };
1456
1457 for (CondBrInst *BI : DC.conditionsFor(X)) {
1458 CmpPredicate DomPred;
1459 const APInt *DomC;
1460 if (!match(BI->getCondition(),
1461 m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))))
1462 continue;
1463
1464 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1465 if (DT.dominates(Edge0, Cmp.getParent())) {
1466 if (auto *V = handleDomCond(DomPred, DomC))
1467 return V;
1468 } else {
1469 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1470 if (DT.dominates(Edge1, Cmp.getParent()))
1471 if (auto *V =
1472 handleDomCond(CmpInst::getInversePredicate(DomPred), DomC))
1473 return V;
1474 }
1475 }
1476
1477 return nullptr;
1478}
1479
1480/// Fold icmp (trunc X), C.
1482 TruncInst *Trunc,
1483 const APInt &C) {
1484 ICmpInst::Predicate Pred = Cmp.getPredicate();
1485 Value *X = Trunc->getOperand(0);
1486 Type *SrcTy = X->getType();
1487 unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
1488 SrcBits = SrcTy->getScalarSizeInBits();
1489
1490 // Match (icmp pred (trunc nuw/nsw X), C)
1491 // Which we can convert to (icmp pred X, (sext/zext C))
1492 if (shouldChangeType(Trunc->getType(), SrcTy)) {
1493 if (Trunc->hasNoSignedWrap())
1494 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.sext(SrcBits)));
1495 if (!Cmp.isSigned() && Trunc->hasNoUnsignedWrap())
1496 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, C.zext(SrcBits)));
1497 }
1498
1499 if (C.isOne() && C.getBitWidth() > 1) {
1500 // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
1501 Value *V = nullptr;
1502 if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
1503 return new ICmpInst(ICmpInst::ICMP_SLT, V,
1504 ConstantInt::get(V->getType(), 1));
1505 }
1506
1507 // TODO: Handle non-equality predicates.
1508 Value *Y;
1509 const APInt *Pow2;
1510 if (Cmp.isEquality() && match(X, m_Shl(m_Power2(Pow2), m_Value(Y))) &&
1511 DstBits > Pow2->logBase2()) {
1512 // (trunc (Pow2 << Y) to iN) == 0 --> Y u>= N - log2(Pow2)
1513 // (trunc (Pow2 << Y) to iN) != 0 --> Y u< N - log2(Pow2)
1514 // iff N > log2(Pow2)
1515 if (C.isZero()) {
1516 auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
1517 return new ICmpInst(NewPred, Y,
1518 ConstantInt::get(SrcTy, DstBits - Pow2->logBase2()));
1519 }
1520 // (trunc (Pow2 << Y) to iN) == 2**C --> Y == C - log2(Pow2)
1521 // (trunc (Pow2 << Y) to iN) != 2**C --> Y != C - log2(Pow2)
1522 if (C.isPowerOf2())
1523 return new ICmpInst(
1524 Pred, Y, ConstantInt::get(SrcTy, C.logBase2() - Pow2->logBase2()));
1525 }
1526
1527 if (Cmp.isEquality() && (Trunc->hasOneUse() || Trunc->hasNoUnsignedWrap())) {
1528 // Canonicalize to a mask and wider compare if the wide type is suitable:
1529 // (trunc X to i8) == C --> (X & 0xff) == (zext C)
1530 if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
1531 Constant *Mask =
1532 ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
1533 Value *And = Trunc->hasNoUnsignedWrap() ? X : Builder.CreateAnd(X, Mask);
1534 Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
1535 return new ICmpInst(Pred, And, WideC);
1536 }
1537
1538 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
1539 // of the high bits truncated out of x are known.
1541
1542 // If all the high bits are known, we can do this xform.
1543 if ((Known.Zero | Known.One).countl_one() >= SrcBits - DstBits) {
1544 // Pull in the high bits from known-ones set.
1545 APInt NewRHS = C.zext(SrcBits);
1546 NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
1547 return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
1548 }
1549 }
1550
1551 // Look through truncated right-shift of the sign-bit for a sign-bit check:
1552 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
1553 // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
1554 Value *ShOp;
1555 uint64_t ShAmt;
1556 bool TrueIfSigned;
1557 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
1558 match(X, m_Shr(m_Value(ShOp), m_ConstantInt(ShAmt))) &&
1559 DstBits == SrcBits - ShAmt) {
1560 return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
1562 : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
1564 }
1565
1566 return nullptr;
1567}
1568
1569/// Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
1570/// Fold icmp (trunc nuw/nsw X), (zext/sext Y).
1573 const SimplifyQuery &Q) {
1574 Value *X, *Y;
1575 CmpPredicate Pred;
1576 bool YIsSExt = false;
1577 // Try to match icmp (trunc X), (trunc Y)
1578 if (match(&Cmp, m_ICmp(Pred, m_Trunc(m_Value(X)), m_Trunc(m_Value(Y))))) {
1579 unsigned NoWrapFlags = cast<TruncInst>(Cmp.getOperand(0))->getNoWrapKind() &
1580 cast<TruncInst>(Cmp.getOperand(1))->getNoWrapKind();
1581 if (Cmp.isSigned()) {
1582 // For signed comparisons, both truncs must be nsw.
1583 if (!(NoWrapFlags & TruncInst::NoSignedWrap))
1584 return nullptr;
1585 } else {
1586 // For unsigned and equality comparisons, either both must be nuw or
1587 // both must be nsw, we don't care which.
1588 if (!NoWrapFlags)
1589 return nullptr;
1590 }
1591
1592 if (X->getType() != Y->getType() &&
1593 (!Cmp.getOperand(0)->hasOneUse() || !Cmp.getOperand(1)->hasOneUse()))
1594 return nullptr;
1595 if (!isDesirableIntType(X->getType()->getScalarSizeInBits()) &&
1596 isDesirableIntType(Y->getType()->getScalarSizeInBits())) {
1597 std::swap(X, Y);
1598 Pred = Cmp.getSwappedPredicate(Pred);
1599 }
1600 YIsSExt = !(NoWrapFlags & TruncInst::NoUnsignedWrap);
1601 }
1602 // Try to match icmp (trunc nuw X), (zext Y)
1603 else if (!Cmp.isSigned() &&
1604 match(&Cmp, m_c_ICmp(Pred, m_NUWTrunc(m_Value(X)),
1605 m_OneUse(m_ZExt(m_Value(Y)))))) {
1606 // Can fold trunc nuw + zext for unsigned and equality predicates.
1607 }
1608 // Try to match icmp (trunc nsw X), (sext Y)
1609 else if (match(&Cmp, m_c_ICmp(Pred, m_NSWTrunc(m_Value(X)),
1611 // Can fold trunc nsw + zext/sext for all predicates.
1612 YIsSExt =
1613 isa<SExtInst>(Cmp.getOperand(0)) || isa<SExtInst>(Cmp.getOperand(1));
1614 } else
1615 return nullptr;
1616
1617 Type *TruncTy = Cmp.getOperand(0)->getType();
1618 unsigned TruncBits = TruncTy->getScalarSizeInBits();
1619
1620 // If this transform will end up changing from desirable types -> undesirable
1621 // types skip it.
1622 if (isDesirableIntType(TruncBits) &&
1623 !isDesirableIntType(X->getType()->getScalarSizeInBits()))
1624 return nullptr;
1625
1626 Value *NewY = Builder.CreateIntCast(Y, X->getType(), YIsSExt);
1627 return new ICmpInst(Pred, X, NewY);
1628}
1629
1630/// Fold icmp (xor X, Y), C.
1633 const APInt &C) {
1634 if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
1635 return I;
1636
1637 Value *X = Xor->getOperand(0);
1638 Value *Y = Xor->getOperand(1);
1639 const APInt *XorC;
1640 if (!match(Y, m_APInt(XorC)))
1641 return nullptr;
1642
1643 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
1644 // fold the xor.
1645 ICmpInst::Predicate Pred = Cmp.getPredicate();
1646 bool TrueIfSigned = false;
1647 if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
1648
1649 // If the sign bit of the XorCst is not set, there is no change to
1650 // the operation, just stop using the Xor.
1651 if (!XorC->isNegative())
1652 return replaceOperand(Cmp, 0, X);
1653
1654 // Emit the opposite comparison.
1655 if (TrueIfSigned)
1656 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1657 ConstantInt::getAllOnesValue(X->getType()));
1658 else
1659 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1660 ConstantInt::getNullValue(X->getType()));
1661 }
1662
1663 if (Xor->hasOneUse()) {
1664 // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
1665 if (!Cmp.isEquality() && XorC->isSignMask()) {
1666 Pred = Cmp.getFlippedSignednessPredicate();
1667 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1668 }
1669
1670 // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
1671 if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
1672 Pred = Cmp.getFlippedSignednessPredicate();
1673 Pred = Cmp.getSwappedPredicate(Pred);
1674 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
1675 }
1676 }
1677
1678 // Mask constant magic can eliminate an 'xor' with unsigned compares.
1679 if (Pred == ICmpInst::ICMP_UGT) {
1680 // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
1681 if (*XorC == ~C && (C + 1).isPowerOf2())
1682 return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
1683 // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
1684 if (*XorC == C && (C + 1).isPowerOf2())
1685 return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
1686 }
1687 if (Pred == ICmpInst::ICMP_ULT) {
1688 // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
1689 if (*XorC == -C && C.isPowerOf2())
1690 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1691 ConstantInt::get(X->getType(), ~C));
1692 // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
1693 if (*XorC == C && (-C).isPowerOf2())
1694 return new ICmpInst(ICmpInst::ICMP_UGT, X,
1695 ConstantInt::get(X->getType(), ~C));
1696 }
1697 return nullptr;
1698}
1699
1700/// For power-of-2 C:
1701/// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
1702/// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
1705 const APInt &C) {
1706 CmpInst::Predicate Pred = Cmp.getPredicate();
1707 APInt PowerOf2;
1708 if (Pred == ICmpInst::ICMP_ULT)
1709 PowerOf2 = C;
1710 else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
1711 PowerOf2 = C + 1;
1712 else
1713 return nullptr;
1714 if (!PowerOf2.isPowerOf2())
1715 return nullptr;
1716 Value *X;
1717 const APInt *ShiftC;
1719 m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
1720 return nullptr;
1721 uint64_t Shift = ShiftC->getLimitedValue();
1722 Type *XType = X->getType();
1723 if (Shift == 0 || PowerOf2.isMinSignedValue())
1724 return nullptr;
1725 Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
1726 APInt Bound =
1727 Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
1728 return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
1729}
1730
1731/// Fold icmp (and (sh X, Y), C2), C1.
1734 const APInt &C1,
1735 const APInt &C2) {
1736 BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
1737 if (!Shift || !Shift->isShift())
1738 return nullptr;
1739
1740 // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
1741 // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
1742 // code produced by the clang front-end, for bitfield access.
1743 // This seemingly simple opportunity to fold away a shift turns out to be
1744 // rather complicated. See PR17827 for details.
1745 unsigned ShiftOpcode = Shift->getOpcode();
1746 bool IsShl = ShiftOpcode == Instruction::Shl;
1747 const APInt *C3;
1748 if (match(Shift->getOperand(1), m_APInt(C3))) {
1749 APInt NewAndCst, NewCmpCst;
1750 bool AnyCmpCstBitsShiftedOut;
1751 if (ShiftOpcode == Instruction::Shl) {
1752 // For a left shift, we can fold if the comparison is not signed. We can
1753 // also fold a signed comparison if the mask value and comparison value
1754 // are not negative. These constraints may not be obvious, but we can
1755 // prove that they are correct using an SMT solver.
1756 if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
1757 return nullptr;
1758
1759 NewCmpCst = C1.lshr(*C3);
1760 NewAndCst = C2.lshr(*C3);
1761 AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
1762 } else if (ShiftOpcode == Instruction::LShr) {
1763 // For a logical right shift, we can fold if the comparison is not signed.
1764 // We can also fold a signed comparison if the shifted mask value and the
1765 // shifted comparison value are not negative. These constraints may not be
1766 // obvious, but we can prove that they are correct using an SMT solver.
1767 NewCmpCst = C1.shl(*C3);
1768 NewAndCst = C2.shl(*C3);
1769 AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
1770 if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
1771 return nullptr;
1772 } else {
1773 // For an arithmetic shift, check that both constants don't use (in a
1774 // signed sense) the top bits being shifted out.
1775 assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
1776 NewCmpCst = C1.shl(*C3);
1777 NewAndCst = C2.shl(*C3);
1778 AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
1779 if (NewAndCst.ashr(*C3) != C2)
1780 return nullptr;
1781 }
1782
1783 if (AnyCmpCstBitsShiftedOut) {
1784 // If we shifted bits out, the fold is not going to work out. As a
1785 // special case, check to see if this means that the result is always
1786 // true or false now.
1787 if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
1788 return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
1789 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1790 return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
1791 } else {
1792 Value *NewAnd = Builder.CreateAnd(
1793 Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
1794 return new ICmpInst(Cmp.getPredicate(), NewAnd,
1795 ConstantInt::get(And->getType(), NewCmpCst));
1796 }
1797 }
1798
1799 // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
1800 // preferable because it allows the C2 << Y expression to be hoisted out of a
1801 // loop if Y is invariant and X is not.
1802 if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
1803 !Shift->isArithmeticShift() &&
1804 ((!IsShl && C2.isOne()) || !isa<Constant>(Shift->getOperand(0)))) {
1805 // Compute C2 << Y.
1806 Value *NewShift =
1807 IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
1808 : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
1809
1810 // Compute X & (C2 << Y).
1811 Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
1812 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1813 }
1814
1815 return nullptr;
1816}
1817
1818/// Fold icmp (and X, C2), C1.
1821 const APInt &C1) {
1822 bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
1823
1824 // icmp ne (and X, 1), 0 --> trunc X to i1
1825 if (isICMP_NE && C1.isZero() && match(And->getOperand(1), m_One()))
1826 return new TruncInst(And->getOperand(0), Cmp.getType());
1827
1828 const APInt *C2;
1829 Value *X;
1830 if (!match(And, m_And(m_Value(X), m_APInt(C2))))
1831 return nullptr;
1832
1833 // (and X, highmask) s> [0, ~highmask] --> X s> ~highmask
1834 if (Cmp.getPredicate() == ICmpInst::ICMP_SGT && C1.ule(~*C2) &&
1835 C2->isNegatedPowerOf2())
1836 return new ICmpInst(ICmpInst::ICMP_SGT, X,
1837 ConstantInt::get(X->getType(), ~*C2));
1838 // (and X, highmask) s< [1, -highmask] --> X s< -highmask
1839 if (Cmp.getPredicate() == ICmpInst::ICMP_SLT && !C1.isSignMask() &&
1840 (C1 - 1).ule(~*C2) && C2->isNegatedPowerOf2() && !C2->isSignMask())
1841 return new ICmpInst(ICmpInst::ICMP_SLT, X,
1842 ConstantInt::get(X->getType(), -*C2));
1843
1844 // Don't perform the following transforms if the AND has multiple uses
1845 if (!And->hasOneUse())
1846 return nullptr;
1847
1848 if (Cmp.isEquality() && C1.isZero()) {
1849 // Restrict this fold to single-use 'and' (PR10267).
1850 // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
1851 if (C2->isSignMask()) {
1852 Constant *Zero = Constant::getNullValue(X->getType());
1853 auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
1854 return new ICmpInst(NewPred, X, Zero);
1855 }
1856
1857 APInt NewC2 = *C2;
1858 KnownBits Know = computeKnownBits(And->getOperand(0), And);
1859 // Set high zeros of C2 to allow matching negated power-of-2.
1860 NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
1861 Know.countMinLeadingZeros());
1862
1863 // Restrict this fold only for single-use 'and' (PR10267).
1864 // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
1865 if (NewC2.isNegatedPowerOf2()) {
1866 Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
1867 auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
1868 return new ICmpInst(NewPred, X, NegBOC);
1869 }
1870 }
1871
1872 // If the LHS is an 'and' of a truncate and we can widen the and/compare to
1873 // the input width without changing the value produced, eliminate the cast:
1874 //
1875 // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
1876 //
1877 // We can do this transformation if the constants do not have their sign bits
1878 // set or if it is an equality comparison. Extending a relational comparison
1879 // when we're checking the sign bit would not work.
1880 Value *W;
1881 if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
1882 (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
1883 // TODO: Is this a good transform for vectors? Wider types may reduce
1884 // throughput. Should this transform be limited (even for scalars) by using
1885 // shouldChangeType()?
1886 if (!Cmp.getType()->isVectorTy()) {
1887 Type *WideType = W->getType();
1888 unsigned WideScalarBits = WideType->getScalarSizeInBits();
1889 Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
1890 Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
1891 Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
1892 return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
1893 }
1894 }
1895
1896 if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
1897 return I;
1898
1899 // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
1900 // (icmp pred (and A, (or (shl 1, B), 1), 0))
1901 //
1902 // iff pred isn't signed
1903 if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
1904 match(And->getOperand(1), m_One())) {
1905 Constant *One = cast<Constant>(And->getOperand(1));
1906 Value *Or = And->getOperand(0);
1907 Value *A, *B, *LShr;
1908 if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
1909 match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
1910 unsigned UsesRemoved = 0;
1911 if (And->hasOneUse())
1912 ++UsesRemoved;
1913 if (Or->hasOneUse())
1914 ++UsesRemoved;
1915 if (LShr->hasOneUse())
1916 ++UsesRemoved;
1917
1918 // Compute A & ((1 << B) | 1)
1919 unsigned RequireUsesRemoved = match(B, m_ImmConstant()) ? 1 : 3;
1920 if (UsesRemoved >= RequireUsesRemoved) {
1921 Value *NewOr =
1922 Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
1923 /*HasNUW=*/true),
1924 One, Or->getName());
1925 Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
1926 return new ICmpInst(Cmp.getPredicate(), NewAnd, Cmp.getOperand(1));
1927 }
1928 }
1929 }
1930
1931 // (icmp eq (and (bitcast X to int), ExponentMask), ExponentMask) -->
1932 // llvm.is.fpclass(X, fcInf|fcNan)
1933 // (icmp ne (and (bitcast X to int), ExponentMask), ExponentMask) -->
1934 // llvm.is.fpclass(X, ~(fcInf|fcNan))
1935 // (icmp eq (and (bitcast X to int), ExponentMask), 0) -->
1936 // llvm.is.fpclass(X, fcSubnormal|fcZero)
1937 // (icmp ne (and (bitcast X to int), ExponentMask), 0) -->
1938 // llvm.is.fpclass(X, ~(fcSubnormal|fcZero))
1939 Value *V;
1940 if (!Cmp.getParent()->getParent()->hasFnAttribute(
1941 Attribute::NoImplicitFloat) &&
1942 Cmp.isEquality() &&
1944 Type *FPType = V->getType()->getScalarType();
1945 if (FPType->isIEEELikeFPTy() && (C1.isZero() || C1 == *C2)) {
1946 APInt ExponentMask =
1947 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt();
1948 if (*C2 == ExponentMask) {
1949 unsigned Mask = C1.isZero()
1952 if (isICMP_NE)
1953 Mask = ~Mask & fcAllFlags;
1954 return replaceInstUsesWith(Cmp, Builder.createIsFPClass(V, Mask));
1955 }
1956 }
1957 }
1958
1959 return nullptr;
1960}
1961
1962/// Fold icmp (and X, Y), C.
1965 const APInt &C) {
1966 if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
1967 return I;
1968
1969 const ICmpInst::Predicate Pred = Cmp.getPredicate();
1970 bool TrueIfNeg;
1971 if (isSignBitCheck(Pred, C, TrueIfNeg)) {
1972 // ((X - 1) & ~X) < 0 --> X == 0
1973 // ((X - 1) & ~X) >= 0 --> X != 0
1974 Value *X;
1975 if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
1976 match(And->getOperand(1), m_Not(m_Specific(X)))) {
1977 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1978 return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
1979 }
1980 // (X & -X) < 0 --> X == MinSignedC
1981 // (X & -X) > -1 --> X != MinSignedC
1982 if (match(And, m_c_And(m_Neg(m_Value(X)), m_Deferred(X)))) {
1983 Constant *MinSignedC = ConstantInt::get(
1984 X->getType(),
1985 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits()));
1986 auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1987 return new ICmpInst(NewPred, X, MinSignedC);
1988 }
1989 }
1990
1991 // TODO: These all require that Y is constant too, so refactor with the above.
1992
1993 // Try to optimize things like "A[i] & 42 == 0" to index computations.
1994 Value *X = And->getOperand(0);
1995 Value *Y = And->getOperand(1);
1996 if (auto *C2 = dyn_cast<ConstantInt>(Y))
1997 if (auto *LI = dyn_cast<LoadInst>(X))
1998 if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
2000 LI, GEP, Cmp.getPredicate(), cast<Constant>(Cmp.getOperand(1)),
2001 Cmp, C2))
2002 return Res;
2003
2004 if (!Cmp.isEquality())
2005 return nullptr;
2006
2007 // (X & -X) == 0 --> X == 0
2008 // (X & -X) != 0 --> X != 0
2009 // (X & -X) == 1 --> trunc X to i1
2010 // (X & -X) != 1 --> !(trunc X to i1)
2011 // Cmp is == or != by the check above.
2012 Value *MatchedX;
2013 // Match X & -X in either operand order.
2014 if (C.getBitWidth() > 1 && (C.isZero() || C.isOne()) &&
2015 match(And, m_c_And(m_Neg(m_Value(MatchedX)), m_Deferred(MatchedX)))) {
2016 // Preserve the predicate: (X & -X) ==/!= 0 --> X ==/!= 0.
2017 if (C.isZero())
2018 return new ICmpInst(Pred, MatchedX, Cmp.getOperand(1));
2019
2020 // (X & -X) == 1 iff the low bit of X is set.
2021 if (Pred == CmpInst::ICMP_EQ)
2022 return new TruncInst(MatchedX, Cmp.getType());
2023
2024 // The remaining case needs a trunc and not. Require the original and
2025 // to become dead to avoid increasing the instruction count.
2026 if (And->hasOneUse()) {
2027 Value *Trunc = Builder.CreateTrunc(MatchedX, Cmp.getType());
2028 return BinaryOperator::CreateNot(Trunc);
2029 }
2030 }
2031
2032 // X & -C == -C -> X > u ~C
2033 // X & -C != -C -> X <= u ~C
2034 // iff C is a power of 2
2035 if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
2036 auto NewPred =
2038 return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
2039 }
2040
2041 // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
2042 // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
2043 // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
2044 // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
2046 X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
2047 Value *TruncY = Builder.CreateTrunc(Y, X->getType());
2048 if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
2049 Value *And = Builder.CreateAnd(TruncY, X);
2051 }
2052 return BinaryOperator::CreateAnd(TruncY, X);
2053 }
2054
2055 // (icmp eq/ne (and (shl -1, X), Y), 0)
2056 // -> (icmp eq/ne (lshr Y, X), 0)
2057 // We could technically handle any C == 0 or (C < 0 && isOdd(C)) but it seems
2058 // highly unlikely the non-zero case will ever show up in code.
2059 if (C.isZero() &&
2061 m_Value(Y))))) {
2062 Value *LShr = Builder.CreateLShr(Y, X);
2063 return new ICmpInst(Pred, LShr, Constant::getNullValue(LShr->getType()));
2064 }
2065
2066 // (icmp eq/ne (and (add A, Addend), Msk), C)
2067 // -> (icmp eq/ne (and A, Msk), (and (sub C, Addend), Msk))
2068 {
2069 Value *A;
2070 const APInt *Addend, *Msk;
2072 m_LowBitMask(Msk)))) &&
2073 C.ule(*Msk)) {
2074 APInt NewComperand = (C - *Addend) & *Msk;
2075 Value *MaskA = Builder.CreateAnd(A, ConstantInt::get(A->getType(), *Msk));
2076 return new ICmpInst(Pred, MaskA,
2077 ConstantInt::get(MaskA->getType(), NewComperand));
2078 }
2079 }
2080
2081 return nullptr;
2082}
2083
2084/// Fold icmp eq/ne (or (xor/sub (X1, X2), xor/sub (X3, X4))), 0.
2086 InstCombiner::BuilderTy &Builder) {
2087 // Are we using xors or subs to bitwise check for a pair or pairs of
2088 // (in)equalities? Convert to a shorter form that has more potential to be
2089 // folded even further.
2090 // ((X1 ^/- X2) || (X3 ^/- X4)) == 0 --> (X1 == X2) && (X3 == X4)
2091 // ((X1 ^/- X2) || (X3 ^/- X4)) != 0 --> (X1 != X2) || (X3 != X4)
2092 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) == 0 -->
2093 // (X1 == X2) && (X3 == X4) && (X5 == X6)
2094 // ((X1 ^/- X2) || (X3 ^/- X4) || (X5 ^/- X6)) != 0 -->
2095 // (X1 != X2) || (X3 != X4) || (X5 != X6)
2097 SmallVector<Value *, 16> WorkList(1, Or);
2098
2099 while (!WorkList.empty()) {
2100 auto MatchOrOperatorArgument = [&](Value *OrOperatorArgument) {
2101 Value *Lhs, *Rhs;
2102
2103 if (match(OrOperatorArgument,
2104 m_OneUse(m_Xor(m_Value(Lhs), m_Value(Rhs))))) {
2105 CmpValues.emplace_back(Lhs, Rhs);
2106 return;
2107 }
2108
2109 if (match(OrOperatorArgument,
2110 m_OneUse(m_Sub(m_Value(Lhs), m_Value(Rhs))))) {
2111 CmpValues.emplace_back(Lhs, Rhs);
2112 return;
2113 }
2114
2115 WorkList.push_back(OrOperatorArgument);
2116 };
2117
2118 Value *CurrentValue = WorkList.pop_back_val();
2119 Value *OrOperatorLhs, *OrOperatorRhs;
2120
2121 if (!match(CurrentValue,
2122 m_Or(m_Value(OrOperatorLhs), m_Value(OrOperatorRhs)))) {
2123 return nullptr;
2124 }
2125
2126 MatchOrOperatorArgument(OrOperatorRhs);
2127 MatchOrOperatorArgument(OrOperatorLhs);
2128 }
2129
2130 ICmpInst::Predicate Pred = Cmp.getPredicate();
2131 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2132 Value *LhsCmp = Builder.CreateICmp(Pred, CmpValues.rbegin()->first,
2133 CmpValues.rbegin()->second);
2134
2135 for (auto It = CmpValues.rbegin() + 1; It != CmpValues.rend(); ++It) {
2136 Value *RhsCmp = Builder.CreateICmp(Pred, It->first, It->second);
2137 LhsCmp = Builder.CreateBinOp(BOpc, LhsCmp, RhsCmp);
2138 }
2139
2140 return LhsCmp;
2141}
2142
2143/// Fold icmp (or X, Y), C.
2146 const APInt &C) {
2147 ICmpInst::Predicate Pred = Cmp.getPredicate();
2148 if (C.isOne()) {
2149 // icmp slt signum(V) 1 --> icmp slt V, 1
2150 Value *V = nullptr;
2151 if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
2152 return new ICmpInst(ICmpInst::ICMP_SLT, V,
2153 ConstantInt::get(V->getType(), 1));
2154 }
2155
2156 Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
2157
2158 // (icmp eq/ne (or disjoint x, C0), C1)
2159 // -> (icmp eq/ne x, C0^C1)
2160 if (Cmp.isEquality() && match(OrOp1, m_ImmConstant()) &&
2161 cast<PossiblyDisjointInst>(Or)->isDisjoint()) {
2162 Value *NewC =
2163 Builder.CreateXor(OrOp1, ConstantInt::get(OrOp1->getType(), C));
2164 return new ICmpInst(Pred, OrOp0, NewC);
2165 }
2166
2167 const APInt *MaskC;
2168 if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
2169 if (*MaskC == C && (C + 1).isPowerOf2()) {
2170 // X | C == C --> X <=u C
2171 // X | C != C --> X >u C
2172 // iff C+1 is a power of 2 (C is a bitmask of the low bits)
2174 return new ICmpInst(Pred, OrOp0, OrOp1);
2175 }
2176
2177 // More general: canonicalize 'equality with set bits mask' to
2178 // 'equality with clear bits mask'.
2179 // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
2180 // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
2181 if (Or->hasOneUse()) {
2182 Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
2183 Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
2184 return new ICmpInst(Pred, And, NewC);
2185 }
2186 }
2187
2188 // (X | (X-1)) s< 0 --> X s< 1
2189 // (X | (X-1)) s> -1 --> X s> 0
2190 Value *X;
2191 bool TrueIfSigned;
2192 if (isSignBitCheck(Pred, C, TrueIfSigned) &&
2194 auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
2195 Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
2196 return new ICmpInst(NewPred, X, NewC);
2197 }
2198
2199 const APInt *OrC;
2200 // icmp(X | OrC, C) --> icmp(X, 0)
2201 if (C.isNonNegative() && match(Or, m_Or(m_Value(X), m_APInt(OrC)))) {
2202 switch (Pred) {
2203 // X | OrC s< C --> X s< 0 iff OrC s>= C s>= 0
2204 case ICmpInst::ICMP_SLT:
2205 // X | OrC s>= C --> X s>= 0 iff OrC s>= C s>= 0
2206 case ICmpInst::ICMP_SGE:
2207 if (OrC->sge(C))
2208 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
2209 break;
2210 // X | OrC s<= C --> X s< 0 iff OrC s> C s>= 0
2211 case ICmpInst::ICMP_SLE:
2212 // X | OrC s> C --> X s>= 0 iff OrC s> C s>= 0
2213 case ICmpInst::ICMP_SGT:
2214 if (OrC->sgt(C))
2216 ConstantInt::getNullValue(X->getType()));
2217 break;
2218 default:
2219 break;
2220 }
2221 }
2222
2223 if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
2224 return nullptr;
2225
2226 Value *P, *Q;
2228 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
2229 // -> and (icmp eq P, null), (icmp eq Q, null).
2230 Value *CmpP =
2231 Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
2232 Value *CmpQ =
2233 Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
2234 auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2235 return BinaryOperator::Create(BOpc, CmpP, CmpQ);
2236 }
2237
2238 if (Value *V = foldICmpOrXorSubChain(Cmp, Or, Builder))
2239 return replaceInstUsesWith(Cmp, V);
2240
2241 return nullptr;
2242}
2243
2244/// Fold icmp (mul X, Y), C.
2247 const APInt &C) {
2248 ICmpInst::Predicate Pred = Cmp.getPredicate();
2249 Type *MulTy = Mul->getType();
2250 Value *X = Mul->getOperand(0);
2251
2252 // If comparing a square with a constant, try simplifying to comparing square
2253 // roots.
2254 if (X == Mul->getOperand(1) && !Cmp.isSigned()) {
2255 APInt R = C.sqrtFloor();
2256 bool IsSqr = C == R * R;
2257
2258 // X * X eq/ne C
2259 if (Cmp.isEquality() &&
2260 (Mul->hasNoUnsignedWrap() || (Mul->hasNoSignedWrap() && C.isZero()))) {
2261
2262 // If constant is not a square, eq/ne is false/true respectively
2263 if (!IsSqr)
2264 return replaceInstUsesWith(
2265 Cmp,
2266 ConstantInt::getBool(Cmp.getType(), Pred == ICmpInst::ICMP_NE));
2267
2268 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2269 }
2270
2271 // If the multiply does not wrap
2272 // X * X pred C --> X pred R
2273 if (Mul->hasNoUnsignedWrap()) {
2274
2275 if (IsSqr)
2276 return new ICmpInst(Pred, X, ConstantInt::get(MulTy, R));
2277
2278 // If C is not a square, we use floor/ceil of sqrt(C).
2279 //
2280 // If LT or LE, we need R to be an overestimate of sqrt(C),
2281 // then use the strict predicate (LT->LT, LE->LT).
2282 //
2283 // If GT or GE, we need R to be an underestimate of sqrt(C),
2284 // then use the strict predicate (GT->GT, GE->GT).
2285 //
2286 // R is already an underestimate of sqrt(C) due to sqrtFloor.
2287 if (ICmpInst::isLT(Pred) || ICmpInst::isLE(Pred))
2288 ++R;
2289
2290 return new ICmpInst(Cmp.getStrictPredicate(), X,
2291 ConstantInt::get(MulTy, R));
2292 }
2293 }
2294
2295 const APInt *MulC;
2296 if (!match(Mul->getOperand(1), m_APInt(MulC)))
2297 return nullptr;
2298
2299 // If this is a test of the sign bit and the multiply is sign-preserving with
2300 // a constant operand, use the multiply LHS operand instead:
2301 // (X * +MulC) < 0 --> X < 0
2302 // (X * -MulC) < 0 --> X > 0
2303 if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
2304 if (MulC->isNegative())
2305 Pred = ICmpInst::getSwappedPredicate(Pred);
2306 return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
2307 }
2308
2309 if (MulC->isZero())
2310 return nullptr;
2311
2312 // If the multiply does not wrap or the constant is odd, try to divide the
2313 // compare constant by the multiplication factor.
2314 if (Cmp.isEquality()) {
2315 // (mul nsw X, MulC) eq/ne C --> X eq/ne C /s MulC
2316 if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
2317 Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
2318 return new ICmpInst(Pred, X, NewC);
2319 }
2320
2321 // C % MulC == 0 is weaker than we could use if MulC is odd because it
2322 // correct to transform if MulC * N == C including overflow. I.e with i8
2323 // (icmp eq (mul X, 5), 101) -> (icmp eq X, 225) but since 101 % 5 != 0, we
2324 // miss that case.
2325 if (C.urem(*MulC).isZero()) {
2326 // (mul nuw X, MulC) eq/ne C --> X eq/ne C /u MulC
2327 // (mul X, OddC) eq/ne N * C --> X eq/ne N
2328 if ((*MulC & 1).isOne() || Mul->hasNoUnsignedWrap()) {
2329 Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
2330 return new ICmpInst(Pred, X, NewC);
2331 }
2332 }
2333 }
2334
2335 // With a matching no-overflow guarantee, fold the constants:
2336 // (X * MulC) < C --> X < (C / MulC)
2337 // (X * MulC) > C --> X > (C / MulC)
2338 // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
2339 Constant *NewC = nullptr;
2340 if (Mul->hasNoSignedWrap() && ICmpInst::isSigned(Pred)) {
2341 // MININT / -1 --> overflow.
2342 if (C.isMinSignedValue() && MulC->isAllOnes())
2343 return nullptr;
2344 if (MulC->isNegative())
2345 Pred = ICmpInst::getSwappedPredicate(Pred);
2346
2347 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2348 NewC = ConstantInt::get(
2350 } else {
2351 assert((Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT) &&
2352 "Unexpected predicate");
2353 NewC = ConstantInt::get(
2355 }
2356 } else if (Mul->hasNoUnsignedWrap() && ICmpInst::isUnsigned(Pred)) {
2357 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) {
2358 NewC = ConstantInt::get(
2360 } else {
2361 assert((Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
2362 "Unexpected predicate");
2363 NewC = ConstantInt::get(
2365 }
2366 }
2367
2368 return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
2369}
2370
2371/// Fold icmp (shl nuw C2, Y), C.
2373 const APInt &C) {
2374 Value *Y;
2375 const APInt *C2;
2376 if (!match(Shl, m_NUWShl(m_APInt(C2), m_Value(Y))))
2377 return nullptr;
2378
2379 Type *ShiftType = Shl->getType();
2380 unsigned TypeBits = C.getBitWidth();
2381 ICmpInst::Predicate Pred = Cmp.getPredicate();
2382 if (Cmp.isUnsigned()) {
2383 if (C2->isZero() || C2->ugt(C))
2384 return nullptr;
2385 APInt Div, Rem;
2386 APInt::udivrem(C, *C2, Div, Rem);
2387 bool CIsPowerOf2 = Rem.isZero() && Div.isPowerOf2();
2388
2389 // (1 << Y) pred C -> Y pred Log2(C)
2390 if (!CIsPowerOf2) {
2391 // (1 << Y) < 30 -> Y <= 4
2392 // (1 << Y) <= 30 -> Y <= 4
2393 // (1 << Y) >= 30 -> Y > 4
2394 // (1 << Y) > 30 -> Y > 4
2395 if (Pred == ICmpInst::ICMP_ULT)
2396 Pred = ICmpInst::ICMP_ULE;
2397 else if (Pred == ICmpInst::ICMP_UGE)
2398 Pred = ICmpInst::ICMP_UGT;
2399 }
2400
2401 unsigned CLog2 = Div.logBase2();
2402 return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
2403 } else if (Cmp.isSigned() && C2->isOne()) {
2404 Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
2405 // (1 << Y) > 0 -> Y != 31
2406 // (1 << Y) > C -> Y != 31 if C is negative.
2407 if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
2408 return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
2409
2410 // (1 << Y) < 0 -> Y == 31
2411 // (1 << Y) < 1 -> Y == 31
2412 // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
2413 // Exclude signed min by subtracting 1 and lower the upper bound to 0.
2414 if (Pred == ICmpInst::ICMP_SLT && (C - 1).sle(0))
2415 return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
2416 }
2417
2418 return nullptr;
2419}
2420
2421/// Fold icmp (shl X, Y), C.
2423 BinaryOperator *Shl,
2424 const APInt &C) {
2425 const APInt *ShiftVal;
2426 if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
2427 return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
2428
2429 ICmpInst::Predicate Pred = Cmp.getPredicate();
2430 // (icmp pred (shl nuw&nsw X, Y), Csle0)
2431 // -> (icmp pred X, Csle0)
2432 //
2433 // The idea is the nuw/nsw essentially freeze the sign bit for the shift op
2434 // so X's must be what is used.
2435 if (C.sle(0) && Shl->hasNoUnsignedWrap() && Shl->hasNoSignedWrap())
2436 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2437
2438 // (icmp eq/ne (shl nuw|nsw X, Y), 0)
2439 // -> (icmp eq/ne X, 0)
2440 if (ICmpInst::isEquality(Pred) && C.isZero() &&
2441 (Shl->hasNoUnsignedWrap() || Shl->hasNoSignedWrap()))
2442 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2443
2444 // (icmp slt (shl nsw X, Y), 0/1)
2445 // -> (icmp slt X, 0/1)
2446 // (icmp sgt (shl nsw X, Y), 0/-1)
2447 // -> (icmp sgt X, 0/-1)
2448 //
2449 // NB: sge/sle with a constant will canonicalize to sgt/slt.
2450 if (Shl->hasNoSignedWrap() &&
2451 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT))
2452 if (C.isZero() || (Pred == ICmpInst::ICMP_SGT ? C.isAllOnes() : C.isOne()))
2453 return new ICmpInst(Pred, Shl->getOperand(0), Cmp.getOperand(1));
2454
2455 const APInt *ShiftAmt;
2456 if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
2457 return foldICmpShlLHSC(Cmp, Shl, C);
2458
2459 // Check that the shift amount is in range. If not, don't perform undefined
2460 // shifts. When the shift is visited, it will be simplified.
2461 unsigned TypeBits = C.getBitWidth();
2462 if (ShiftAmt->uge(TypeBits))
2463 return nullptr;
2464
2465 Value *X = Shl->getOperand(0);
2466 Type *ShType = Shl->getType();
2467
2468 // NSW guarantees that we are only shifting out sign bits from the high bits,
2469 // so we can ASHR the compare constant without needing a mask and eliminate
2470 // the shift.
2471 if (Shl->hasNoSignedWrap()) {
2472 if (Pred == ICmpInst::ICMP_SGT) {
2473 // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
2474 APInt ShiftedC = C.ashr(*ShiftAmt);
2475 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2476 }
2477 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2478 C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
2479 APInt ShiftedC = C.ashr(*ShiftAmt);
2480 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2481 }
2482 if (Pred == ICmpInst::ICMP_SLT) {
2483 // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
2484 // (X << S) <=s C is equiv to X <=s (C >> S) for all C
2485 // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
2486 // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
2487 assert(!C.isMinSignedValue() && "Unexpected icmp slt");
2488 APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
2489 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2490 }
2491 }
2492
2493 // NUW guarantees that we are only shifting out zero bits from the high bits,
2494 // so we can LSHR the compare constant without needing a mask and eliminate
2495 // the shift.
2496 if (Shl->hasNoUnsignedWrap()) {
2497 if (Pred == ICmpInst::ICMP_UGT) {
2498 // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
2499 APInt ShiftedC = C.lshr(*ShiftAmt);
2500 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2501 }
2502 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2503 C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
2504 APInt ShiftedC = C.lshr(*ShiftAmt);
2505 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2506 }
2507 if (Pred == ICmpInst::ICMP_ULT) {
2508 // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
2509 // (X << S) <=u C is equiv to X <=u (C >> S) for all C
2510 // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
2511 // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
2512 assert(C.ugt(0) && "ult 0 should have been eliminated");
2513 APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
2514 return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
2515 }
2516 }
2517
2518 if (Cmp.isEquality() && Shl->hasOneUse()) {
2519 // Strength-reduce the shift into an 'and'.
2520 Constant *Mask = ConstantInt::get(
2521 ShType,
2522 APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
2523 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2524 Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
2525 return new ICmpInst(Pred, And, LShrC);
2526 }
2527
2528 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
2529 bool TrueIfSigned = false;
2530 if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
2531 // (X << 31) <s 0 --> (X & 1) != 0
2532 Constant *Mask = ConstantInt::get(
2533 ShType,
2534 APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
2535 Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
2536 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
2537 And, Constant::getNullValue(ShType));
2538 }
2539
2540 // Simplify 'shl' inequality test into 'and' equality test.
2541 if (Cmp.isUnsigned() && Shl->hasOneUse()) {
2542 // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
2543 if ((C + 1).isPowerOf2() &&
2544 (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
2545 Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
2546 return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
2548 And, Constant::getNullValue(ShType));
2549 }
2550 // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
2551 if (C.isPowerOf2() &&
2552 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
2553 Value *And =
2554 Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
2555 return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
2557 And, Constant::getNullValue(ShType));
2558 }
2559 }
2560
2561 // Transform (icmp pred iM (shl iM %v, N), C)
2562 // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
2563 // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
2564 // This enables us to get rid of the shift in favor of a trunc that may be
2565 // free on the target. It has the additional benefit of comparing to a
2566 // smaller constant that may be more target-friendly.
2567 unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
2568 if (Shl->hasOneUse() && Amt != 0 &&
2569 shouldChangeType(ShType->getScalarSizeInBits(), TypeBits - Amt)) {
2570 ICmpInst::Predicate CmpPred = Pred;
2571 APInt RHSC = C;
2572
2573 if (RHSC.countr_zero() < Amt && ICmpInst::isStrictPredicate(CmpPred)) {
2574 // Try the flipped strictness predicate.
2575 // e.g.:
2576 // icmp ult i64 (shl X, 32), 8589934593 ->
2577 // icmp ule i64 (shl X, 32), 8589934592 ->
2578 // icmp ule i32 (trunc X, i32), 2 ->
2579 // icmp ult i32 (trunc X, i32), 3
2580 if (auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(
2581 Pred, ConstantInt::get(ShType->getContext(), C))) {
2582 CmpPred = FlippedStrictness->first;
2583 RHSC = cast<ConstantInt>(FlippedStrictness->second)->getValue();
2584 }
2585 }
2586
2587 if (RHSC.countr_zero() >= Amt) {
2588 Type *TruncTy = ShType->getWithNewBitWidth(TypeBits - Amt);
2589 Constant *NewC =
2590 ConstantInt::get(TruncTy, RHSC.ashr(*ShiftAmt).trunc(TypeBits - Amt));
2591 return new ICmpInst(CmpPred,
2592 Builder.CreateTrunc(X, TruncTy, "", /*IsNUW=*/false,
2593 Shl->hasNoSignedWrap()),
2594 NewC);
2595 }
2596 }
2597
2598 return nullptr;
2599}
2600
2601/// Fold icmp ({al}shr X, Y), C.
2603 BinaryOperator *Shr,
2604 const APInt &C) {
2605 // An exact shr only shifts out zero bits, so:
2606 // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
2607 Value *X = Shr->getOperand(0);
2608 CmpInst::Predicate Pred = Cmp.getPredicate();
2609 if (Cmp.isEquality() && Shr->isExact() && C.isZero())
2610 return new ICmpInst(Pred, X, Cmp.getOperand(1));
2611
2612 bool IsAShr = Shr->getOpcode() == Instruction::AShr;
2613 const APInt *ShiftValC;
2614 if (match(X, m_APInt(ShiftValC))) {
2615 if (Cmp.isEquality())
2616 return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
2617
2618 // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
2619 // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
2620 bool TrueIfSigned;
2621 if (!IsAShr && ShiftValC->isNegative() &&
2622 isSignBitCheck(Pred, C, TrueIfSigned))
2623 return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
2624 Shr->getOperand(1),
2625 ConstantInt::getNullValue(X->getType()));
2626
2627 // If the shifted constant is a power-of-2, test the shift amount directly:
2628 // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
2629 // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
2630 if (!IsAShr && ShiftValC->isPowerOf2() &&
2631 (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
2632 bool IsUGT = Pred == CmpInst::ICMP_UGT;
2633 assert(ShiftValC->uge(C) && "Expected simplify of compare");
2634 assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
2635
2636 unsigned CmpLZ = IsUGT ? C.countl_zero() : (C - 1).countl_zero();
2637 unsigned ShiftLZ = ShiftValC->countl_zero();
2638 Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
2639 auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
2640 return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
2641 }
2642 }
2643
2644 const APInt *ShiftAmtC;
2645 if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
2646 return nullptr;
2647
2648 // Check that the shift amount is in range. If not, don't perform undefined
2649 // shifts. When the shift is visited it will be simplified.
2650 unsigned TypeBits = C.getBitWidth();
2651 unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
2652 if (ShAmtVal >= TypeBits || ShAmtVal == 0)
2653 return nullptr;
2654
2655 bool IsExact = Shr->isExact();
2656 Type *ShrTy = Shr->getType();
2657 // TODO: If we could guarantee that InstSimplify would handle all of the
2658 // constant-value-based preconditions in the folds below, then we could assert
2659 // those conditions rather than checking them. This is difficult because of
2660 // undef/poison (PR34838).
2661 if (IsAShr && Shr->hasOneUse()) {
2662 if (IsExact && (Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) &&
2663 (C - 1).isPowerOf2() && C.countLeadingZeros() > ShAmtVal) {
2664 // When C - 1 is a power of two and the transform can be legally
2665 // performed, prefer this form so the produced constant is close to a
2666 // power of two.
2667 // icmp slt/ult (ashr exact X, ShAmtC), C
2668 // --> icmp slt/ult X, (C - 1) << ShAmtC) + 1
2669 APInt ShiftedC = (C - 1).shl(ShAmtVal) + 1;
2670 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2671 }
2672 if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
2673 // When ShAmtC can be shifted losslessly:
2674 // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
2675 // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
2676 APInt ShiftedC = C.shl(ShAmtVal);
2677 if (ShiftedC.ashr(ShAmtVal) == C)
2678 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2679 }
2680 if (Pred == CmpInst::ICMP_SGT) {
2681 // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
2682 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2683 if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
2684 (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
2685 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2686 }
2687 if (Pred == CmpInst::ICMP_UGT) {
2688 // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2689 // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
2690 // clause accounts for that pattern.
2691 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2692 if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
2693 (C + 1).shl(ShAmtVal).isMinSignedValue())
2694 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2695 }
2696
2697 // If the compare constant has significant bits above the lowest sign-bit,
2698 // then convert an unsigned cmp to a test of the sign-bit:
2699 // (ashr X, ShiftC) u> C --> X s< 0
2700 // (ashr X, ShiftC) u< C --> X s> -1
2701 if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
2702 if (Pred == CmpInst::ICMP_UGT) {
2703 return new ICmpInst(CmpInst::ICMP_SLT, X,
2705 }
2706 if (Pred == CmpInst::ICMP_ULT) {
2707 return new ICmpInst(CmpInst::ICMP_SGT, X,
2709 }
2710 }
2711 } else if (!IsAShr) {
2712 if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
2713 // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
2714 // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
2715 APInt ShiftedC = C.shl(ShAmtVal);
2716 if (ShiftedC.lshr(ShAmtVal) == C)
2717 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2718 }
2719 if (Pred == CmpInst::ICMP_UGT) {
2720 // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
2721 APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
2722 if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
2723 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
2724 }
2725 }
2726
2727 if (!Cmp.isEquality())
2728 return nullptr;
2729
2730 // Handle equality comparisons of shift-by-constant.
2731
2732 // If the comparison constant changes with the shift, the comparison cannot
2733 // succeed (bits of the comparison constant cannot match the shifted value).
2734 // This should be known by InstSimplify and already be folded to true/false.
2735 assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
2736 (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
2737 "Expected icmp+shr simplify did not occur.");
2738
2739 // If the bits shifted out are known zero, compare the unshifted value:
2740 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
2741 if (Shr->isExact())
2742 return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
2743
2744 if (Shr->hasOneUse()) {
2745 // Canonicalize the shift into an 'and':
2746 // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
2747 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
2748 Constant *Mask = ConstantInt::get(ShrTy, Val);
2749 Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
2750 return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
2751 }
2752
2753 return nullptr;
2754}
2755
2757 BinaryOperator *SRem,
2758 const APInt &C) {
2759 const ICmpInst::Predicate Pred = Cmp.getPredicate();
2760 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT) {
2761 // Canonicalize unsigned predicates to signed:
2762 // (X s% DivisorC) u> C -> (X s% DivisorC) s< 0
2763 // iff (C s< 0 ? ~C : C) u>= abs(DivisorC)-1
2764 // (X s% DivisorC) u< C+1 -> (X s% DivisorC) s> -1
2765 // iff (C+1 s< 0 ? ~C : C) u>= abs(DivisorC)-1
2766
2767 const APInt *DivisorC;
2768 if (!match(SRem->getOperand(1), m_APInt(DivisorC)))
2769 return nullptr;
2770 if (DivisorC->isZero())
2771 return nullptr;
2772
2773 APInt NormalizedC = C;
2774 if (Pred == ICmpInst::ICMP_ULT) {
2775 assert(!NormalizedC.isZero() &&
2776 "ult X, 0 should have been simplified already.");
2777 --NormalizedC;
2778 }
2779 if (C.isNegative())
2780 NormalizedC.flipAllBits();
2781 if (!NormalizedC.uge(DivisorC->abs() - 1))
2782 return nullptr;
2783
2784 Type *Ty = SRem->getType();
2785 if (Pred == ICmpInst::ICMP_UGT)
2786 return new ICmpInst(ICmpInst::ICMP_SLT, SRem,
2788 return new ICmpInst(ICmpInst::ICMP_SGT, SRem,
2790 }
2791 // Match an 'is positive' or 'is negative' comparison of remainder by a
2792 // constant power-of-2 value:
2793 // (X % pow2C) sgt/slt 0
2794 if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
2795 Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2796 return nullptr;
2797
2798 // TODO: The one-use check is standard because we do not typically want to
2799 // create longer instruction sequences, but this might be a special-case
2800 // because srem is not good for analysis or codegen.
2801 if (!SRem->hasOneUse())
2802 return nullptr;
2803
2804 const APInt *DivisorC;
2805 if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
2806 return nullptr;
2807
2808 // For cmp_sgt/cmp_slt only zero valued C is handled.
2809 // For cmp_eq/cmp_ne only positive valued C is handled.
2810 if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
2811 !C.isZero()) ||
2812 ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2813 !C.isStrictlyPositive()))
2814 return nullptr;
2815
2816 // Mask off the sign bit and the modulo bits (low-bits).
2817 Type *Ty = SRem->getType();
2818 APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
2819 Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
2820 Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
2821
2822 if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
2823 return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
2824
2825 // For 'is positive?' check that the sign-bit is clear and at least 1 masked
2826 // bit is set. Example:
2827 // (i8 X % 32) s> 0 --> (X & 159) s> 0
2828 if (Pred == ICmpInst::ICMP_SGT)
2830
2831 // For 'is negative?' check that the sign-bit is set and at least 1 masked
2832 // bit is set. Example:
2833 // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
2834 return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
2835}
2836
2837/// Fold icmp (udiv X, Y), C.
2839 BinaryOperator *UDiv,
2840 const APInt &C) {
2841 ICmpInst::Predicate Pred = Cmp.getPredicate();
2842 Value *X = UDiv->getOperand(0);
2843 Value *Y = UDiv->getOperand(1);
2844 Type *Ty = UDiv->getType();
2845
2846 const APInt *C2;
2847 if (!match(X, m_APInt(C2)))
2848 return nullptr;
2849
2850 assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
2851
2852 // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
2853 if (Pred == ICmpInst::ICMP_UGT) {
2854 assert(!C.isMaxValue() &&
2855 "icmp ugt X, UINT_MAX should have been simplified already.");
2856 return new ICmpInst(ICmpInst::ICMP_ULE, Y,
2857 ConstantInt::get(Ty, C2->udiv(C + 1)));
2858 }
2859
2860 // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
2861 if (Pred == ICmpInst::ICMP_ULT) {
2862 assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
2863 return new ICmpInst(ICmpInst::ICMP_UGT, Y,
2864 ConstantInt::get(Ty, C2->udiv(C)));
2865 }
2866
2867 return nullptr;
2868}
2869
2870/// Fold icmp ({su}div X, Y), C.
2872 BinaryOperator *Div,
2873 const APInt &C) {
2874 ICmpInst::Predicate Pred = Cmp.getPredicate();
2875 Value *X = Div->getOperand(0);
2876 Value *Y = Div->getOperand(1);
2877 Type *Ty = Div->getType();
2878 bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
2879
2880 // If unsigned division and the compare constant is bigger than
2881 // UMAX/2 (negative), there's only one pair of values that satisfies an
2882 // equality check, so eliminate the division:
2883 // (X u/ Y) == C --> (X == C) && (Y == 1)
2884 // (X u/ Y) != C --> (X != C) || (Y != 1)
2885 // Similarly, if signed division and the compare constant is exactly SMIN:
2886 // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
2887 // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
2888 if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
2889 (!DivIsSigned || C.isMinSignedValue())) {
2890 Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
2891 Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
2892 auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
2893 return BinaryOperator::Create(Logic, XBig, YOne);
2894 }
2895
2896 // Fold: icmp pred ([us]div X, C2), C -> range test
2897 // Fold this div into the comparison, producing a range check.
2898 // Determine, based on the divide type, what the range is being
2899 // checked. If there is an overflow on the low or high side, remember
2900 // it, otherwise compute the range [low, hi) bounding the new value.
2901 // See: InsertRangeTest above for the kinds of replacements possible.
2902 const APInt *C2;
2903 if (!match(Y, m_APInt(C2)))
2904 return nullptr;
2905
2906 // FIXME: If the operand types don't match the type of the divide
2907 // then don't attempt this transform. The code below doesn't have the
2908 // logic to deal with a signed divide and an unsigned compare (and
2909 // vice versa). This is because (x /s C2) <s C produces different
2910 // results than (x /s C2) <u C or (x /u C2) <s C or even
2911 // (x /u C2) <u C. Simply casting the operands and result won't
2912 // work. :( The if statement below tests that condition and bails
2913 // if it finds it.
2914 // However, when the divisor is a positive constant and the dividend is
2915 // known non-negative, sdiv is equivalent to udiv, so we can lower
2916 // DivIsSigned and proceed through the unsigned path.
2917 if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned()) {
2918 if (!DivIsSigned || !C2->isStrictlyPositive() ||
2919 !isKnownNonNegative(X, SQ.getWithInstruction(&Cmp)))
2920 return nullptr;
2921 DivIsSigned = false;
2922 }
2923
2924 // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
2925 // INT_MIN will also fail if the divisor is 1. Although folds of all these
2926 // division-by-constant cases should be present, we can not assert that they
2927 // have happened before we reach this icmp instruction.
2928 if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
2929 return nullptr;
2930
2931 // Compute Prod = C * C2. We are essentially solving an equation of
2932 // form X / C2 = C. We solve for X by multiplying C2 and C.
2933 // By solving for X, we can turn this into a range check instead of computing
2934 // a divide.
2935 APInt Prod = C * *C2;
2936
2937 // Determine if the product overflows by seeing if the product is not equal to
2938 // the divide. Make sure we do the same kind of divide as in the LHS
2939 // instruction that we're folding.
2940 bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
2941
2942 // If the division is known to be exact, then there is no remainder from the
2943 // divide, so the covered range size is unit, otherwise it is the divisor.
2944 APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
2945
2946 // Figure out the interval that is being checked. For example, a comparison
2947 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
2948 // Compute this interval based on the constants involved and the signedness of
2949 // the compare/divide. This computes a half-open interval, keeping track of
2950 // whether either value in the interval overflows. After analysis each
2951 // overflow variable is set to 0 if it's corresponding bound variable is valid
2952 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
2953 int LoOverflow = 0, HiOverflow = 0;
2954 APInt LoBound, HiBound;
2955
2956 if (!DivIsSigned) { // udiv
2957 // e.g. X/5 op 3 --> [15, 20)
2958 LoBound = Prod;
2959 HiOverflow = LoOverflow = ProdOV;
2960 if (!HiOverflow) {
2961 // If this is not an exact divide, then many values in the range collapse
2962 // to the same result value.
2963 HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
2964 }
2965 } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
2966 if (C.isZero()) { // (X / pos) op 0
2967 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
2968 LoBound = -(RangeSize - 1);
2969 HiBound = RangeSize;
2970 } else if (C.isStrictlyPositive()) { // (X / pos) op pos
2971 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
2972 HiOverflow = LoOverflow = ProdOV;
2973 if (!HiOverflow)
2974 HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
2975 } else { // (X / pos) op neg
2976 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
2977 HiBound = Prod + 1;
2978 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
2979 if (!LoOverflow) {
2980 APInt DivNeg = -RangeSize;
2981 LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
2982 }
2983 }
2984 } else if (C2->isNegative()) { // Divisor is < 0.
2985 if (Div->isExact())
2986 RangeSize.negate();
2987 if (C.isZero()) { // (X / neg) op 0
2988 // e.g. X/-5 op 0 --> [-4, 5)
2989 LoBound = RangeSize + 1;
2990 HiBound = -RangeSize;
2991 if (HiBound == *C2) { // -INTMIN = INTMIN
2992 HiOverflow = 1; // [INTMIN+1, overflow)
2993 HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
2994 }
2995 } else if (C.isStrictlyPositive()) { // (X / neg) op pos
2996 // e.g. X/-5 op 3 --> [-19, -14)
2997 HiBound = Prod + 1;
2998 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
2999 if (!LoOverflow)
3000 LoOverflow =
3001 addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
3002 } else { // (X / neg) op neg
3003 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
3004 LoOverflow = HiOverflow = ProdOV;
3005 if (!HiOverflow)
3006 HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
3007 }
3008
3009 // Dividing by a negative swaps the condition. LT <-> GT
3010 Pred = ICmpInst::getSwappedPredicate(Pred);
3011 }
3012
3013 switch (Pred) {
3014 default:
3015 llvm_unreachable("Unhandled icmp predicate!");
3016 case ICmpInst::ICMP_EQ:
3017 if (LoOverflow && HiOverflow)
3018 return replaceInstUsesWith(Cmp, Builder.getFalse());
3019 if (HiOverflow)
3020 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3021 X, ConstantInt::get(Ty, LoBound));
3022 if (LoOverflow)
3023 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3024 X, ConstantInt::get(Ty, HiBound));
3025 return replaceInstUsesWith(
3026 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
3027 case ICmpInst::ICMP_NE:
3028 if (LoOverflow && HiOverflow)
3029 return replaceInstUsesWith(Cmp, Builder.getTrue());
3030 if (HiOverflow)
3031 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3032 X, ConstantInt::get(Ty, LoBound));
3033 if (LoOverflow)
3034 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
3035 X, ConstantInt::get(Ty, HiBound));
3036 return replaceInstUsesWith(
3037 Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
3038 case ICmpInst::ICMP_ULT:
3039 case ICmpInst::ICMP_SLT:
3040 if (LoOverflow == +1) // Low bound is greater than input range.
3041 return replaceInstUsesWith(Cmp, Builder.getTrue());
3042 if (LoOverflow == -1) // Low bound is less than input range.
3043 return replaceInstUsesWith(Cmp, Builder.getFalse());
3044 return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
3045 case ICmpInst::ICMP_UGT:
3046 case ICmpInst::ICMP_SGT:
3047 if (HiOverflow == +1) // High bound greater than input range.
3048 return replaceInstUsesWith(Cmp, Builder.getFalse());
3049 if (HiOverflow == -1) // High bound less than input range.
3050 return replaceInstUsesWith(Cmp, Builder.getTrue());
3051 if (Pred == ICmpInst::ICMP_UGT)
3052 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
3053 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
3054 }
3055
3056 return nullptr;
3057}
3058
3059/// Fold icmp (sub X, Y), C.
3062 const APInt &C) {
3063 Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
3064 ICmpInst::Predicate Pred = Cmp.getPredicate();
3065 Type *Ty = Sub->getType();
3066
3067 // (X - (X urem D)) is D*(X/D), a multiple of D, so it is u> C exactly when
3068 // X u>= D (for C u< D), and u< C exactly when X u< D (for 0 u< C u<= D):
3069 // icmp ugt (sub X, (urem X, D)), C --> icmp ugt X, D-1
3070 // icmp ult (sub X, (urem X, D)), C --> icmp ult X, D
3071 const APInt *D;
3072 if (match(Y, m_URem(m_Specific(X), m_APInt(D))) && !D->isZero()) {
3073 if (Pred == ICmpInst::ICMP_UGT && C.ult(*D))
3074 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, *D - 1));
3075 if (Pred == ICmpInst::ICMP_ULT && !C.isZero() && C.ule(*D))
3076 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, *D));
3077 }
3078
3079 // (SubC - Y) == C) --> Y == (SubC - C)
3080 // (SubC - Y) != C) --> Y != (SubC - C)
3081 Constant *SubC;
3082 if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
3083 return new ICmpInst(Pred, Y,
3084 ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
3085 }
3086
3087 // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
3088 const APInt *C2;
3089 APInt SubResult;
3090 ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
3091 bool HasNSW = Sub->hasNoSignedWrap();
3092 bool HasNUW = Sub->hasNoUnsignedWrap();
3093 if (match(X, m_APInt(C2)) &&
3094 ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
3095 !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
3096 return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
3097
3098 // X - Y == 0 --> X == Y.
3099 // X - Y != 0 --> X != Y.
3100 // TODO: We allow this with multiple uses as long as the other uses are not
3101 // in phis. The phi use check is guarding against a codegen regression
3102 // for a loop test. If the backend could undo this (and possibly
3103 // subsequent transforms), we would not need this hack.
3104 if (Cmp.isEquality() && C.isZero() &&
3105 none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
3106 return new ICmpInst(Pred, X, Y);
3107
3108 // The following transforms are only worth it if the only user of the subtract
3109 // is the icmp.
3110 // TODO: This is an artificial restriction for all of the transforms below
3111 // that only need a single replacement icmp. Can these use the phi test
3112 // like the transform above here?
3113 if (!Sub->hasOneUse())
3114 return nullptr;
3115
3116 if (Sub->hasNoSignedWrap()) {
3117 // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
3118 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
3119 return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
3120
3121 // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
3122 if (Pred == ICmpInst::ICMP_SGT && C.isZero())
3123 return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
3124
3125 // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
3126 if (Pred == ICmpInst::ICMP_SLT && C.isZero())
3127 return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
3128
3129 // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
3130 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
3131 return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
3132 }
3133
3134 if (!match(X, m_APInt(C2)))
3135 return nullptr;
3136
3137 // C2 - Y <u C -> (Y | (C - 1)) == C2
3138 // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
3139 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
3140 (*C2 & (C - 1)) == (C - 1))
3141 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
3142
3143 // C2 - Y >u C -> (Y | C) != C2
3144 // iff C2 & C == C and C + 1 is a power of 2
3145 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
3146 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
3147
3148 // We have handled special cases that reduce.
3149 // Canonicalize any remaining sub to add as:
3150 // (C2 - Y) > C --> (Y + ~C2) < ~C
3151 Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
3152 HasNUW, HasNSW);
3153 return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
3154}
3155
3156static Value *createLogicFromTable(const std::bitset<4> &Table, Value *Op0,
3157 Value *Op1, IRBuilderBase &Builder,
3158 bool HasOneUse) {
3159 auto FoldConstant = [&](bool Val) {
3160 Constant *Res = Val ? Builder.getTrue() : Builder.getFalse();
3161 if (Op0->getType()->isVectorTy())
3163 cast<VectorType>(Op0->getType())->getElementCount(), Res);
3164 return Res;
3165 };
3166
3167 switch (Table.to_ulong()) {
3168 case 0: // 0 0 0 0
3169 return FoldConstant(false);
3170 case 1: // 0 0 0 1
3171 return HasOneUse ? Builder.CreateNot(Builder.CreateOr(Op0, Op1)) : nullptr;
3172 case 2: // 0 0 1 0
3173 return HasOneUse ? Builder.CreateAnd(Builder.CreateNot(Op0), Op1) : nullptr;
3174 case 3: // 0 0 1 1
3175 return Builder.CreateNot(Op0);
3176 case 4: // 0 1 0 0
3177 return HasOneUse ? Builder.CreateAnd(Op0, Builder.CreateNot(Op1)) : nullptr;
3178 case 5: // 0 1 0 1
3179 return Builder.CreateNot(Op1);
3180 case 6: // 0 1 1 0
3181 return Builder.CreateXor(Op0, Op1);
3182 case 7: // 0 1 1 1
3183 return HasOneUse ? Builder.CreateNot(Builder.CreateAnd(Op0, Op1)) : nullptr;
3184 case 8: // 1 0 0 0
3185 return Builder.CreateAnd(Op0, Op1);
3186 case 9: // 1 0 0 1
3187 return HasOneUse ? Builder.CreateNot(Builder.CreateXor(Op0, Op1)) : nullptr;
3188 case 10: // 1 0 1 0
3189 return Op1;
3190 case 11: // 1 0 1 1
3191 return HasOneUse ? Builder.CreateOr(Builder.CreateNot(Op0), Op1) : nullptr;
3192 case 12: // 1 1 0 0
3193 return Op0;
3194 case 13: // 1 1 0 1
3195 return HasOneUse ? Builder.CreateOr(Op0, Builder.CreateNot(Op1)) : nullptr;
3196 case 14: // 1 1 1 0
3197 return Builder.CreateOr(Op0, Op1);
3198 case 15: // 1 1 1 1
3199 return FoldConstant(true);
3200 default:
3201 llvm_unreachable("Invalid Operation");
3202 }
3203 return nullptr;
3204}
3205
3207 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3208 Value *A, *B;
3209 Constant *C1, *C2, *C3, *C4;
3210 if (!match(BO->getOperand(0),
3212 !match(BO->getOperand(1),
3214 Cmp.getType() != A->getType() || Cmp.getType() != B->getType())
3215 return nullptr;
3216
3217 std::bitset<4> Table;
3218 auto ComputeTable = [&](bool First, bool Second) -> std::optional<bool> {
3219 Constant *L = First ? C1 : C2;
3220 Constant *R = Second ? C3 : C4;
3221 if (auto *Res = ConstantFoldBinaryOpOperands(BO->getOpcode(), L, R, DL)) {
3222 auto *Val = Res->getType()->isVectorTy() ? Res->getSplatValue() : Res;
3223 if (auto *CI = dyn_cast_or_null<ConstantInt>(Val))
3224 return ICmpInst::compare(CI->getValue(), C, Cmp.getPredicate());
3225 }
3226 return std::nullopt;
3227 };
3228
3229 for (unsigned I = 0; I < 4; ++I) {
3230 bool First = (I >> 1) & 1;
3231 bool Second = I & 1;
3232 if (auto Res = ComputeTable(First, Second))
3233 Table[I] = *Res;
3234 else
3235 return nullptr;
3236 }
3237
3238 // Synthesize optimal logic.
3239 if (auto *Cond = createLogicFromTable(Table, A, B, Builder, BO->hasOneUse()))
3240 return replaceInstUsesWith(Cmp, Cond);
3241 return nullptr;
3242}
3243
3244/// Fold icmp (add X, Y), C.
3247 const APInt &C) {
3248 Value *Y = Add->getOperand(1);
3249 Value *X = Add->getOperand(0);
3250 const CmpPredicate Pred = Cmp.getCmpPredicate();
3251
3252 // icmp ult (add nuw A, (lshr A, ShAmtC)), C --> icmp ult A, C
3253 // when C <= (1 << ShAmtC).
3254 const APInt *ShAmtC;
3255 Value *A;
3256 unsigned BitWidth = C.getBitWidth();
3257 if (Pred == ICmpInst::ICMP_ULT &&
3258 match(Add,
3259 m_c_NUWAdd(m_Value(A), m_LShr(m_Deferred(A), m_APInt(ShAmtC)))) &&
3260 ShAmtC->ult(BitWidth) &&
3261 C.ule(APInt::getOneBitSet(BitWidth, ShAmtC->getZExtValue())))
3262 return new ICmpInst(Pred, A, ConstantInt::get(A->getType(), C));
3263
3264 const APInt *C2;
3265 if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
3266 return nullptr;
3267
3268 // Fold icmp pred (add X, C2), C.
3269 Type *Ty = Add->getType();
3270
3271 // If the add does not wrap, we can always adjust the compare by subtracting
3272 // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
3273 // have been canonicalized to SGT/SLT/UGT/ULT.
3274 if (Add->hasNoUnsignedWrap() &&
3275 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT)) {
3276 bool Overflow;
3277 APInt NewC = C.usub_ov(*C2, Overflow);
3278 // If there is overflow, the result must be true or false.
3279 if (!Overflow)
3280 // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
3281 return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
3282 }
3283
3284 CmpInst::Predicate ChosenPred = Pred.getPreferredSignedPredicate();
3285
3286 if (Add->hasNoSignedWrap() &&
3287 (ChosenPred == ICmpInst::ICMP_SGT || ChosenPred == ICmpInst::ICMP_SLT)) {
3288 bool Overflow;
3289 APInt NewC = C.ssub_ov(*C2, Overflow);
3290 if (!Overflow)
3291 // icmp samesign ugt/ult (add nsw X, C2), C
3292 // -> icmp sgt/slt X, (C - C2)
3293 return new ICmpInst(ChosenPred, X, ConstantInt::get(Ty, NewC));
3294 }
3295
3296 if (ICmpInst::isUnsigned(Pred) && Add->hasNoSignedWrap() &&
3297 C.isNonNegative() && (C - *C2).isNonNegative() &&
3298 computeConstantRange(X, /*ForSigned=*/true, SQ.getWithInstruction(&Cmp))
3299 .add(*C2)
3300 .isAllNonNegative())
3301 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), X,
3302 ConstantInt::get(Ty, C - *C2));
3303
3304 auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
3305 const APInt &Upper = CR.getUpper();
3306 const APInt &Lower = CR.getLower();
3307 if (Cmp.isSigned()) {
3308 if (Lower.isSignMask())
3309 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
3310 if (Upper.isSignMask())
3311 return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
3312 } else {
3313 if (Lower.isMinValue())
3314 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
3315 if (Upper.isMinValue())
3316 return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
3317 }
3318
3319 // This set of folds is intentionally placed after folds that use no-wrapping
3320 // flags because those folds are likely better for later analysis/codegen.
3321 const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
3322 const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
3323
3324 // Fold compare with offset to opposite sign compare if it eliminates offset:
3325 // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
3326 if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
3327 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
3328
3329 // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
3330 if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
3331 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
3332
3333 // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
3334 if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
3335 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
3336
3337 // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
3338 if (Pred == CmpInst::ICMP_SLT && C == *C2)
3339 return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
3340
3341 // (X + -1) <u C --> X <=u C (if X is never null)
3342 if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
3343 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3344 if (llvm::isKnownNonZero(X, Q))
3345 return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
3346 }
3347
3348 if (!Add->hasOneUse())
3349 return nullptr;
3350
3351 // X+C <u C2 -> (X & -C2) == C
3352 // iff C & (C2-1) == 0
3353 // C2 is a power of 2
3354 if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
3355 return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
3357
3358 // X+C2 <u C -> (X & C) == 2C
3359 // iff C == -(C2)
3360 // C2 is a power of 2
3361 if (Pred == ICmpInst::ICMP_ULT && C2->isPowerOf2() && C == -*C2)
3362 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, C),
3363 ConstantInt::get(Ty, C * 2));
3364
3365 // X+C >u C2 -> (X & ~C2) != C
3366 // iff C & C2 == 0
3367 // C2+1 is a power of 2
3368 if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
3369 return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
3371
3372 // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
3373 // to the ult form.
3374 // X+C2 >u C -> X+(C2-C-1) <u ~C
3375 if (Pred == ICmpInst::ICMP_UGT)
3376 return new ICmpInst(ICmpInst::ICMP_ULT,
3377 Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
3378 ConstantInt::get(Ty, ~C));
3379
3380 // zext(V) + C2 pred C -> V + C3 pred' C4
3381 Value *V;
3382 if (match(X, m_ZExt(m_Value(V)))) {
3383 Type *NewCmpTy = V->getType();
3384 unsigned NewCmpBW = NewCmpTy->getScalarSizeInBits();
3385 if (shouldChangeType(Ty, NewCmpTy)) {
3386 ConstantRange SrcCR = CR.truncate(NewCmpBW, TruncInst::NoUnsignedWrap);
3387 CmpInst::Predicate EquivPred;
3388 APInt EquivInt;
3389 APInt EquivOffset;
3390
3391 SrcCR.getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
3392 return new ICmpInst(
3393 EquivPred,
3394 EquivOffset.isZero()
3395 ? V
3396 : Builder.CreateAdd(V, ConstantInt::get(NewCmpTy, EquivOffset)),
3397 ConstantInt::get(NewCmpTy, EquivInt));
3398 }
3399 }
3400
3401 return nullptr;
3402}
3403
3405 Value *&RHS, ConstantInt *&Less,
3406 ConstantInt *&Equal,
3407 ConstantInt *&Greater) {
3408 // TODO: Generalize this to work with other comparison idioms or ensure
3409 // they get canonicalized into this form.
3410
3411 // select i1 (a == b),
3412 // i32 Equal,
3413 // i32 (select i1 (a < b), i32 Less, i32 Greater)
3414 // where Equal, Less and Greater are placeholders for any three constants.
3415 CmpPredicate PredA;
3416 if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
3417 !ICmpInst::isEquality(PredA))
3418 return false;
3419 Value *EqualVal = SI->getTrueValue();
3420 Value *UnequalVal = SI->getFalseValue();
3421 // We still can get non-canonical predicate here, so canonicalize.
3422 if (PredA == ICmpInst::ICMP_NE)
3423 std::swap(EqualVal, UnequalVal);
3424 if (!match(EqualVal, m_ConstantInt(Equal)))
3425 return false;
3426 CmpPredicate PredB;
3427 Value *LHS2, *RHS2;
3428 if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
3429 m_ConstantInt(Less), m_ConstantInt(Greater))))
3430 return false;
3431 // We can get predicate mismatch here, so canonicalize if possible:
3432 // First, ensure that 'LHS' match.
3433 if (LHS2 != LHS) {
3434 // x sgt y <--> y slt x
3435 std::swap(LHS2, RHS2);
3436 PredB = ICmpInst::getSwappedPredicate(PredB);
3437 }
3438 if (LHS2 != LHS)
3439 return false;
3440 // We also need to canonicalize 'RHS'.
3441 if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
3442 // x sgt C-1 <--> x sge C <--> not(x slt C)
3443 auto FlippedStrictness =
3445 if (!FlippedStrictness)
3446 return false;
3447 assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
3448 "basic correctness failure");
3449 RHS2 = FlippedStrictness->second;
3450 // And kind-of perform the result swap.
3451 std::swap(Less, Greater);
3452 PredB = ICmpInst::ICMP_SLT;
3453 }
3454 return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
3455}
3456
3459 ConstantInt *C) {
3460
3461 assert(C && "Cmp RHS should be a constant int!");
3462 // If we're testing a constant value against the result of a three way
3463 // comparison, the result can be expressed directly in terms of the
3464 // original values being compared. Note: We could possibly be more
3465 // aggressive here and remove the hasOneUse test. The original select is
3466 // really likely to simplify or sink when we remove a test of the result.
3467 Value *OrigLHS, *OrigRHS;
3468 ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
3469 if (Cmp.hasOneUse() &&
3470 matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
3471 C3GreaterThan)) {
3472 assert(C1LessThan && C2Equal && C3GreaterThan);
3473
3474 bool TrueWhenLessThan = ICmpInst::compare(
3475 C1LessThan->getValue(), C->getValue(), Cmp.getPredicate());
3476 bool TrueWhenEqual = ICmpInst::compare(C2Equal->getValue(), C->getValue(),
3477 Cmp.getPredicate());
3478 bool TrueWhenGreaterThan = ICmpInst::compare(
3479 C3GreaterThan->getValue(), C->getValue(), Cmp.getPredicate());
3480
3481 // This generates the new instruction that will replace the original Cmp
3482 // Instruction. Instead of enumerating the various combinations when
3483 // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
3484 // false, we rely on chaining of ORs and future passes of InstCombine to
3485 // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
3486
3487 // When none of the three constants satisfy the predicate for the RHS (C),
3488 // the entire original Cmp can be simplified to a false.
3489 Value *Cond = Builder.getFalse();
3490 if (TrueWhenLessThan)
3491 Cond = Builder.CreateOr(
3492 Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT, OrigLHS, OrigRHS));
3493 if (TrueWhenEqual)
3494 Cond = Builder.CreateOr(
3495 Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ, OrigLHS, OrigRHS));
3496 if (TrueWhenGreaterThan)
3497 Cond = Builder.CreateOr(
3498 Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT, OrigLHS, OrigRHS));
3499
3500 return replaceInstUsesWith(Cmp, Cond);
3501 }
3502 return nullptr;
3503}
3504
3506 auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
3507 if (!Bitcast)
3508 return nullptr;
3509
3510 ICmpInst::Predicate Pred = Cmp.getPredicate();
3511 Value *Op1 = Cmp.getOperand(1);
3512 Value *BCSrcOp = Bitcast->getOperand(0);
3513 Type *SrcType = Bitcast->getSrcTy();
3514 Type *DstType = Bitcast->getType();
3515
3516 // Make sure the bitcast doesn't change between scalar and vector and
3517 // doesn't change the number of vector elements.
3518 if (SrcType->isVectorTy() == DstType->isVectorTy() &&
3519 SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
3520 // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
3521 Value *X;
3522 if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
3523 // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
3524 // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
3525 // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
3526 // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
3527 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
3528 Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
3529 match(Op1, m_Zero()))
3530 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3531
3532 // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
3533 if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
3534 return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
3535
3536 // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
3537 if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
3538 return new ICmpInst(Pred, X,
3539 ConstantInt::getAllOnesValue(X->getType()));
3540 }
3541
3542 // Zero-equality checks are preserved through unsigned floating-point casts:
3543 // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
3544 // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
3545 if (match(BCSrcOp, m_UIToFP(m_Value(X))))
3546 if (Cmp.isEquality() && match(Op1, m_Zero()))
3547 return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
3548
3549 const APInt *C;
3550 bool TrueIfSigned;
3551 if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse()) {
3552 // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
3553 // the FP extend/truncate because that cast does not change the sign-bit.
3554 // This is true for all standard IEEE-754 types and the X86 80-bit type.
3555 // The sign-bit is always the most significant bit in those types.
3556 if (isSignBitCheck(Pred, *C, TrueIfSigned) &&
3557 (match(BCSrcOp, m_FPExt(m_Value(X))) ||
3558 match(BCSrcOp, m_FPTrunc(m_Value(X))))) {
3559 // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
3560 // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
3561 Type *XType = X->getType();
3562
3563 // We can't currently handle Power style floating point operations here.
3564 if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
3565 Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
3566 if (auto *XVTy = dyn_cast<VectorType>(XType))
3567 NewType = VectorType::get(NewType, XVTy->getElementCount());
3568 Value *NewBitcast = Builder.CreateBitCast(X, NewType);
3569 if (TrueIfSigned)
3570 return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
3571 ConstantInt::getNullValue(NewType));
3572 else
3573 return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
3575 }
3576 }
3577
3578 // icmp eq/ne (bitcast X to int), special fp -> llvm.is.fpclass(X, class)
3579 Type *FPType = SrcType->getScalarType();
3580 if (!Cmp.getParent()->getParent()->hasFnAttribute(
3581 Attribute::NoImplicitFloat) &&
3582 Cmp.isEquality() && FPType->isIEEELikeFPTy()) {
3583 FPClassTest Mask = APFloat(FPType->getFltSemantics(), *C).classify();
3584 if (Mask & (fcInf | fcZero)) {
3585 if (Pred == ICmpInst::ICMP_NE)
3586 Mask = ~Mask;
3587 return replaceInstUsesWith(Cmp,
3588 Builder.createIsFPClass(BCSrcOp, Mask));
3589 }
3590 }
3591 }
3592 }
3593
3594 // Fold the canonicalized form of vector_reduce_or if the arg is
3595 // get_active_lane mask.
3596 // icmp ne (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3597 // icmp ult l, h
3598 // icmp eq (bitcast <N x i1> to iN (get_active_lane_mask(l, h))), 0 ->
3599 // icmp uge l, h
3600 Value *Upper, *Lower;
3602 m_Value(Lower), m_Value(Upper))) &&
3603 match(Op1, m_Zero()) && DstType->isIntegerTy()) {
3604 if (Pred == ICmpInst::ICMP_NE)
3605 return new ICmpInst(ICmpInst::ICMP_ULT, Lower, Upper);
3606 if (Pred == ICmpInst::ICMP_EQ)
3607 return new ICmpInst(ICmpInst::ICMP_UGE, Lower, Upper);
3608 }
3609
3610 const APInt *C;
3611 if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
3612 !SrcType->isIntOrIntVectorTy())
3613 return nullptr;
3614
3615 // If this is checking if all elements of a vector compare are set or not,
3616 // invert the casted vector equality compare and test if all compare
3617 // elements are clear or not. Compare against zero is generally easier for
3618 // analysis and codegen.
3619 // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
3620 // Example: are all elements equal? --> are zero elements not equal?
3621 // TODO: Try harder to reduce compare of 2 freely invertible operands?
3622 if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse()) {
3623 if (Value *NotBCSrcOp =
3624 getFreelyInverted(BCSrcOp, BCSrcOp->hasOneUse(), &Builder)) {
3625 Value *Cast = Builder.CreateBitCast(NotBCSrcOp, DstType);
3626 return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
3627 }
3628 }
3629
3630 // If this is checking if all elements of an extended vector are clear or not,
3631 // compare in a narrow type to eliminate the extend:
3632 // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
3633 Value *X;
3634 if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
3635 match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
3636 if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
3637 Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
3638 Value *NewCast = Builder.CreateBitCast(X, NewType);
3639 return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
3640 }
3641 }
3642
3643 // Folding: icmp <pred> iN X, C
3644 // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
3645 // and C is a splat of a K-bit pattern
3646 // and SC is a constant vector = <C', C', C', ..., C'>
3647 // Into:
3648 // %E = extractelement <M x iK> %vec, i32 C'
3649 // icmp <pred> iK %E, trunc(C)
3650 Value *Vec;
3651 ArrayRef<int> Mask;
3652 if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
3653 // Check whether every element of Mask is the same constant
3654 if (all_equal(Mask)) {
3655 auto *VecTy = cast<VectorType>(SrcType);
3656 auto *EltTy = cast<IntegerType>(VecTy->getElementType());
3657 if (C->isSplat(EltTy->getBitWidth())) {
3658 // Fold the icmp based on the value of C
3659 // If C is M copies of an iK sized bit pattern,
3660 // then:
3661 // => %E = extractelement <N x iK> %vec, i64 Elem
3662 // icmp <pred> iK %SplatVal, <pattern>
3663 Value *Extract = Builder.CreateExtractElement(Vec, Mask[0]);
3664 Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
3665 return new ICmpInst(Pred, Extract, NewC);
3666 }
3667 }
3668 }
3669 return nullptr;
3670}
3671
3672/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
3673/// where X is some kind of instruction.
3675 const APInt *C;
3676
3677 if (match(Cmp.getOperand(1), m_APInt(C))) {
3678 if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
3679 if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
3680 return I;
3681
3682 if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
3683 // For now, we only support constant integers while folding the
3684 // ICMP(SELECT)) pattern. We can extend this to support vector of integers
3685 // similar to the cases handled by binary ops above.
3686 if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
3687 if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
3688 return I;
3689
3690 if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
3691 if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
3692 return I;
3693
3694 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
3696 return I;
3697
3698 {
3699 // icmp slt/sgt (extractvalue (frexp X), 1), C -->
3700 // fcmp olt/oge (fabs X), 2^ExpVal
3701 // slt -> olt, ExpVal = C-1; sgt -> oge, ExpVal = C.
3702 Value *X;
3703 if (match(Cmp.getOperand(0),
3706 ICmpInst::Predicate Pred = Cmp.getPredicate();
3707 APInt Exp;
3708 FCmpInst::Predicate NewPred;
3709 bool ValidPred = true;
3710
3711 switch (Pred) {
3712 case ICmpInst::ICMP_SLT:
3713 NewPred = FCmpInst::FCMP_OLT;
3714 Exp = *C - 1;
3715 break;
3716 case ICmpInst::ICMP_SGT:
3717 NewPred = FCmpInst::FCMP_OGE;
3718 Exp = *C;
3719 break;
3720 default:
3721 ValidPred = false;
3722 break;
3723 }
3724
3725 if (ValidPred) {
3726 const fltSemantics &Sem =
3727 X->getType()->getScalarType()->getFltSemantics();
3728 int MaxExp = APFloat::semanticsMaxExponent(Sem);
3729
3730 if (!Exp.isNegative() && Exp.sle(MaxExp + 1) &&
3731 isKnownNeverInfOrNaN(X, SQ.getWithInstruction(&Cmp))) {
3732 int ExpVal = static_cast<int>(Exp.getSExtValue());
3733 APFloat CmpConst = scalbn(APFloat::getOne(Sem), ExpVal,
3735 Value *Fabs = Builder.CreateFAbs(X);
3736 return new FCmpInst(NewPred, Fabs,
3737 ConstantFP::get(X->getType(), CmpConst));
3738 }
3739 }
3740 }
3741 }
3742
3743 // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
3744 // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
3745 // TODO: This checks one-use, but that is not strictly necessary.
3746 Value *Cmp0 = Cmp.getOperand(0);
3747 Value *X, *Y;
3748 if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
3749 (match(Cmp0,
3751 m_Value(X), m_Value(Y)))) ||
3752 match(Cmp0,
3754 m_Value(X), m_Value(Y))))))
3755 return new ICmpInst(Cmp.getPredicate(), X, Y);
3756 }
3757
3758 if (match(Cmp.getOperand(1), m_APIntAllowPoison(C)))
3760
3761 return nullptr;
3762}
3763
3764/// Fold an icmp equality instruction with binary operator LHS and constant RHS:
3765/// icmp eq/ne BO, C.
3767 ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
3768 // TODO: Some of these folds could work with arbitrary constants, but this
3769 // function is limited to scalar and vector splat constants.
3770 if (!Cmp.isEquality())
3771 return nullptr;
3772
3773 ICmpInst::Predicate Pred = Cmp.getPredicate();
3774 bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
3775 Constant *RHS = cast<Constant>(Cmp.getOperand(1));
3776 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3777
3778 switch (BO->getOpcode()) {
3779 case Instruction::SRem:
3780 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3781 if (C.isZero() && BO->hasOneUse()) {
3782 const APInt *BOC;
3783 if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
3784 Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
3785 return new ICmpInst(Pred, NewRem,
3787 }
3788 }
3789 break;
3790 case Instruction::Add: {
3791 // (A + C2) == C --> A == (C - C2)
3792 // (A + C2) != C --> A != (C - C2)
3793 // TODO: Remove the one-use limitation? See discussion in D58633.
3794 if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
3795 if (BO->hasOneUse())
3796 return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
3797 } else if (C.isZero()) {
3798 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3799 // efficiently invertible, or if the add has just this one use.
3800 if (Value *NegVal = dyn_castNegVal(BOp1))
3801 return new ICmpInst(Pred, BOp0, NegVal);
3802 if (Value *NegVal = dyn_castNegVal(BOp0))
3803 return new ICmpInst(Pred, NegVal, BOp1);
3804 if (BO->hasOneUse()) {
3805 // (add nuw A, B) != 0 -> (or A, B) != 0
3806 if (match(BO, m_NUWAdd(m_Value(), m_Value()))) {
3807 Value *Or = Builder.CreateOr(BOp0, BOp1);
3808 return new ICmpInst(Pred, Or, Constant::getNullValue(BO->getType()));
3809 }
3810 Value *Neg = Builder.CreateNeg(BOp1);
3811 Neg->takeName(BO);
3812 return new ICmpInst(Pred, BOp0, Neg);
3813 }
3814 }
3815 break;
3816 }
3817 case Instruction::Xor:
3818 if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
3819 // For the xor case, we can xor two constants together, eliminating
3820 // the explicit xor.
3821 return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
3822 } else if (C.isZero()) {
3823 // Replace ((xor A, B) != 0) with (A != B)
3824 return new ICmpInst(Pred, BOp0, BOp1);
3825 }
3826 break;
3827 case Instruction::Or: {
3828 const APInt *BOC;
3829 if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
3830 // Comparing if all bits outside of a constant mask are set?
3831 // Replace (X | C) == -1 with (X & ~C) == ~C.
3832 // This removes the -1 constant.
3834 Value *And = Builder.CreateAnd(BOp0, NotBOC);
3835 return new ICmpInst(Pred, And, NotBOC);
3836 }
3837 // (icmp eq (or (select cond, 0, NonZero), Other), 0)
3838 // -> (and cond, (icmp eq Other, 0))
3839 // (icmp ne (or (select cond, NonZero, 0), Other), 0)
3840 // -> (or cond, (icmp ne Other, 0))
3841 Value *Cond, *TV, *FV, *Other, *Sel;
3842 if (C.isZero() &&
3843 match(BO,
3846 m_Value(FV))),
3847 m_Value(Other)))) &&
3848 Cond->getType() == Cmp.getType()) {
3849 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
3850 // Easy case is if eq/ne matches whether 0 is trueval/falseval.
3851 if (Pred == ICmpInst::ICMP_EQ
3852 ? (match(TV, m_Zero()) && isKnownNonZero(FV, Q))
3853 : (match(FV, m_Zero()) && isKnownNonZero(TV, Q))) {
3854 Value *Cmp = Builder.CreateICmp(
3855 Pred, Other, Constant::getNullValue(Other->getType()));
3857 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3858 Cond);
3859 }
3860 // Harder case is if eq/ne matches whether 0 is falseval/trueval. In this
3861 // case we need to invert the select condition so we need to be careful to
3862 // avoid creating extra instructions.
3863 // (icmp ne (or (select cond, 0, NonZero), Other), 0)
3864 // -> (or (not cond), (icmp ne Other, 0))
3865 // (icmp eq (or (select cond, NonZero, 0), Other), 0)
3866 // -> (and (not cond), (icmp eq Other, 0))
3867 //
3868 // Only do this if the inner select has one use, in which case we are
3869 // replacing `select` with `(not cond)`. Otherwise, we will create more
3870 // uses. NB: Trying to freely invert cond doesn't make sense here, as if
3871 // cond was freely invertable, the select arms would have been inverted.
3872 if (Sel->hasOneUse() &&
3873 (Pred == ICmpInst::ICMP_EQ
3874 ? (match(FV, m_Zero()) && isKnownNonZero(TV, Q))
3875 : (match(TV, m_Zero()) && isKnownNonZero(FV, Q)))) {
3876 Value *NotCond = Builder.CreateNot(Cond);
3877 Value *Cmp = Builder.CreateICmp(
3878 Pred, Other, Constant::getNullValue(Other->getType()));
3880 Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or, Cmp,
3881 NotCond);
3882 }
3883 }
3884 break;
3885 }
3886 case Instruction::UDiv:
3887 case Instruction::SDiv:
3888 if (BO->isExact()) {
3889 // div exact X, Y eq/ne 0 -> X eq/ne 0
3890 // div exact X, Y eq/ne 1 -> X eq/ne Y
3891 // div exact X, Y eq/ne C ->
3892 // if Y * C never-overflow && OneUse:
3893 // -> Y * C eq/ne X
3894 if (C.isZero())
3895 return new ICmpInst(Pred, BOp0, Constant::getNullValue(BO->getType()));
3896 else if (C.isOne())
3897 return new ICmpInst(Pred, BOp0, BOp1);
3898 else if (BO->hasOneUse()) {
3900 Instruction::Mul, BO->getOpcode() == Instruction::SDiv, BOp1,
3901 Cmp.getOperand(1), BO);
3903 Value *YC =
3904 Builder.CreateMul(BOp1, ConstantInt::get(BO->getType(), C));
3905 return new ICmpInst(Pred, YC, BOp0);
3906 }
3907 }
3908 }
3909 if (BO->getOpcode() == Instruction::UDiv && C.isZero()) {
3910 // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
3911 auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
3912 return new ICmpInst(NewPred, BOp1, BOp0);
3913 }
3914 break;
3915 default:
3916 break;
3917 }
3918 return nullptr;
3919}
3920
3922 const APInt &CRhs,
3923 InstCombiner::BuilderTy &Builder,
3924 const SimplifyQuery &Q) {
3925 assert(CtpopLhs->getIntrinsicID() == Intrinsic::ctpop &&
3926 "Non-ctpop intrin in ctpop fold");
3927 if (!CtpopLhs->hasOneUse())
3928 return nullptr;
3929
3930 // Power of 2 test:
3931 // isPow2OrZero : ctpop(X) u< 2
3932 // isPow2 : ctpop(X) == 1
3933 // NotPow2OrZero: ctpop(X) u> 1
3934 // NotPow2 : ctpop(X) != 1
3935 // If we know any bit of X can be folded to:
3936 // IsPow2 : X & (~Bit) == 0
3937 // NotPow2 : X & (~Bit) != 0
3938 const ICmpInst::Predicate Pred = I.getPredicate();
3939 if (((I.isEquality() || Pred == ICmpInst::ICMP_UGT) && CRhs == 1) ||
3940 (Pred == ICmpInst::ICMP_ULT && CRhs == 2)) {
3941 Value *Op = CtpopLhs->getArgOperand(0);
3942 KnownBits OpKnown = computeKnownBits(Op, Q.DL, Q.AC, Q.CtxI, Q.DT);
3943 // No need to check for count > 1, that should be already constant folded.
3944 if (OpKnown.countMinPopulation() == 1) {
3945 Value *And = Builder.CreateAnd(
3946 Op, Constant::getIntegerValue(Op->getType(), ~(OpKnown.One)));
3947 return new ICmpInst(
3948 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_ULT)
3951 And, Constant::getNullValue(Op->getType()));
3952 }
3953 }
3954
3955 return nullptr;
3956}
3957
3958/// Fold an equality icmp with LLVM intrinsic and constant operand.
3960 ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
3961 Type *Ty = II->getType();
3962 unsigned BitWidth = C.getBitWidth();
3963 const ICmpInst::Predicate Pred = Cmp.getPredicate();
3964
3965 switch (II->getIntrinsicID()) {
3966 case Intrinsic::abs:
3967 // abs(A) == 0 -> A == 0
3968 // abs(A) == INT_MIN -> A == INT_MIN
3969 if (C.isZero() || C.isMinSignedValue())
3970 return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
3971 break;
3972
3973 case Intrinsic::bswap:
3974 // bswap(A) == C -> A == bswap(C)
3975 return new ICmpInst(Pred, II->getArgOperand(0),
3976 ConstantInt::get(Ty, C.byteSwap()));
3977
3978 case Intrinsic::bitreverse:
3979 // bitreverse(A) == C -> A == bitreverse(C)
3980 return new ICmpInst(Pred, II->getArgOperand(0),
3981 ConstantInt::get(Ty, C.reverseBits()));
3982
3983 case Intrinsic::ctlz:
3984 case Intrinsic::cttz: {
3985 // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
3986 if (C == BitWidth)
3987 return new ICmpInst(Pred, II->getArgOperand(0),
3989
3990 // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
3991 // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
3992 // Limit to one use to ensure we don't increase instruction count.
3993 unsigned Num = C.getLimitedValue(BitWidth);
3994 if (Num != BitWidth && II->hasOneUse()) {
3995 bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
3996 APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
3997 : APInt::getHighBitsSet(BitWidth, Num + 1);
3998 APInt Mask2 = IsTrailing
4001 return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
4002 ConstantInt::get(Ty, Mask2));
4003 }
4004 break;
4005 }
4006
4007 case Intrinsic::ctpop: {
4008 // popcount(A) == 0 -> A == 0 and likewise for !=
4009 // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
4010 bool IsZero = C.isZero();
4011 if (IsZero || C == BitWidth)
4012 return new ICmpInst(Pred, II->getArgOperand(0),
4013 IsZero ? Constant::getNullValue(Ty)
4015
4016 break;
4017 }
4018
4019 case Intrinsic::fshl:
4020 case Intrinsic::fshr:
4021 if (II->getArgOperand(0) == II->getArgOperand(1)) {
4022 const APInt *RotAmtC;
4023 // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
4024 // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
4025 if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
4026 return new ICmpInst(Pred, II->getArgOperand(0),
4027 II->getIntrinsicID() == Intrinsic::fshl
4028 ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
4029 : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
4030 }
4031 break;
4032
4033 case Intrinsic::umax:
4034 case Intrinsic::uadd_sat: {
4035 // uadd.sat(a, b) == 0 -> (a | b) == 0
4036 // umax(a, b) == 0 -> (a | b) == 0
4037 if (C.isZero() && II->hasOneUse()) {
4038 Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
4039 return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
4040 }
4041 break;
4042 }
4043
4044 case Intrinsic::ssub_sat:
4045 // ssub.sat(a, b) == 0 -> a == b
4046 //
4047 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4048 // (because 1 saturates to 0). Just skip the optimization for i1.
4049 if (C.isZero() && II->getType()->getScalarSizeInBits() > 1)
4050 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4051 break;
4052 case Intrinsic::usub_sat: {
4053 // usub.sat(a, b) == 0 -> a <= b
4054 if (C.isZero()) {
4055 ICmpInst::Predicate NewPred =
4057 return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
4058 }
4059 break;
4060 }
4061 default:
4062 break;
4063 }
4064
4065 return nullptr;
4066}
4067
4068/// Fold an icmp with LLVM intrinsics
4069static Instruction *
4071 InstCombiner::BuilderTy &Builder) {
4072 assert(Cmp.isEquality());
4073
4074 ICmpInst::Predicate Pred = Cmp.getPredicate();
4075 Value *Op0 = Cmp.getOperand(0);
4076 Value *Op1 = Cmp.getOperand(1);
4077 const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
4078 const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
4079 if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
4080 return nullptr;
4081
4082 switch (IIOp0->getIntrinsicID()) {
4083 case Intrinsic::bswap:
4084 case Intrinsic::bitreverse:
4085 // If both operands are byte-swapped or bit-reversed, just compare the
4086 // original values.
4087 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4088 case Intrinsic::fshl:
4089 case Intrinsic::fshr: {
4090 // If both operands are rotated by same amount, just compare the
4091 // original values.
4092 if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
4093 break;
4094 if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
4095 break;
4096 if (IIOp0->getOperand(2) == IIOp1->getOperand(2))
4097 return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
4098
4099 // rotate(X, AmtX) == rotate(Y, AmtY)
4100 // -> rotate(X, AmtX - AmtY) == Y
4101 // Do this if either both rotates have one use or if only one has one use
4102 // and AmtX/AmtY are constants.
4103 const unsigned BW = IIOp0->getType()->getScalarSizeInBits();
4104 unsigned OneUses = IIOp0->hasOneUse() + IIOp1->hasOneUse();
4105 if (OneUses == 2 ||
4106 (OneUses == 1 && match(IIOp0->getOperand(2), m_ImmConstant()) &&
4107 match(IIOp1->getOperand(2), m_ImmConstant()))) {
4108
4109 // Only valid assuming (2**BW) % BW == 0, which only holds for powers
4110 // of two.
4111 if (isPowerOf2_32(BW)) {
4112 Value *SubAmt =
4113 Builder.CreateSub(IIOp0->getOperand(2), IIOp1->getOperand(2));
4114 Value *CombinedRotate = Builder.CreateIntrinsic(
4115 Op0->getType(), IIOp0->getIntrinsicID(),
4116 {IIOp0->getOperand(0), IIOp0->getOperand(0), SubAmt});
4117 return new ICmpInst(Pred, IIOp1->getOperand(0), CombinedRotate);
4118 }
4119 }
4120 } break;
4121 default:
4122 break;
4123 }
4124
4125 return nullptr;
4126}
4127
4128/// Try to fold integer comparisons with a constant operand: icmp Pred X, C
4129/// where X is some kind of instruction and C is AllowPoison.
4130/// TODO: Move more folds which allow poison to this function.
4133 const APInt &C) {
4134 const ICmpInst::Predicate Pred = Cmp.getPredicate();
4135 if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
4136 switch (II->getIntrinsicID()) {
4137 default:
4138 break;
4139 case Intrinsic::fshl:
4140 case Intrinsic::fshr:
4141 if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
4142 // (rot X, ?) == 0/-1 --> X == 0/-1
4143 if (C.isZero() || C.isAllOnes())
4144 return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
4145 }
4146 break;
4147 }
4148 }
4149
4150 return nullptr;
4151}
4152
4153/// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
4155 BinaryOperator *BO,
4156 const APInt &C) {
4157 switch (BO->getOpcode()) {
4158 case Instruction::Xor:
4159 if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
4160 return I;
4161 break;
4162 case Instruction::And:
4163 if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
4164 return I;
4165 break;
4166 case Instruction::Or:
4167 if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
4168 return I;
4169 break;
4170 case Instruction::Mul:
4171 if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
4172 return I;
4173 break;
4174 case Instruction::Shl:
4175 if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
4176 return I;
4177 break;
4178 case Instruction::LShr:
4179 case Instruction::AShr:
4180 if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
4181 return I;
4182 break;
4183 case Instruction::SRem:
4184 if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
4185 return I;
4186 break;
4187 case Instruction::UDiv:
4188 if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
4189 return I;
4190 [[fallthrough]];
4191 case Instruction::SDiv:
4192 if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
4193 return I;
4194 break;
4195 case Instruction::Sub:
4196 if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
4197 return I;
4198 break;
4199 case Instruction::Add:
4200 if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
4201 return I;
4202 break;
4203 default:
4204 break;
4205 }
4206
4207 // TODO: These folds could be refactored to be part of the above calls.
4209 return I;
4210
4211 // Fall back to handling `icmp pred (select A ? C1 : C2) binop (select B ? C3
4212 // : C4), C5` pattern, by computing a truth table of the four constant
4213 // variants.
4215}
4216
4217static Instruction *
4219 const APInt &C,
4220 InstCombiner::BuilderTy &Builder) {
4221 // This transform may end up producing more than one instruction for the
4222 // intrinsic, so limit it to one user of the intrinsic.
4223 if (!II->hasOneUse())
4224 return nullptr;
4225
4226 // Let Y = [add/sub]_sat(X, C) pred C2
4227 // SatVal = The saturating value for the operation
4228 // WillWrap = Whether or not the operation will underflow / overflow
4229 // => Y = (WillWrap ? SatVal : (X binop C)) pred C2
4230 // => Y = WillWrap ? (SatVal pred C2) : ((X binop C) pred C2)
4231 //
4232 // When (SatVal pred C2) is true, then
4233 // Y = WillWrap ? true : ((X binop C) pred C2)
4234 // => Y = WillWrap || ((X binop C) pred C2)
4235 // else
4236 // Y = WillWrap ? false : ((X binop C) pred C2)
4237 // => Y = !WillWrap ? ((X binop C) pred C2) : false
4238 // => Y = !WillWrap && ((X binop C) pred C2)
4239 Value *Op0 = II->getOperand(0);
4240 Value *Op1 = II->getOperand(1);
4241
4242 const APInt *COp1;
4243 // This transform only works when the intrinsic has an integral constant or
4244 // splat vector as the second operand.
4245 if (!match(Op1, m_APInt(COp1)))
4246 return nullptr;
4247
4248 APInt SatVal;
4249 switch (II->getIntrinsicID()) {
4250 default:
4252 "This function only works with usub_sat and uadd_sat for now!");
4253 case Intrinsic::uadd_sat:
4254 SatVal = APInt::getAllOnes(C.getBitWidth());
4255 break;
4256 case Intrinsic::usub_sat:
4257 SatVal = APInt::getZero(C.getBitWidth());
4258 break;
4259 }
4260
4261 // Check (SatVal pred C2)
4262 bool SatValCheck = ICmpInst::compare(SatVal, C, Pred);
4263
4264 // !WillWrap.
4266 II->getBinaryOp(), *COp1, II->getNoWrapKind());
4267
4268 // WillWrap.
4269 if (SatValCheck)
4270 C1 = C1.inverse();
4271
4273 if (II->getBinaryOp() == Instruction::Add)
4274 C2 = C2.sub(*COp1);
4275 else
4276 C2 = C2.add(*COp1);
4277
4278 Instruction::BinaryOps CombiningOp =
4279 SatValCheck ? Instruction::BinaryOps::Or : Instruction::BinaryOps::And;
4280
4281 std::optional<ConstantRange> Combination;
4282 if (CombiningOp == Instruction::BinaryOps::Or)
4283 Combination = C1.exactUnionWith(C2);
4284 else /* CombiningOp == Instruction::BinaryOps::And */
4285 Combination = C1.exactIntersectWith(C2);
4286
4287 if (!Combination)
4288 return nullptr;
4289
4290 CmpInst::Predicate EquivPred;
4291 APInt EquivInt;
4292 APInt EquivOffset;
4293
4294 Combination->getEquivalentICmp(EquivPred, EquivInt, EquivOffset);
4295
4296 return new ICmpInst(
4297 EquivPred,
4298 Builder.CreateAdd(Op0, ConstantInt::get(Op1->getType(), EquivOffset)),
4299 ConstantInt::get(Op1->getType(), EquivInt));
4300}
4301
4302static Instruction *
4304 const APInt &C,
4305 InstCombiner::BuilderTy &Builder) {
4306 std::optional<ICmpInst::Predicate> NewPredicate = std::nullopt;
4307 switch (Pred) {
4308 case ICmpInst::ICMP_EQ:
4309 case ICmpInst::ICMP_NE:
4310 if (C.isZero())
4311 NewPredicate = Pred;
4312 else if (C.isOne())
4313 NewPredicate =
4315 else if (C.isAllOnes())
4316 NewPredicate =
4318 break;
4319
4320 case ICmpInst::ICMP_SGT:
4321 if (C.isAllOnes())
4322 NewPredicate = ICmpInst::ICMP_UGE;
4323 else if (C.isZero())
4324 NewPredicate = ICmpInst::ICMP_UGT;
4325 break;
4326
4327 case ICmpInst::ICMP_SLT:
4328 if (C.isZero())
4329 NewPredicate = ICmpInst::ICMP_ULT;
4330 else if (C.isOne())
4331 NewPredicate = ICmpInst::ICMP_ULE;
4332 break;
4333
4334 case ICmpInst::ICMP_ULT:
4335 if (C.ugt(1))
4336 NewPredicate = ICmpInst::ICMP_UGE;
4337 break;
4338
4339 case ICmpInst::ICMP_UGT:
4340 if (!C.isZero() && !C.isAllOnes())
4341 NewPredicate = ICmpInst::ICMP_ULT;
4342 break;
4343
4344 default:
4345 break;
4346 }
4347
4348 if (!NewPredicate)
4349 return nullptr;
4350
4351 if (I->getIntrinsicID() == Intrinsic::scmp)
4352 NewPredicate = ICmpInst::getSignedPredicate(*NewPredicate);
4353 Value *LHS = I->getOperand(0);
4354 Value *RHS = I->getOperand(1);
4355 return new ICmpInst(*NewPredicate, LHS, RHS);
4356}
4357
4358/// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
4361 const APInt &C) {
4362 ICmpInst::Predicate Pred = Cmp.getPredicate();
4363
4364 // Handle folds that apply for any kind of icmp.
4365 switch (II->getIntrinsicID()) {
4366 default:
4367 break;
4368 case Intrinsic::uadd_sat:
4369 case Intrinsic::usub_sat:
4371 Pred, cast<SaturatingInst>(II), C, Builder))
4372 return Folded;
4373 break;
4374 case Intrinsic::ctpop: {
4375 const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
4376 if (Instruction *R = foldCtpopPow2Test(Cmp, II, C, Builder, Q))
4377 return R;
4378 } break;
4379 case Intrinsic::scmp:
4380 case Intrinsic::ucmp:
4382 return Folded;
4383 break;
4384 }
4385
4386 if (Cmp.isEquality())
4387 return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
4388
4389 Type *Ty = II->getType();
4390 unsigned BitWidth = C.getBitWidth();
4391 switch (II->getIntrinsicID()) {
4392 case Intrinsic::ctpop: {
4393 // (ctpop X > BitWidth - 1) --> X == -1
4394 Value *X = II->getArgOperand(0);
4395 if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
4396 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
4398 // (ctpop X < BitWidth) --> X != -1
4399 if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
4400 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
4402 break;
4403 }
4404 case Intrinsic::ctlz: {
4405 // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
4406 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4407 unsigned Num = C.getLimitedValue();
4408 APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
4409 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
4410 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4411 }
4412
4413 // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
4414 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4415 unsigned Num = C.getLimitedValue();
4417 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
4418 II->getArgOperand(0), ConstantInt::get(Ty, Limit));
4419 }
4420 break;
4421 }
4422 case Intrinsic::cttz: {
4423 // Limit to one use to ensure we don't increase instruction count.
4424 if (!II->hasOneUse())
4425 return nullptr;
4426
4427 // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
4428 if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
4429 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
4430 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
4431 Builder.CreateAnd(II->getArgOperand(0), Mask),
4433 }
4434
4435 // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
4436 if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
4437 APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
4438 return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
4439 Builder.CreateAnd(II->getArgOperand(0), Mask),
4441 }
4442 break;
4443 }
4444 case Intrinsic::ssub_sat:
4445 // ssub.sat(a, b) spred 0 -> a spred b
4446 //
4447 // Note this doesn't work for ssub.sat.i1 because ssub.sat.i1 0, -1 = 0
4448 // (because 1 saturates to 0). Just skip the optimization for i1.
4449 if (ICmpInst::isSigned(Pred) && C.getBitWidth() > 1) {
4450 if (C.isZero())
4451 return new ICmpInst(Pred, II->getArgOperand(0), II->getArgOperand(1));
4452 // X s<= 0 is cannonicalized to X s< 1
4453 if (Pred == ICmpInst::ICMP_SLT && C.isOne())
4454 return new ICmpInst(ICmpInst::ICMP_SLE, II->getArgOperand(0),
4455 II->getArgOperand(1));
4456 // X s>= 0 is cannonicalized to X s> -1
4457 if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
4458 return new ICmpInst(ICmpInst::ICMP_SGE, II->getArgOperand(0),
4459 II->getArgOperand(1));
4460 }
4461 break;
4462 case Intrinsic::abs: {
4463 if (!II->hasOneUse())
4464 return nullptr;
4465
4466 Value *X = II->getArgOperand(0);
4467
4468 // If C >= 0:
4469 // abs(X) u> C --> X + C u> 2 * C
4470 if (Pred == CmpInst::ICMP_UGT && C.isNonNegative()) {
4471 return new ICmpInst(ICmpInst::ICMP_UGT,
4472 Builder.CreateAdd(X, ConstantInt::get(Ty, C)),
4473 ConstantInt::get(Ty, 2 * C));
4474 }
4475
4476 // If C >= 1:
4477 // abs(X) u< C --> X + (C - 1) u<= 2 * (C - 1)
4478 if (Pred == CmpInst::ICMP_ULT && C.sge(1))
4479 return new ICmpInst(ICmpInst::ICMP_ULE,
4480 Builder.CreateAdd(X, ConstantInt::get(Ty, C - 1)),
4481 ConstantInt::get(Ty, 2 * (C - 1)));
4482
4483 break;
4484 }
4485 default:
4486 break;
4487 }
4488
4489 return nullptr;
4490}
4491
4492/// Handle icmp with constant (but not simple integer constant) RHS.
4494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4495 Constant *RHSC = dyn_cast<Constant>(Op1);
4497 if (!RHSC || !LHSI)
4498 return nullptr;
4499
4500 switch (LHSI->getOpcode()) {
4501 case Instruction::IntToPtr:
4502 // icmp pred inttoptr(X), null -> icmp pred X, null pointer value
4503 if (isa<ConstantPointerNull>(RHSC)) {
4504 Type *IntPtrTy = DL.getIntPtrType(RHSC->getType());
4505 if (IntPtrTy == LHSI->getOperand(0)->getType()) {
4506 APInt NullPtrValue =
4507 DL.getNullPtrValue(RHSC->getType()->getPointerAddressSpace());
4508 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4509 Constant::getIntegerValue(IntPtrTy, NullPtrValue));
4510 }
4511 }
4512 break;
4513
4514 case Instruction::Load:
4515 // Try to optimize things like "A[i] > 4" to index computations.
4516 if (GetElementPtrInst *GEP =
4519 cast<LoadInst>(LHSI), GEP, I.getPredicate(), RHSC, I))
4520 return Res;
4521 break;
4522 }
4523
4524 return nullptr;
4525}
4526
4528 Value *RHS, const ICmpInst &I) {
4529 // Try to fold the comparison into the select arms, which will cause the
4530 // select to be converted into a logical and/or.
4531 auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
4532 if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
4533 return Res;
4534 if (std::optional<bool> Impl = isImpliedCondition(
4535 SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
4536 return ConstantInt::get(I.getType(), *Impl);
4537 return nullptr;
4538 };
4539
4540 ConstantInt *CI = nullptr;
4541 Value *Op1 = SimplifyOp(SI->getOperand(1), true);
4542 if (Op1)
4543 CI = dyn_cast<ConstantInt>(Op1);
4544
4545 Value *Op2 = SimplifyOp(SI->getOperand(2), false);
4546 if (Op2)
4547 CI = dyn_cast<ConstantInt>(Op2);
4548
4549 auto Simplifies = [&](Value *Op, unsigned Idx) {
4550 // A comparison of ucmp/scmp with a constant will fold into an icmp.
4551 const APInt *Dummy;
4552 return Op ||
4553 (isa<CmpIntrinsic>(SI->getOperand(Idx)) &&
4554 SI->getOperand(Idx)->hasOneUse() && match(RHS, m_APInt(Dummy)));
4555 };
4556
4557 // We only want to perform this transformation if it will not lead to
4558 // additional code. This is true if either both sides of the select
4559 // fold to a constant (in which case the icmp is replaced with a select
4560 // which will usually simplify) or this is the only user of the
4561 // select (in which case we are trading a select+icmp for a simpler
4562 // select+icmp) or all uses of the select can be replaced based on
4563 // dominance information ("Global cases").
4564 bool Transform = false;
4565 if (Op1 && Op2)
4566 Transform = true;
4567 else if (Simplifies(Op1, 1) || Simplifies(Op2, 2)) {
4568 // Local case
4569 if (SI->hasOneUse())
4570 Transform = true;
4571 // Global cases
4572 else if (CI && !CI->isZero())
4573 // When Op1 is constant try replacing select with second operand.
4574 // Otherwise Op2 is constant and try replacing select with first
4575 // operand.
4576 Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
4577 }
4578 if (Transform) {
4579 if (!Op1)
4580 Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
4581 if (!Op2)
4582 Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
4583 return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr, SI);
4584 }
4585
4586 // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
4587 // When the select condition compares X with a constant P and the select
4588 // arms are constants C1/C2, we can fold to a set membership test.
4589 // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
4590 // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
4591 if (ICmpInst::isEquality(Pred)) {
4592 CmpPredicate CondPred;
4593 const APInt *C1, *C2, *P;
4594 if (match(SI,
4595 m_OneUse(m_Select(m_ICmp(CondPred, m_Specific(RHS), m_APInt(P)),
4596 m_APInt(C1), m_APInt(C2))))) {
4597 bool C1SatisfiesCond = ICmpInst::compare(*C1, *P, CondPred);
4598 bool C2SatisfiesCond = ICmpInst::compare(*C2, *P, CondPred);
4599
4600 if (C1SatisfiesCond && !C2SatisfiesCond) {
4601 // X == select(cond, C1, C2) -> (X == C1) | (X == C2)
4602 // X != select(cond, C1, C2) -> (X != C1) & (X != C2)
4603 Value *Cmp1 = Builder.CreateICmp(Pred, RHS, SI->getTrueValue());
4604 Value *Cmp2 = Builder.CreateICmp(Pred, RHS, SI->getFalseValue());
4605 if (Pred == ICmpInst::ICMP_EQ)
4606 return BinaryOperator::CreateOr(Cmp1, Cmp2);
4607 return BinaryOperator::CreateAnd(Cmp1, Cmp2);
4608 }
4609 }
4610 }
4611
4612 return nullptr;
4613}
4614
4615// Returns whether V is a Mask ((X + 1) & X == 0) or ~Mask (-Pow2OrZero)
4616static bool isMaskOrZero(const Value *V, bool Not, const SimplifyQuery &Q,
4617 unsigned Depth = 0) {
4618 if (Not ? match(V, m_NegatedPower2OrZero()) : match(V, m_LowBitMaskOrZero()))
4619 return true;
4620 if (V->getType()->getScalarSizeInBits() == 1)
4621 return true;
4623 return false;
4624 Value *X;
4626 if (!I)
4627 return false;
4628 switch (I->getOpcode()) {
4629 case Instruction::ZExt:
4630 // ZExt(Mask) is a Mask.
4631 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4632 case Instruction::SExt:
4633 // SExt(Mask) is a Mask.
4634 // SExt(~Mask) is a ~Mask.
4635 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4636 case Instruction::And:
4637 case Instruction::Or:
4638 // Mask0 | Mask1 is a Mask.
4639 // Mask0 & Mask1 is a Mask.
4640 // ~Mask0 | ~Mask1 is a ~Mask.
4641 // ~Mask0 & ~Mask1 is a ~Mask.
4642 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4643 isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4644 case Instruction::Xor:
4645 if (match(V, m_Not(m_Value(X))))
4646 return isMaskOrZero(X, !Not, Q, Depth);
4647
4648 // (X ^ -X) is a ~Mask
4649 if (Not)
4650 return match(V, m_c_Xor(m_Value(X), m_Neg(m_Deferred(X))));
4651 // (X ^ (X - 1)) is a Mask
4652 else
4653 return match(V, m_c_Xor(m_Value(X), m_Add(m_Deferred(X), m_AllOnes())));
4654 case Instruction::Select:
4655 // c ? Mask0 : Mask1 is a Mask.
4656 return isMaskOrZero(I->getOperand(1), Not, Q, Depth) &&
4657 isMaskOrZero(I->getOperand(2), Not, Q, Depth);
4658 case Instruction::Shl:
4659 // (~Mask) << X is a ~Mask.
4660 return Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4661 case Instruction::LShr:
4662 // Mask >> X is a Mask.
4663 return !Not && isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4664 case Instruction::AShr:
4665 // Mask s>> X is a Mask.
4666 // ~Mask s>> X is a ~Mask.
4667 return isMaskOrZero(I->getOperand(0), Not, Q, Depth);
4668 case Instruction::Add:
4669 // Pow2 - 1 is a Mask.
4670 if (!Not && match(I->getOperand(1), m_AllOnes()))
4671 return isKnownToBeAPowerOfTwo(I->getOperand(0), Q.DL, /*OrZero*/ true,
4672 Q.AC, Q.CtxI, Q.DT, Depth);
4673 break;
4674 case Instruction::Sub:
4675 // -Pow2 is a ~Mask.
4676 if (Not && match(I->getOperand(0), m_Zero()))
4677 return isKnownToBeAPowerOfTwo(I->getOperand(1), Q.DL, /*OrZero*/ true,
4678 Q.AC, Q.CtxI, Q.DT, Depth);
4679 break;
4680 case Instruction::Call: {
4681 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
4682 switch (II->getIntrinsicID()) {
4683 // min/max(Mask0, Mask1) is a Mask.
4684 // min/max(~Mask0, ~Mask1) is a ~Mask.
4685 case Intrinsic::umax:
4686 case Intrinsic::smax:
4687 case Intrinsic::umin:
4688 case Intrinsic::smin:
4689 return isMaskOrZero(II->getArgOperand(1), Not, Q, Depth) &&
4690 isMaskOrZero(II->getArgOperand(0), Not, Q, Depth);
4691
4692 // In the context of masks, bitreverse(Mask) == ~Mask
4693 case Intrinsic::bitreverse:
4694 return isMaskOrZero(II->getArgOperand(0), !Not, Q, Depth);
4695 default:
4696 break;
4697 }
4698 }
4699 break;
4700 }
4701 default:
4702 break;
4703 }
4704 return false;
4705}
4706
4707/// Some comparisons can be simplified.
4708/// In this case, we are looking for comparisons that look like
4709/// a check for a lossy truncation.
4710/// Folds:
4711/// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
4712/// icmp SrcPred (x & ~Mask), ~Mask to icmp DstPred x, ~Mask
4713/// icmp eq/ne (x & ~Mask), 0 to icmp DstPred x, Mask
4714/// icmp eq/ne (~x | Mask), -1 to icmp DstPred x, Mask
4715/// Where Mask is some pattern that produces all-ones in low bits:
4716/// (-1 >> y)
4717/// ((-1 << y) >> y) <- non-canonical, has extra uses
4718/// ~(-1 << y)
4719/// ((1 << y) + (-1)) <- non-canonical, has extra uses
4720/// The Mask can be a constant, too.
4721/// For some predicates, the operands are commutative.
4722/// For others, x can only be on a specific side.
4724 Value *Op1, const SimplifyQuery &Q,
4725 InstCombiner &IC) {
4726
4727 ICmpInst::Predicate DstPred;
4728 switch (Pred) {
4730 // x & Mask == x
4731 // x & ~Mask == 0
4732 // ~x | Mask == -1
4733 // -> x u<= Mask
4734 // x & ~Mask == ~Mask
4735 // -> ~Mask u<= x
4737 break;
4739 // x & Mask != x
4740 // x & ~Mask != 0
4741 // ~x | Mask != -1
4742 // -> x u> Mask
4743 // x & ~Mask != ~Mask
4744 // -> ~Mask u> x
4746 break;
4748 // x & Mask u< x
4749 // -> x u> Mask
4750 // x & ~Mask u< ~Mask
4751 // -> ~Mask u> x
4753 break;
4755 // x & Mask u>= x
4756 // -> x u<= Mask
4757 // x & ~Mask u>= ~Mask
4758 // -> ~Mask u<= x
4760 break;
4762 // x & Mask s< x [iff Mask s>= 0]
4763 // -> x s> Mask
4764 // x & ~Mask s< ~Mask [iff ~Mask != 0]
4765 // -> ~Mask s> x
4767 break;
4769 // x & Mask s>= x [iff Mask s>= 0]
4770 // -> x s<= Mask
4771 // x & ~Mask s>= ~Mask [iff ~Mask != 0]
4772 // -> ~Mask s<= x
4774 break;
4775 default:
4776 // We don't support sgt,sle
4777 // ult/ugt are simplified to true/false respectively.
4778 return nullptr;
4779 }
4780
4781 Value *X, *M;
4782 // Put search code in lambda for early positive returns.
4783 auto IsLowBitMask = [&]() {
4784 if (match(Op0, m_c_And(m_Specific(Op1), m_Value(M)))) {
4785 X = Op1;
4786 // Look for: x & Mask pred x
4787 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4788 return !ICmpInst::isSigned(Pred) ||
4789 (match(M, m_NonNegative()) || isKnownNonNegative(M, Q));
4790 }
4791
4792 // Look for: x & ~Mask pred ~Mask
4793 if (isMaskOrZero(X, /*Not=*/true, Q)) {
4794 return !ICmpInst::isSigned(Pred) || isKnownNonZero(X, Q);
4795 }
4796 return false;
4797 }
4798 if (ICmpInst::isEquality(Pred) && match(Op1, m_AllOnes()) &&
4799 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(M))))) {
4800
4801 auto Check = [&]() {
4802 // Look for: ~x | Mask == -1
4803 if (isMaskOrZero(M, /*Not=*/false, Q)) {
4804 if (Value *NotX =
4805 IC.getFreelyInverted(X, X->hasOneUse(), &IC.Builder)) {
4806 X = NotX;
4807 return true;
4808 }
4809 }
4810 return false;
4811 };
4812 if (Check())
4813 return true;
4814 std::swap(X, M);
4815 return Check();
4816 }
4817 if (ICmpInst::isEquality(Pred) && match(Op1, m_Zero()) &&
4818 match(Op0, m_OneUse(m_And(m_Value(X), m_Value(M))))) {
4819 auto Check = [&]() {
4820 // Look for: x & ~Mask == 0
4821 if (isMaskOrZero(M, /*Not=*/true, Q)) {
4822 if (Value *NotM =
4823 IC.getFreelyInverted(M, M->hasOneUse(), &IC.Builder)) {
4824 M = NotM;
4825 return true;
4826 }
4827 }
4828 return false;
4829 };
4830 if (Check())
4831 return true;
4832 std::swap(X, M);
4833 return Check();
4834 }
4835 return false;
4836 };
4837
4838 if (!IsLowBitMask())
4839 return nullptr;
4840
4841 return IC.Builder.CreateICmp(DstPred, X, M);
4842}
4843
4844/// Some comparisons can be simplified.
4845/// In this case, we are looking for comparisons that look like
4846/// a check for a lossy signed truncation.
4847/// Folds: (MaskedBits is a constant.)
4848/// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
4849/// Into:
4850/// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
4851/// Where KeptBits = bitwidth(%x) - MaskedBits
4852static Value *
4854 InstCombiner::BuilderTy &Builder) {
4855 CmpPredicate SrcPred;
4856 Value *X;
4857 const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
4858 // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
4859 if (!match(&I, m_c_ICmp(SrcPred,
4861 m_APInt(C1))),
4862 m_Deferred(X))))
4863 return nullptr;
4864
4865 // Potential handling of non-splats: for each element:
4866 // * if both are undef, replace with constant 0.
4867 // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
4868 // * if both are not undef, and are different, bailout.
4869 // * else, only one is undef, then pick the non-undef one.
4870
4871 // The shift amount must be equal.
4872 if (*C0 != *C1)
4873 return nullptr;
4874 const APInt &MaskedBits = *C0;
4875 assert(MaskedBits != 0 && "shift by zero should be folded away already.");
4876
4877 ICmpInst::Predicate DstPred;
4878 switch (SrcPred) {
4880 // ((%x << MaskedBits) a>> MaskedBits) == %x
4881 // =>
4882 // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
4884 break;
4886 // ((%x << MaskedBits) a>> MaskedBits) != %x
4887 // =>
4888 // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
4890 break;
4891 // FIXME: are more folds possible?
4892 default:
4893 return nullptr;
4894 }
4895
4896 auto *XType = X->getType();
4897 const unsigned XBitWidth = XType->getScalarSizeInBits();
4898 const APInt BitWidth = APInt(XBitWidth, XBitWidth);
4899 assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
4900
4901 // KeptBits = bitwidth(%x) - MaskedBits
4902 const APInt KeptBits = BitWidth - MaskedBits;
4903 assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
4904 // ICmpCst = (1 << KeptBits)
4905 const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
4906 assert(ICmpCst.isPowerOf2());
4907 // AddCst = (1 << (KeptBits-1))
4908 const APInt AddCst = ICmpCst.lshr(1);
4909 assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
4910
4911 // T0 = add %x, AddCst
4912 Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
4913 // T1 = T0 DstPred ICmpCst
4914 Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
4915
4916 return T1;
4917}
4918
4919// Given pattern:
4920// icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4921// we should move shifts to the same hand of 'and', i.e. rewrite as
4922// icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4923// We are only interested in opposite logical shifts here.
4924// One of the shifts can be truncated.
4925// If we can, we want to end up creating 'lshr' shift.
4926static Value *
4928 InstCombiner::BuilderTy &Builder) {
4929 if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
4930 !I.getOperand(0)->hasOneUse())
4931 return nullptr;
4932
4933 auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
4934
4935 // Look for an 'and' of two logical shifts, one of which may be truncated.
4936 // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
4937 Instruction *XShift, *MaybeTruncation, *YShift;
4938 if (!match(
4939 I.getOperand(0),
4940 m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
4942 m_AnyLogicalShift, m_Instruction(YShift))),
4943 m_Instruction(MaybeTruncation)))))
4944 return nullptr;
4945
4946 // We potentially looked past 'trunc', but only when matching YShift,
4947 // therefore YShift must have the widest type.
4948 Instruction *WidestShift = YShift;
4949 // Therefore XShift must have the shallowest type.
4950 // Or they both have identical types if there was no truncation.
4951 Instruction *NarrowestShift = XShift;
4952
4953 Type *WidestTy = WidestShift->getType();
4954 Type *NarrowestTy = NarrowestShift->getType();
4955 assert(NarrowestTy == I.getOperand(0)->getType() &&
4956 "We did not look past any shifts while matching XShift though.");
4957 bool HadTrunc = WidestTy != I.getOperand(0)->getType();
4958
4959 // If YShift is a 'lshr', swap the shifts around.
4960 if (match(YShift, m_LShr(m_Value(), m_Value())))
4961 std::swap(XShift, YShift);
4962
4963 // The shifts must be in opposite directions.
4964 auto XShiftOpcode = XShift->getOpcode();
4965 if (XShiftOpcode == YShift->getOpcode())
4966 return nullptr; // Do not care about same-direction shifts here.
4967
4968 Value *X, *XShAmt, *Y, *YShAmt;
4969 match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
4970 match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
4971
4972 // If one of the values being shifted is a constant, then we will end with
4973 // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
4974 // however, we will need to ensure that we won't increase instruction count.
4975 if (!isa<Constant>(X) && !isa<Constant>(Y)) {
4976 // At least one of the hands of the 'and' should be one-use shift.
4977 if (!match(I.getOperand(0),
4978 m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
4979 return nullptr;
4980 if (HadTrunc) {
4981 // Due to the 'trunc', we will need to widen X. For that either the old
4982 // 'trunc' or the shift amt in the non-truncated shift should be one-use.
4983 if (!MaybeTruncation->hasOneUse() &&
4984 !NarrowestShift->getOperand(1)->hasOneUse())
4985 return nullptr;
4986 }
4987 }
4988
4989 // We have two shift amounts from two different shifts. The types of those
4990 // shift amounts may not match. If that's the case let's bailout now.
4991 if (XShAmt->getType() != YShAmt->getType())
4992 return nullptr;
4993
4994 // As input, we have the following pattern:
4995 // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
4996 // We want to rewrite that as:
4997 // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
4998 // While we know that originally (Q+K) would not overflow
4999 // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
5000 // shift amounts. so it may now overflow in smaller bitwidth.
5001 // To ensure that does not happen, we need to ensure that the total maximal
5002 // shift amount is still representable in that smaller bit width.
5003 unsigned MaximalPossibleTotalShiftAmount =
5004 (WidestTy->getScalarSizeInBits() - 1) +
5005 (NarrowestTy->getScalarSizeInBits() - 1);
5006 APInt MaximalRepresentableShiftAmount =
5008 if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
5009 return nullptr;
5010
5011 // Can we fold (XShAmt+YShAmt) ?
5012 auto *NewShAmt = dyn_cast_or_null<Constant>(
5013 simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
5014 /*isNUW=*/false, SQ.getWithInstruction(&I)));
5015 if (!NewShAmt)
5016 return nullptr;
5017 if (NewShAmt->getType() != WidestTy) {
5018 NewShAmt =
5019 ConstantFoldCastOperand(Instruction::ZExt, NewShAmt, WidestTy, SQ.DL);
5020 if (!NewShAmt)
5021 return nullptr;
5022 }
5023 unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
5024
5025 // Is the new shift amount smaller than the bit width?
5026 // FIXME: could also rely on ConstantRange.
5027 if (!match(NewShAmt,
5029 APInt(WidestBitWidth, WidestBitWidth))))
5030 return nullptr;
5031
5032 // An extra legality check is needed if we had trunc-of-lshr.
5033 if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
5034 auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
5035 WidestShift]() {
5036 // It isn't obvious whether it's worth it to analyze non-constants here.
5037 // Also, let's basically give up on non-splat cases, pessimizing vectors.
5038 // If *any* of these preconditions matches we can perform the fold.
5039 Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
5040 ? NewShAmt->getSplatValue()
5041 : NewShAmt;
5042 // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
5043 if (NewShAmtSplat &&
5044 (NewShAmtSplat->isNullValue() ||
5045 NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
5046 return true;
5047 // We consider *min* leading zeros so a single outlier
5048 // blocks the transform as opposed to allowing it.
5049 if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
5051 unsigned MinLeadZero = Known.countMinLeadingZeros();
5052 // If the value being shifted has at most lowest bit set we can fold.
5053 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5054 if (MaxActiveBits <= 1)
5055 return true;
5056 // Precondition: NewShAmt u<= countLeadingZeros(C)
5057 if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
5058 return true;
5059 }
5060 if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
5062 unsigned MinLeadZero = Known.countMinLeadingZeros();
5063 // If the value being shifted has at most lowest bit set we can fold.
5064 unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
5065 if (MaxActiveBits <= 1)
5066 return true;
5067 // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
5068 if (NewShAmtSplat) {
5069 APInt AdjNewShAmt =
5070 (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
5071 if (AdjNewShAmt.ule(MinLeadZero))
5072 return true;
5073 }
5074 }
5075 return false; // Can't tell if it's ok.
5076 };
5077 if (!CanFold())
5078 return nullptr;
5079 }
5080
5081 // All good, we can do this fold.
5082 X = Builder.CreateZExt(X, WidestTy);
5083 Y = Builder.CreateZExt(Y, WidestTy);
5084 // The shift is the same that was for X.
5085 Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
5086 ? Builder.CreateLShr(X, NewShAmt)
5087 : Builder.CreateShl(X, NewShAmt);
5088 Value *T1 = Builder.CreateAnd(T0, Y);
5089 return Builder.CreateICmp(I.getPredicate(), T1,
5090 Constant::getNullValue(WidestTy));
5091}
5092
5093/// Fold
5094/// (-1 u/ x) u< y
5095/// ((x * y) ?/ x) != y
5096/// to
5097/// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
5098/// Note that the comparison is commutative, while inverted (u>=, ==) predicate
5099/// will mean that we are looking for the opposite answer.
5101 CmpPredicate Pred;
5102 Value *X, *Y;
5104 Instruction *Div;
5105 bool NeedNegation;
5106 // Look for: (-1 u/ x) u</u>= y
5107 if (!I.isEquality() &&
5108 match(&I, m_c_ICmp(Pred,
5110 m_Instruction(Div)),
5111 m_Value(Y)))) {
5112 Mul = nullptr;
5113
5114 // Are we checking that overflow does not happen, or does happen?
5115 switch (Pred) {
5117 NeedNegation = false;
5118 break; // OK
5120 NeedNegation = true;
5121 break; // OK
5122 default:
5123 return nullptr; // Wrong predicate.
5124 }
5125 } else // Look for: ((x * y) / x) !=/== y
5126 if (I.isEquality() &&
5127 match(&I, m_c_ICmp(Pred, m_Value(Y),
5130 m_Value(X)),
5132 m_Deferred(X))),
5133 m_Instruction(Div))))) {
5134 NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
5135 } else
5136 return nullptr;
5137
5139 // If the pattern included (x * y), we'll want to insert new instructions
5140 // right before that original multiplication so that we can replace it.
5141 bool MulHadOtherUses = Mul && !Mul->hasOneUse();
5142 if (MulHadOtherUses)
5143 Builder.SetInsertPoint(Mul);
5144
5145 Value *Call = Builder.CreateIntrinsic(
5146 Div->getOpcode() == Instruction::UDiv ? Intrinsic::umul_with_overflow
5147 : Intrinsic::smul_with_overflow,
5148 X->getType(), {X, Y}, /*FMFSource=*/nullptr, "mul");
5149
5150 // If the multiplication was used elsewhere, to ensure that we don't leave
5151 // "duplicate" instructions, replace uses of that original multiplication
5152 // with the multiplication result from the with.overflow intrinsic.
5153 if (MulHadOtherUses)
5154 replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
5155
5156 Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
5157 if (NeedNegation) // This technically increases instruction count.
5158 Res = Builder.CreateNot(Res, "mul.not.ov");
5159
5160 // If we replaced the mul, erase it. Do this after all uses of Builder,
5161 // as the mul is used as insertion point.
5162 if (MulHadOtherUses)
5164
5165 return Res;
5166}
5167
5169 InstCombiner::BuilderTy &Builder) {
5170 CmpPredicate Pred;
5171 Value *X;
5172 if (match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X)))) {
5173
5174 if (ICmpInst::isSigned(Pred))
5175 Pred = ICmpInst::getSwappedPredicate(Pred);
5176 else if (ICmpInst::isUnsigned(Pred))
5177 Pred = ICmpInst::getSignedPredicate(Pred);
5178 // else for equality-comparisons just keep the predicate.
5179
5180 return ICmpInst::Create(Instruction::ICmp, Pred, X,
5181 Constant::getNullValue(X->getType()), I.getName());
5182 }
5183
5184 // A value is not equal to its negation unless that value is 0 or
5185 // MinSignedValue, ie: a != -a --> (a & MaxSignedVal) != 0
5186 if (match(&I, m_c_ICmp(Pred, m_OneUse(m_Neg(m_Value(X))), m_Deferred(X))) &&
5187 ICmpInst::isEquality(Pred)) {
5188 Type *Ty = X->getType();
5189 uint32_t BitWidth = Ty->getScalarSizeInBits();
5190 Constant *MaxSignedVal =
5191 ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
5192 Value *And = Builder.CreateAnd(X, MaxSignedVal);
5193 Constant *Zero = Constant::getNullValue(Ty);
5194 return CmpInst::Create(Instruction::ICmp, Pred, And, Zero);
5195 }
5196
5197 return nullptr;
5198}
5199
5201 InstCombinerImpl &IC) {
5202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5203 // Normalize and operand as operand 0.
5204 CmpInst::Predicate Pred = I.getPredicate();
5205 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) {
5206 std::swap(Op0, Op1);
5207 Pred = ICmpInst::getSwappedPredicate(Pred);
5208 }
5209
5210 if (!match(Op0, m_c_And(m_Specific(Op1), m_Value(A))))
5211 return nullptr;
5212
5213 // (icmp (X & Y) u< X --> (X & Y) != X
5214 if (Pred == ICmpInst::ICMP_ULT)
5215 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5216
5217 // (icmp (X & Y) u>= X --> (X & Y) == X
5218 if (Pred == ICmpInst::ICMP_UGE)
5219 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5220
5221 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5222 // icmp (X & Y) eq/ne Y --> (X | ~Y) eq/ne -1 if Y is freely invertible and
5223 // Y is non-constant. If Y is constant the `X & C == C` form is preferable
5224 // so don't do this fold.
5225 if (!match(Op1, m_ImmConstant()))
5226 if (auto *NotOp1 =
5227 IC.getFreelyInverted(Op1, !Op1->hasNUsesOrMore(3), &IC.Builder))
5228 return new ICmpInst(Pred, IC.Builder.CreateOr(A, NotOp1),
5229 Constant::getAllOnesValue(Op1->getType()));
5230 // icmp (X & Y) eq/ne Y --> (~X & Y) eq/ne 0 if X is freely invertible.
5231 if (auto *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5232 return new ICmpInst(Pred, IC.Builder.CreateAnd(Op1, NotA),
5233 Constant::getNullValue(Op1->getType()));
5234 }
5235
5236 if (!ICmpInst::isSigned(Pred))
5237 return nullptr;
5238
5239 KnownBits KnownY = IC.computeKnownBits(A, &I);
5240 // (X & NegY) spred X --> (X & NegY) upred X
5241 if (KnownY.isNegative())
5242 return new ICmpInst(ICmpInst::getUnsignedPredicate(Pred), Op0, Op1);
5243
5244 if (Pred != ICmpInst::ICMP_SLE && Pred != ICmpInst::ICMP_SGT)
5245 return nullptr;
5246
5247 if (KnownY.isNonNegative())
5248 // (X & PosY) s<= X --> X s>= 0
5249 // (X & PosY) s> X --> X s< 0
5250 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
5251 Constant::getNullValue(Op1->getType()));
5252
5254 // (NegX & Y) s<= NegX --> Y s< 0
5255 // (NegX & Y) s> NegX --> Y s>= 0
5257 Constant::getNullValue(A->getType()));
5258
5259 return nullptr;
5260}
5261
5263 InstCombinerImpl &IC) {
5264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5265
5266 // Normalize or operand as operand 0.
5267 CmpInst::Predicate Pred = I.getPredicate();
5268 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value(A)))) {
5269 std::swap(Op0, Op1);
5270 Pred = ICmpInst::getSwappedPredicate(Pred);
5271 } else if (!match(Op0, m_c_Or(m_Specific(Op1), m_Value(A)))) {
5272 return nullptr;
5273 }
5274
5275 // icmp (X | Y) u<= X --> (X | Y) == X
5276 if (Pred == ICmpInst::ICMP_ULE)
5277 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5278
5279 // icmp (X | Y) u> X --> (X | Y) != X
5280 if (Pred == ICmpInst::ICMP_UGT)
5281 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5282
5283 if (ICmpInst::isEquality(Pred) && Op0->hasOneUse()) {
5284 // icmp (X | Y) eq/ne Y --> (X & ~Y) eq/ne 0 if Y is freely invertible
5285 if (Value *NotOp1 = IC.getFreelyInverted(
5286 Op1, !isa<Constant>(Op1) && !Op1->hasNUsesOrMore(3), &IC.Builder))
5287 return new ICmpInst(Pred, IC.Builder.CreateAnd(A, NotOp1),
5288 Constant::getNullValue(Op1->getType()));
5289 // icmp (X | Y) eq/ne Y --> (~X | Y) eq/ne -1 if X is freely invertible.
5290 if (Value *NotA = IC.getFreelyInverted(A, A->hasOneUse(), &IC.Builder))
5291 return new ICmpInst(Pred, IC.Builder.CreateOr(Op1, NotA),
5292 Constant::getAllOnesValue(Op1->getType()));
5293 }
5294 return nullptr;
5295}
5296
5298 InstCombinerImpl &IC) {
5299 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1), *A;
5300 // Normalize xor operand as operand 0.
5301 CmpInst::Predicate Pred = I.getPredicate();
5302 if (match(Op1, m_c_Xor(m_Specific(Op0), m_Value()))) {
5303 std::swap(Op0, Op1);
5304 Pred = ICmpInst::getSwappedPredicate(Pred);
5305 }
5306 if (!match(Op0, m_c_Xor(m_Specific(Op1), m_Value(A))))
5307 return nullptr;
5308
5309 // icmp (X ^ Y_NonZero) u>= X --> icmp (X ^ Y_NonZero) u> X
5310 // icmp (X ^ Y_NonZero) u<= X --> icmp (X ^ Y_NonZero) u< X
5311 // icmp (X ^ Y_NonZero) s>= X --> icmp (X ^ Y_NonZero) s> X
5312 // icmp (X ^ Y_NonZero) s<= X --> icmp (X ^ Y_NonZero) s< X
5314 if (PredOut != Pred && isKnownNonZero(A, Q))
5315 return new ICmpInst(PredOut, Op0, Op1);
5316
5317 // These transform work when A is negative.
5318 // X s< X^A, X s<= X^A, X u> X^A, X u>= X^A --> X s< 0
5319 // X s> X^A, X s>= X^A, X u< X^A, X u<= X^A --> X s>= 0
5320 if (match(A, m_Negative())) {
5321 CmpInst::Predicate NewPred;
5322 switch (ICmpInst::getStrictPredicate(Pred)) {
5323 default:
5324 return nullptr;
5325 case ICmpInst::ICMP_SLT:
5326 case ICmpInst::ICMP_UGT:
5327 NewPred = ICmpInst::ICMP_SLT;
5328 break;
5329 case ICmpInst::ICMP_SGT:
5330 case ICmpInst::ICMP_ULT:
5331 NewPred = ICmpInst::ICMP_SGE;
5332 break;
5333 }
5334 Constant *Const = Constant::getNullValue(Op0->getType());
5335 return new ICmpInst(NewPred, Op0, Const);
5336 }
5337
5338 return nullptr;
5339}
5340
5341/// Return true if X is a multiple of C.
5342/// TODO: Handle non-power-of-2 factors.
5343static bool isMultipleOf(Value *X, const APInt &C, const SimplifyQuery &Q) {
5344 if (C.isOne())
5345 return true;
5346
5347 if (!C.isPowerOf2())
5348 return false;
5349
5350 return MaskedValueIsZero(X, C - 1, Q);
5351}
5352
5354 bool &HasNSW, bool &HasNUW) {
5356 HasNUW = BO.hasNoUnsignedWrap();
5357 HasNSW = BO.hasNoSignedWrap();
5358 return ICmpInst::isEquality(Pred) ||
5359 (CmpInst::isUnsigned(Pred) && HasNUW) ||
5360 (CmpInst::isSigned(Pred) && HasNSW);
5361 }
5362 if (BO.getOpcode() == Instruction::Or) {
5363 // The callers only use this result for an or matched by m_AddLike, which
5364 // must be an or disjoint and is equivalent to an add nuw nsw.
5365 HasNUW = true;
5366 HasNSW = true;
5367 return true;
5368 }
5369 return false;
5370}
5371
5373 CmpInst::Predicate Pred,
5374 Value *&LHS, Value *&RHS,
5375 const SimplifyQuery &Q) {
5376 auto *BO0 = dyn_cast<BinaryOperator>(Op0);
5377 auto *BO1 = dyn_cast<BinaryOperator>(Op1);
5378 if (!BO0 || !BO1)
5379 return false;
5380
5381 bool IsEquality = ICmpInst::isEquality(Pred);
5382 bool IsSigned = ICmpInst::isSigned(Pred);
5383
5384 bool Op0HasNSW = false, Op0HasNUW = false;
5385 bool Op1HasNSW = false, Op1HasNUW = false;
5386 bool NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5387 bool NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5388
5389 Value *A, *B, *C, *D;
5390
5391 // Handle all add-like operations.
5392 if (match(BO0, m_AddLike(m_Value(A), m_Value(B))) &&
5393 match(BO1, m_AddLike(m_Value(C), m_Value(D)))) {
5394 if (!NoOp0WrapProblem || !NoOp1WrapProblem)
5395 return false;
5396
5397 if (A == C) {
5398 // (A + B) cmp (A + D) -> B cmp D
5399 LHS = B;
5400 RHS = D;
5401 return true;
5402 }
5403 if (A == D) {
5404 // (A + B) cmp (C + A) -> B cmp C
5405 LHS = B;
5406 RHS = C;
5407 return true;
5408 }
5409 if (B == C) {
5410 // (A + B) cmp (B + D) -> A cmp D
5411 LHS = A;
5412 RHS = D;
5413 return true;
5414 }
5415 if (B == D) {
5416 // (A + B) cmp (C + B) -> A cmp C
5417 LHS = A;
5418 RHS = C;
5419 return true;
5420 }
5421 return false;
5422 }
5423
5424 if (BO0->getOpcode() != BO1->getOpcode())
5425 return false;
5426
5427 A = BO0->getOperand(0);
5428 B = BO0->getOperand(1);
5429 C = BO1->getOperand(0);
5430 D = BO1->getOperand(1);
5431
5432 switch (BO0->getOpcode()) {
5433 case Instruction::Sub:
5434 if (!NoOp0WrapProblem || !NoOp1WrapProblem)
5435 return false;
5436
5437 // (A - B) cmp (C - B) -> A cmp C
5438 if (B == D) {
5439 LHS = A;
5440 RHS = C;
5441 return true;
5442 }
5443 // (A - B) cmp (A - D) -> D cmp B
5444 if (A == C) {
5445 LHS = D;
5446 RHS = B;
5447 return true;
5448 }
5449 return false;
5450
5451 case Instruction::Mul: {
5452 // Equality comparisons have additional modular-arithmetic folds and are
5453 // handled by the existing multiplication logic in foldICmpBinOp().
5454 if (IsEquality || !NoOp0WrapProblem || !NoOp1WrapProblem)
5455 return false;
5456
5457 Value *Z;
5458
5459 if (A == C) {
5460 // (A * B) cmp (A * D) -> B cmp D
5461 Z = A;
5462 LHS = B;
5463 RHS = D;
5464 } else if (A == D) {
5465 // (A * B) cmp (C * A) -> B cmp C
5466 Z = A;
5467 LHS = B;
5468 RHS = C;
5469 } else if (B == C) {
5470 // (A * B) cmp (B * D) -> A cmp D
5471 Z = B;
5472 LHS = A;
5473 RHS = D;
5474 } else if (B == D) {
5475 // (A * B) cmp (C * B) -> A cmp C
5476 Z = B;
5477 LHS = A;
5478 RHS = C;
5479 } else {
5480 return false;
5481 }
5482
5483 if (!IsSigned)
5484 return isKnownNonZero(Z, Q);
5485
5486 WithCache<const Value *> ZCache(Z);
5487 if (isKnownPositive(ZCache, Q))
5488 return true;
5489
5490 if (isKnownNegative(ZCache, Q)) {
5491 std::swap(LHS, RHS);
5492 return true;
5493 }
5494
5495 return false;
5496 }
5497 default:
5498 return false;
5499 }
5500}
5501
5502/// Try to fold icmp (binop), X or icmp X, (binop).
5503/// TODO: A large part of this logic is duplicated in InstSimplify's
5504/// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
5505/// duplication.
5507 const SimplifyQuery &SQ) {
5508 const SimplifyQuery Q = SQ.getWithInstruction(&I);
5509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5510
5511 // Special logic for binary operators.
5514 if (!BO0 && !BO1)
5515 return nullptr;
5516
5517 if (Instruction *NewICmp = foldICmpXNegX(I, Builder))
5518 return NewICmp;
5519
5520 const CmpInst::Predicate Pred = I.getPredicate();
5521
5522 // (X urem Y) == X --> X u< Y
5523 // (X urem Y) != X --> X u>= Y
5524 Value *Dividend, *Divisor;
5525 if (I.isEquality() &&
5526 match(&I, m_c_ICmp(m_URem(m_Value(Dividend), m_Value(Divisor)),
5527 m_Deferred(Dividend)))) {
5528 CmpInst::Predicate NewPred =
5530 return new ICmpInst(NewPred, Dividend, Divisor);
5531 }
5532
5533 Value *X;
5534
5535 // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
5536 // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
5537 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
5538 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5539 return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
5540 // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
5541 if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
5542 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5543 return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
5544
5545 {
5546 // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
5547 Constant *C;
5548 if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
5549 m_ImmConstant(C)))) &&
5550 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
5552 return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
5553 }
5554 // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
5555 if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
5556 m_ImmConstant(C)))) &&
5557 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
5559 return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
5560 }
5561 }
5562
5563 // (icmp eq/ne (X, -P2), INT_MIN)
5564 // -> (icmp slt/sge X, INT_MIN + P2)
5565 if (ICmpInst::isEquality(Pred) && BO0 &&
5566 match(I.getOperand(1), m_SignMask()) &&
5568 // Will Constant fold.
5569 Value *NewC = Builder.CreateSub(I.getOperand(1), BO0->getOperand(1));
5570 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SLT
5572 BO0->getOperand(0), NewC);
5573 }
5574
5575 {
5576 // Similar to above: an unsigned overflow comparison may use offset + mask:
5577 // ((Op1 + C) & C) u< Op1 --> Op1 != 0
5578 // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
5579 // Op0 u> ((Op0 + C) & C) --> Op0 != 0
5580 // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
5581 BinaryOperator *BO;
5582 const APInt *C;
5583 if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
5584 match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5586 CmpInst::Predicate NewPred =
5588 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5589 return new ICmpInst(NewPred, Op1, Zero);
5590 }
5591
5592 if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
5593 match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
5595 CmpInst::Predicate NewPred =
5597 Constant *Zero = ConstantInt::getNullValue(Op1->getType());
5598 return new ICmpInst(NewPred, Op0, Zero);
5599 }
5600 }
5601
5602 bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
5603 bool Op0HasNUW = false, Op1HasNUW = false;
5604 bool Op0HasNSW = false, Op1HasNSW = false;
5605 // Analyze the case when either Op0 or Op1 is an add instruction.
5606 // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
5607 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
5608
5609 if (BO0) {
5610 match(BO0, m_AddLike(m_Value(A), m_Value(B)));
5611 NoOp0WrapProblem = hasNoWrapProblem(*BO0, Pred, Op0HasNSW, Op0HasNUW);
5612 }
5613 if (BO1) {
5614 match(BO1, m_AddLike(m_Value(C), m_Value(D)));
5615 NoOp1WrapProblem = hasNoWrapProblem(*BO1, Pred, Op1HasNSW, Op1HasNUW);
5616 }
5617
5618 // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
5619 // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
5620 if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
5621 return new ICmpInst(Pred, A == Op1 ? B : A,
5622 Constant::getNullValue(Op1->getType()));
5623
5624 // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
5625 // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
5626 if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
5627 return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
5628 C == Op0 ? D : C);
5629
5630 // Fold comparisons of binops with a removable common operand.
5631 Value *LHS;
5632 Value *RHS;
5633 if (matchCommonBinOpOperands(Op0, Op1, Pred, LHS, RHS, Q))
5634 return new ICmpInst(Pred, LHS, RHS);
5635
5636 if (ICmpInst::isRelational(Pred)) {
5637 // Return if both X and Y is divisible by Z/-Z.
5638 // TODO: Generalize to check if (X - Y) is divisible by Z/-Z.
5639 auto ShareCommonDivisor = [&Q](Value *X, Value *Y, Value *Z,
5640 bool IsNegative) -> bool {
5641 const APInt *OffsetC;
5642 if (!match(Z, m_APInt(OffsetC)))
5643 return false;
5644
5645 // Fast path for Z == 1/-1.
5646 if (IsNegative ? OffsetC->isAllOnes() : OffsetC->isOne())
5647 return true;
5648
5649 APInt C = *OffsetC;
5650 if (IsNegative)
5651 C.negate();
5652 // Note: -INT_MIN is also negative.
5653 if (!C.isStrictlyPositive())
5654 return false;
5655
5656 return isMultipleOf(X, C, Q) && isMultipleOf(Y, C, Q);
5657 };
5658
5659 // The subtraction-related identities (A -nuw B) shown below require that
5660 // the subtraction does not wrap unsigned (i.e., A >=u B). Canonicalization
5661 // from (A -nuw 1) to (A + -1) means that such combinations ought to never
5662 // occur, as sub nuw ops should have been canonicalized to add ones. It may
5663 // however appear in the form of a or disjoint. Though, or disjoint A, -B
5664 // requires proving A <u B, for which the nowrap precondition can never be
5665 // satisfied. These are therefore skipped.
5666 //
5667 // icmp ult (A - 1), Op1 -> icmp ule A, Op1
5668 // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
5669 // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
5670 // icmp ule Op0, (C - 1) -> icmp ult Op0, C
5671
5672 // icmp slt (A + -1), Op1 -> icmp sle A, Op1
5673 // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
5674 // icmp sle (A + 1), Op1 -> icmp slt A, Op1
5675 // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
5676 // icmp ule (A + 1), Op0 -> icmp ult A, Op1
5677 // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
5678 bool IsNegative = ICmpInst::isLT(Pred) || ICmpInst::isGE(Pred);
5679 bool IsAddOrSignedPred = !IsNegative || ICmpInst::isSigned(Pred);
5680 if (A && NoOp0WrapProblem && IsAddOrSignedPred &&
5681 ShareCommonDivisor(A, Op1, B, IsNegative))
5683 Op1);
5684
5685 // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
5686 // icmp sle Op0, (C + -1) -> icmp slt Op0, C
5687 // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
5688 // icmp slt Op0, (C + 1) -> icmp sle Op0, C
5689 // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
5690 // icmp ult Op0, (C + 1) -> icmp ule Op0, C
5691 if (C && NoOp1WrapProblem &&
5692 ShareCommonDivisor(Op0, C, D,
5693 ICmpInst::isGT(Pred) || ICmpInst::isLE(Pred)))
5695 C);
5696 }
5697
5698 // if C1 has greater magnitude than C2:
5699 // icmp (A + C1), (C + C2) -> icmp (A + C3), C
5700 // s.t. C3 = C1 - C2
5701 //
5702 // if C2 has greater magnitude than C1:
5703 // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
5704 // s.t. C3 = C2 - C1
5705 if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
5706 (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
5707 const APInt *AP1, *AP2;
5708 // TODO: Support non-uniform vectors.
5709 // TODO: Allow poison passthrough if B or D's element is poison.
5710 if (match(B, m_APIntAllowPoison(AP1)) &&
5711 match(D, m_APIntAllowPoison(AP2)) &&
5712 AP1->isNegative() == AP2->isNegative()) {
5713 APInt AP1Abs = AP1->abs();
5714 APInt AP2Abs = AP2->abs();
5715 if (AP1Abs.uge(AP2Abs)) {
5716 APInt Diff = *AP1 - *AP2;
5717 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5718 Value *NewAdd = Builder.CreateAdd(
5719 A, C3, "", Op0HasNUW && Diff.ule(*AP1), Op0HasNSW);
5720 return new ICmpInst(Pred, NewAdd, C);
5721 } else {
5722 APInt Diff = *AP2 - *AP1;
5723 Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
5724 Value *NewAdd = Builder.CreateAdd(
5725 C, C3, "", Op1HasNUW && Diff.ule(*AP2), Op1HasNSW);
5726 return new ICmpInst(Pred, A, NewAdd);
5727 }
5728 }
5729 Constant *Cst1, *Cst2;
5730 if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
5731 ICmpInst::isEquality(Pred)) {
5732 Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
5733 Value *NewAdd = Builder.CreateAdd(C, Diff);
5734 return new ICmpInst(Pred, A, NewAdd);
5735 }
5736 }
5737
5738 // Analyze the case when either Op0 or Op1 is a sub instruction.
5739 // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
5740 A = nullptr;
5741 B = nullptr;
5742 C = nullptr;
5743 D = nullptr;
5744 if (BO0 && BO0->getOpcode() == Instruction::Sub) {
5745 A = BO0->getOperand(0);
5746 B = BO0->getOperand(1);
5747 }
5748 if (BO1 && BO1->getOpcode() == Instruction::Sub) {
5749 C = BO1->getOperand(0);
5750 D = BO1->getOperand(1);
5751 }
5752
5753 // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
5754 if (A == Op1 && NoOp0WrapProblem)
5755 return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
5756 // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
5757 if (C == Op0 && NoOp1WrapProblem)
5758 return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
5759
5760 // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
5761 // (A - B) u>/u<= A --> B u>/u<= A
5762 if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
5763 return new ICmpInst(Pred, B, A);
5764 // C u</u>= (C - D) --> C u</u>= D
5765 if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
5766 return new ICmpInst(Pred, C, D);
5767 // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
5768 if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
5769 isKnownNonZero(B, Q))
5771 // C u<=/u> (C - D) --> C u</u>= D iff B != 0
5772 if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
5773 isKnownNonZero(D, Q))
5775
5776 // icmp (0-X) < cst --> x > -cst
5777 if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
5778 Value *X;
5779 if (match(BO0, m_Neg(m_Value(X))))
5780 if (Constant *RHSC = dyn_cast<Constant>(Op1))
5781 if (RHSC->isNotMinSignedValue())
5782 return new ICmpInst(I.getSwappedPredicate(), X,
5783 ConstantExpr::getNeg(RHSC));
5784 }
5785
5786 if (Instruction *R = foldICmpXorXX(I, Q, *this))
5787 return R;
5788 if (Instruction *R = foldICmpOrXX(I, Q, *this))
5789 return R;
5790
5791 {
5792 // Try to remove shared multiplier from comparison:
5793 // X * Z pred Y * Z
5794 Value *X, *Y, *Z;
5795 if ((match(Op0, m_Mul(m_Value(X), m_Value(Z))) &&
5796 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y)))) ||
5797 (match(Op0, m_Mul(m_Value(Z), m_Value(X))) &&
5798 match(Op1, m_c_Mul(m_Specific(Z), m_Value(Y))))) {
5799 if (ICmpInst::isSigned(Pred)) {
5800 if (Op0HasNSW && Op1HasNSW) {
5802 SQ.getWithInstruction(&I));
5803 if (LessThan && match(LessThan, m_One()))
5804 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Z,
5805 Constant::getNullValue(Z->getType()));
5806 Value *GreaterThan = simplifyICmpInst(ICmpInst::ICMP_SGT, X, Y,
5807 SQ.getWithInstruction(&I));
5808 if (GreaterThan && match(GreaterThan, m_One()))
5809 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5810 }
5811 } else if (ICmpInst::isEquality(Pred)) {
5812 // Handle equality folds beyond direct multiplier cancellation.
5813 // If X != Y, fold (X *nw Z) eq/ne (Y *nw Z) -> Z eq/ne 0
5814 if (((Op0HasNSW && Op1HasNSW) || (Op0HasNUW && Op1HasNUW)) &&
5815 isKnownNonEqual(X, Y, SQ))
5816 return new ICmpInst(Pred, Z, Constant::getNullValue(Z->getType()));
5817
5818 KnownBits ZKnown = computeKnownBits(Z, &I);
5819 // if Z % 2 != 0
5820 // X * Z eq/ne Y * Z -> X eq/ne Y
5821 if (ZKnown.countMaxTrailingZeros() == 0)
5822 return new ICmpInst(Pred, X, Y);
5823 bool NonZero = !ZKnown.One.isZero() || isKnownNonZero(Z, Q);
5824 // if Z != 0 and nsw(X * Z) and nsw(Y * Z)
5825 // X * Z eq/ne Y * Z -> X eq/ne Y
5826 if (NonZero && Op0HasNSW && Op1HasNSW)
5827 return new ICmpInst(Pred, X, Y);
5828
5829 // If Z != 0 and nuw(X * Z) and nuw(Y * Z)
5830 // X * Z eq/ne Y * Z -> X eq/ne Y
5831 if (NonZero && Op0HasNUW && Op1HasNUW)
5832 return new ICmpInst(Pred, X, Y);
5833 }
5834 }
5835 }
5836
5837 BinaryOperator *SRem = nullptr;
5838 // icmp (srem X, Y), Y
5839 if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
5840 SRem = BO0;
5841 // icmp Y, (srem X, Y)
5842 else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
5843 Op0 == BO1->getOperand(1))
5844 SRem = BO1;
5845 if (SRem) {
5846 // We don't check hasOneUse to avoid increasing register pressure because
5847 // the value we use is the same value this instruction was already using.
5848 switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
5849 default:
5850 break;
5851 case ICmpInst::ICMP_EQ:
5852 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
5853 case ICmpInst::ICMP_NE:
5854 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
5855 case ICmpInst::ICMP_SGT:
5856 case ICmpInst::ICMP_SGE:
5857 return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
5859 case ICmpInst::ICMP_SLT:
5860 case ICmpInst::ICMP_SLE:
5861 return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
5863 }
5864 }
5865
5866 if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() &&
5867 (BO0->hasOneUse() || BO1->hasOneUse()) &&
5868 BO0->getOperand(1) == BO1->getOperand(1)) {
5869 switch (BO0->getOpcode()) {
5870 default:
5871 break;
5872 case Instruction::Add:
5873 case Instruction::Sub:
5874 case Instruction::Xor: {
5875 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
5876 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5877
5878 const APInt *C;
5879 if (match(BO0->getOperand(1), m_APInt(C))) {
5880 // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
5881 if (C->isSignMask()) {
5882 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5883 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5884 }
5885
5886 // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
5887 if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
5888 ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
5889 NewPred = I.getSwappedPredicate(NewPred);
5890 return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
5891 }
5892 }
5893 break;
5894 }
5895 case Instruction::Mul: {
5896 if (!I.isEquality())
5897 break;
5898
5899 const APInt *C;
5900 if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
5901 !C->isOne()) {
5902 // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
5903 // Mask = -1 >> count-trailing-zeros(C).
5904 if (unsigned TZs = C->countr_zero()) {
5905 Constant *Mask = ConstantInt::get(
5906 BO0->getType(),
5907 APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
5908 Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
5909 Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
5910 return new ICmpInst(Pred, And1, And2);
5911 }
5912 }
5913 break;
5914 }
5915 case Instruction::UDiv:
5916 case Instruction::LShr:
5917 if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
5918 break;
5919 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5920
5921 case Instruction::SDiv:
5922 if (!(I.isEquality() || match(BO0->getOperand(1), m_NonNegative())) ||
5923 !BO0->isExact() || !BO1->isExact())
5924 break;
5925 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5926
5927 case Instruction::AShr:
5928 if (!BO0->isExact() || !BO1->isExact())
5929 break;
5930 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5931
5932 case Instruction::Shl: {
5933 bool NUW = Op0HasNUW && Op1HasNUW;
5934 bool NSW = Op0HasNSW && Op1HasNSW;
5935 if (!NUW && !NSW)
5936 break;
5937 if (!NSW && I.isSigned())
5938 break;
5939 return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
5940 }
5941 }
5942 }
5943
5944 if (BO0) {
5945 // Transform A & (L - 1) `ult` L --> L != 0
5946 auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
5947 auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
5948
5949 if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
5950 auto *Zero = Constant::getNullValue(BO0->getType());
5951 return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
5952 }
5953 }
5954
5955 // For unsigned predicates / eq / ne:
5956 // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
5957 // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
5958 if (!ICmpInst::isSigned(Pred)) {
5959 if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
5960 return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
5961 Constant::getNullValue(Op1->getType()));
5962 else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
5963 return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
5964 Constant::getNullValue(Op0->getType()), Op0);
5965 }
5966
5968 return replaceInstUsesWith(I, V);
5969
5970 if (Instruction *R = foldICmpAndXX(I, Q, *this))
5971 return R;
5972
5974 return replaceInstUsesWith(I, V);
5975
5977 return replaceInstUsesWith(I, V);
5978
5979 return nullptr;
5980}
5981
5982/// Fold icmp Pred min|max(X, Y), Z.
5985 Value *Z, CmpPredicate Pred) {
5986 Value *X = MinMax->getLHS();
5987 Value *Y = MinMax->getRHS();
5988 if (ICmpInst::isSigned(Pred) && !MinMax->isSigned())
5989 return nullptr;
5990 if (ICmpInst::isUnsigned(Pred) && MinMax->isSigned()) {
5991 // Revert the transform signed pred -> unsigned pred
5992 // TODO: We can flip the signedness of predicate if both operands of icmp
5993 // are negative.
5994 if (isKnownNonNegative(Z, SQ.getWithInstruction(&I)) &&
5995 isKnownNonNegative(MinMax, SQ.getWithInstruction(&I))) {
5997 } else
5998 return nullptr;
5999 }
6000 SimplifyQuery Q = SQ.getWithInstruction(&I);
6001 auto IsCondKnownTrue = [](Value *Val) -> std::optional<bool> {
6002 if (!Val)
6003 return std::nullopt;
6004 if (match(Val, m_One()))
6005 return true;
6006 if (match(Val, m_Zero()))
6007 return false;
6008 return std::nullopt;
6009 };
6010 // Remove samesign here since it is illegal to keep it when we speculatively
6011 // execute comparisons. For example, `icmp samesign ult umax(X, -46), -32`
6012 // cannot be decomposed into `(icmp samesign ult X, -46) or (icmp samesign ult
6013 // -46, -32)`. `X` is allowed to be non-negative here.
6014 Pred = Pred.dropSameSign();
6015 auto CmpXZ = IsCondKnownTrue(simplifyICmpInst(Pred, X, Z, Q));
6016 auto CmpYZ = IsCondKnownTrue(simplifyICmpInst(Pred, Y, Z, Q));
6017 if (!CmpXZ.has_value() && !CmpYZ.has_value())
6018 return nullptr;
6019 if (!CmpXZ.has_value()) {
6020 std::swap(X, Y);
6021 std::swap(CmpXZ, CmpYZ);
6022 }
6023
6024 auto FoldIntoCmpYZ = [&]() -> Instruction * {
6025 if (CmpYZ.has_value())
6026 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *CmpYZ));
6027 return ICmpInst::Create(Instruction::ICmp, Pred, Y, Z);
6028 };
6029
6030 switch (Pred) {
6031 case ICmpInst::ICMP_EQ:
6032 case ICmpInst::ICMP_NE: {
6033 // If X == Z:
6034 // Expr Result
6035 // min(X, Y) == Z X <= Y
6036 // max(X, Y) == Z X >= Y
6037 // min(X, Y) != Z X > Y
6038 // max(X, Y) != Z X < Y
6039 if ((Pred == ICmpInst::ICMP_EQ) == *CmpXZ) {
6040 ICmpInst::Predicate NewPred =
6041 ICmpInst::getNonStrictPredicate(MinMax->getPredicate());
6042 if (Pred == ICmpInst::ICMP_NE)
6043 NewPred = ICmpInst::getInversePredicate(NewPred);
6044 return ICmpInst::Create(Instruction::ICmp, NewPred, X, Y);
6045 }
6046 // Otherwise (X != Z):
6047 ICmpInst::Predicate NewPred = MinMax->getPredicate();
6048 auto MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
6049 if (!MinMaxCmpXZ.has_value()) {
6050 std::swap(X, Y);
6051 std::swap(CmpXZ, CmpYZ);
6052 // Re-check pre-condition X != Z
6053 if (!CmpXZ.has_value() || (Pred == ICmpInst::ICMP_EQ) == *CmpXZ)
6054 break;
6055 MinMaxCmpXZ = IsCondKnownTrue(simplifyICmpInst(NewPred, X, Z, Q));
6056 }
6057 if (!MinMaxCmpXZ.has_value())
6058 break;
6059 if (*MinMaxCmpXZ) {
6060 // Expr Fact Result
6061 // min(X, Y) == Z X < Z false
6062 // max(X, Y) == Z X > Z false
6063 // min(X, Y) != Z X < Z true
6064 // max(X, Y) != Z X > Z true
6065 return replaceInstUsesWith(
6066 I, ConstantInt::getBool(I.getType(), Pred == ICmpInst::ICMP_NE));
6067 } else {
6068 // Expr Fact Result
6069 // min(X, Y) == Z X > Z Y == Z
6070 // max(X, Y) == Z X < Z Y == Z
6071 // min(X, Y) != Z X > Z Y != Z
6072 // max(X, Y) != Z X < Z Y != Z
6073 return FoldIntoCmpYZ();
6074 }
6075 break;
6076 }
6077 case ICmpInst::ICMP_SLT:
6078 case ICmpInst::ICMP_ULT:
6079 case ICmpInst::ICMP_SLE:
6080 case ICmpInst::ICMP_ULE:
6081 case ICmpInst::ICMP_SGT:
6082 case ICmpInst::ICMP_UGT:
6083 case ICmpInst::ICMP_SGE:
6084 case ICmpInst::ICMP_UGE: {
6085 bool IsSame = MinMax->getPredicate() == ICmpInst::getStrictPredicate(Pred);
6086 if (*CmpXZ) {
6087 if (IsSame) {
6088 // Expr Fact Result
6089 // min(X, Y) < Z X < Z true
6090 // min(X, Y) <= Z X <= Z true
6091 // max(X, Y) > Z X > Z true
6092 // max(X, Y) >= Z X >= Z true
6093 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
6094 } else {
6095 // Expr Fact Result
6096 // max(X, Y) < Z X < Z Y < Z
6097 // max(X, Y) <= Z X <= Z Y <= Z
6098 // min(X, Y) > Z X > Z Y > Z
6099 // min(X, Y) >= Z X >= Z Y >= Z
6100 return FoldIntoCmpYZ();
6101 }
6102 } else {
6103 if (IsSame) {
6104 // Expr Fact Result
6105 // min(X, Y) < Z X >= Z Y < Z
6106 // min(X, Y) <= Z X > Z Y <= Z
6107 // max(X, Y) > Z X <= Z Y > Z
6108 // max(X, Y) >= Z X < Z Y >= Z
6109 return FoldIntoCmpYZ();
6110 } else {
6111 // Expr Fact Result
6112 // max(X, Y) < Z X >= Z false
6113 // max(X, Y) <= Z X > Z false
6114 // min(X, Y) > Z X <= Z false
6115 // min(X, Y) >= Z X < Z false
6116 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
6117 }
6118 }
6119 break;
6120 }
6121 default:
6122 break;
6123 }
6124
6125 return nullptr;
6126}
6127
6128/// Match and fold patterns like:
6129/// icmp eq/ne X, min(max(X, Lo), Hi)
6130/// which represents a range check and can be represented as a ConstantRange.
6131///
6132/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
6133/// (X - Lo) u< (Hi + 1 - Lo)
6134/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
6135/// (X - (Hi + 1)) u< (Lo - (Hi + 1))
6137 MinMaxIntrinsic *Min) {
6138 if (!I.isEquality() || !Min->hasOneUse() || !Min->isMin())
6139 return nullptr;
6140
6141 const APInt *Lo = nullptr, *Hi = nullptr;
6142 if (Min->isSigned()) {
6143 if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
6144 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
6145 return nullptr;
6146 } else {
6147 if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
6148 !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
6149 return nullptr;
6150 }
6151
6154 APInt C, Offset;
6155 if (I.getPredicate() == ICmpInst::ICMP_EQ)
6156 CR.getEquivalentICmp(Pred, C, Offset);
6157 else
6158 CR.inverse().getEquivalentICmp(Pred, C, Offset);
6159
6160 if (!Offset.isZero())
6161 X = Builder.CreateAdd(X, ConstantInt::get(X->getType(), Offset));
6162
6163 return replaceInstUsesWith(
6164 I, Builder.CreateICmp(Pred, X, ConstantInt::get(X->getType(), C)));
6165}
6166
6167// Canonicalize checking for a power-of-2-or-zero value:
6169 InstCombiner::BuilderTy &Builder) {
6170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6171 const CmpInst::Predicate Pred = I.getPredicate();
6172 Value *A = nullptr;
6173 bool CheckIs;
6174 if (I.isEquality()) {
6175 // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
6176 // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
6177 if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
6178 m_Deferred(A)))) ||
6179 !match(Op1, m_ZeroInt()))
6180 A = nullptr;
6181
6182 // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
6183 // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
6184 if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
6185 A = Op1;
6186 else if (match(Op1,
6188 A = Op0;
6189
6190 CheckIs = Pred == ICmpInst::ICMP_EQ;
6191 } else if (ICmpInst::isUnsigned(Pred)) {
6192 // (A ^ (A-1)) u>= A --> ctpop(A) < 2 (two commuted variants)
6193 // ((A-1) ^ A) u< A --> ctpop(A) > 1 (two commuted variants)
6194
6195 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
6197 m_Specific(Op1))))) {
6198 A = Op1;
6199 CheckIs = Pred == ICmpInst::ICMP_UGE;
6200 } else if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
6202 m_Specific(Op0))))) {
6203 A = Op0;
6204 CheckIs = Pred == ICmpInst::ICMP_ULE;
6205 }
6206 }
6207
6208 if (A) {
6209 Type *Ty = A->getType();
6210 Value *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
6211 return CheckIs ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop,
6212 ConstantInt::get(Ty, 2))
6213 : new ICmpInst(ICmpInst::ICMP_UGT, CtPop,
6214 ConstantInt::get(Ty, 1));
6215 }
6216
6217 return nullptr;
6218}
6219
6220/// Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
6221using OffsetOp = std::pair<Instruction::BinaryOps, Value *>;
6223 bool AllowRecursion) {
6225 if (!Inst || !Inst->hasOneUse())
6226 return;
6227
6228 switch (Inst->getOpcode()) {
6229 case Instruction::Add:
6230 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(1));
6231 Offsets.emplace_back(Instruction::Sub, Inst->getOperand(0));
6232 break;
6233 case Instruction::Sub:
6234 Offsets.emplace_back(Instruction::Add, Inst->getOperand(1));
6235 break;
6236 case Instruction::Xor:
6237 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(1));
6238 Offsets.emplace_back(Instruction::Xor, Inst->getOperand(0));
6239 break;
6240 case Instruction::Shl:
6241 if (Inst->hasNoSignedWrap())
6242 Offsets.emplace_back(Instruction::AShr, Inst->getOperand(1));
6243 if (Inst->hasNoUnsignedWrap())
6244 Offsets.emplace_back(Instruction::LShr, Inst->getOperand(1));
6245 break;
6246 case Instruction::Select:
6247 if (AllowRecursion) {
6248 collectOffsetOp(Inst->getOperand(1), Offsets, /*AllowRecursion=*/false);
6249 collectOffsetOp(Inst->getOperand(2), Offsets, /*AllowRecursion=*/false);
6250 }
6251 break;
6252 default:
6253 break;
6254 }
6255}
6256
6258
6263
6265 return {OffsetKind::Invalid, nullptr, nullptr, nullptr, nullptr};
6266 }
6268 return {OffsetKind::Value, V, nullptr, nullptr, nullptr};
6269 }
6270 static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV,
6272 return {OffsetKind::Select, Cond, TrueV, FalseV, MDFrom};
6273 }
6274 bool isValid() const { return Kind != OffsetKind::Invalid; }
6276 switch (Kind) {
6278 llvm_unreachable("Invalid offset result");
6279 case OffsetKind::Value:
6280 return V0;
6281 case OffsetKind::Select:
6282 return Builder.CreateSelect(V0, V1, V2, "", MDFrom);
6283 }
6284 llvm_unreachable("Unknown OffsetKind enum");
6285 }
6286};
6287
6288/// Offset both sides of an equality icmp to see if we can save some
6289/// instructions: icmp eq/ne X, Y -> icmp eq/ne X op Z, Y op Z.
6290/// Note: This operation should not introduce poison.
6292 InstCombiner::BuilderTy &Builder,
6293 const SimplifyQuery &SQ) {
6294 assert(I.isEquality() && "Expected an equality icmp");
6295 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6296 if (!Op0->getType()->isIntOrIntVectorTy())
6297 return nullptr;
6298
6299 SmallVector<OffsetOp, 4> OffsetOps;
6300 collectOffsetOp(Op0, OffsetOps, /*AllowRecursion=*/true);
6301 collectOffsetOp(Op1, OffsetOps, /*AllowRecursion=*/true);
6302
6303 auto ApplyOffsetImpl = [&](Value *V, unsigned BinOpc, Value *RHS) -> Value * {
6304 switch (BinOpc) {
6305 // V = shl nsw X, RHS => X = ashr V, RHS
6306 case Instruction::AShr: {
6307 const APInt *CV, *CRHS;
6308 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6309 CV->ashr(*CRHS).shl(*CRHS) == *CV) &&
6311 return nullptr;
6312 break;
6313 }
6314 // V = shl nuw X, RHS => X = lshr V, RHS
6315 case Instruction::LShr: {
6316 const APInt *CV, *CRHS;
6317 if (!(match(V, m_APInt(CV)) && match(RHS, m_APInt(CRHS)) &&
6318 CV->lshr(*CRHS).shl(*CRHS) == *CV) &&
6320 return nullptr;
6321 break;
6322 }
6323 default:
6324 break;
6325 }
6326
6327 Value *Simplified = simplifyBinOp(BinOpc, V, RHS, SQ);
6328 if (!Simplified)
6329 return nullptr;
6330 // Reject constant expressions as they don't simplify things.
6331 if (isa<Constant>(Simplified) && !match(Simplified, m_ImmConstant()))
6332 return nullptr;
6333 // Check if the transformation introduces poison.
6334 return impliesPoison(RHS, V) ? Simplified : nullptr;
6335 };
6336
6337 auto ApplyOffset = [&](Value *V, unsigned BinOpc,
6338 Value *RHS) -> OffsetResult {
6339 if (auto *Sel = dyn_cast<SelectInst>(V)) {
6340 if (!Sel->hasOneUse())
6341 return OffsetResult::invalid();
6342 Value *TrueVal = ApplyOffsetImpl(Sel->getTrueValue(), BinOpc, RHS);
6343 if (!TrueVal)
6344 return OffsetResult::invalid();
6345 Value *FalseVal = ApplyOffsetImpl(Sel->getFalseValue(), BinOpc, RHS);
6346 if (!FalseVal)
6347 return OffsetResult::invalid();
6348 return OffsetResult::select(Sel->getCondition(), TrueVal, FalseVal, Sel);
6349 }
6350 if (Value *Simplified = ApplyOffsetImpl(V, BinOpc, RHS))
6351 return OffsetResult::value(Simplified);
6352 return OffsetResult::invalid();
6353 };
6354
6355 for (auto [BinOp, RHS] : OffsetOps) {
6356 auto BinOpc = static_cast<unsigned>(BinOp);
6357
6358 auto Op0Result = ApplyOffset(Op0, BinOpc, RHS);
6359 if (!Op0Result.isValid())
6360 continue;
6361 auto Op1Result = ApplyOffset(Op1, BinOpc, RHS);
6362 if (!Op1Result.isValid())
6363 continue;
6364
6365 Value *NewLHS = Op0Result.materialize(Builder);
6366 Value *NewRHS = Op1Result.materialize(Builder);
6367 return new ICmpInst(I.getPredicate(), NewLHS, NewRHS);
6368 }
6369
6370 return nullptr;
6371}
6372
6374 if (!I.isEquality())
6375 return nullptr;
6376
6377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6378 const CmpInst::Predicate Pred = I.getPredicate();
6379 Value *A, *B, *C, *D;
6380 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6381 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6382 Value *OtherVal = A == Op1 ? B : A;
6383 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6384 }
6385
6386 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6387 // A^c1 == C^c2 --> A == C^(c1^c2)
6388 ConstantInt *C1, *C2;
6389 if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
6390 Op1->hasOneUse()) {
6391 Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
6392 Value *Xor = Builder.CreateXor(C, NC);
6393 return new ICmpInst(Pred, A, Xor);
6394 }
6395
6396 // A^B == A^D -> B == D
6397 if (A == C)
6398 return new ICmpInst(Pred, B, D);
6399 if (A == D)
6400 return new ICmpInst(Pred, B, C);
6401 if (B == C)
6402 return new ICmpInst(Pred, A, D);
6403 if (B == D)
6404 return new ICmpInst(Pred, A, C);
6405 }
6406 }
6407
6408 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
6409 // A == (A^B) -> B == 0
6410 Value *OtherVal = A == Op0 ? B : A;
6411 return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
6412 }
6413
6414 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6415 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
6416 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6417 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
6418
6419 if (A == C) {
6420 X = B;
6421 Y = D;
6422 Z = A;
6423 } else if (A == D) {
6424 X = B;
6425 Y = C;
6426 Z = A;
6427 } else if (B == C) {
6428 X = A;
6429 Y = D;
6430 Z = B;
6431 } else if (B == D) {
6432 X = A;
6433 Y = C;
6434 Z = B;
6435 }
6436
6437 if (X) {
6438 // If X^Y is a negative power of two, then `icmp eq/ne (Z & NegP2), 0`
6439 // will fold to `icmp ult/uge Z, -NegP2` incurringb no additional
6440 // instructions.
6441 const APInt *C0, *C1;
6442 bool XorIsNegP2 = match(X, m_APInt(C0)) && match(Y, m_APInt(C1)) &&
6443 (*C0 ^ *C1).isNegatedPowerOf2();
6444
6445 // If either Op0/Op1 are both one use or X^Y will constant fold and one of
6446 // Op0/Op1 are one use, proceed. In those cases we are instruction neutral
6447 // but `icmp eq/ne A, 0` is easier to analyze than `icmp eq/ne A, B`.
6448 int UseCnt =
6449 int(Op0->hasOneUse()) + int(Op1->hasOneUse()) +
6450 (int(match(X, m_ImmConstant()) && match(Y, m_ImmConstant())));
6451 if (XorIsNegP2 || UseCnt >= 2) {
6452 // Build (X^Y) & Z
6453 Op1 = Builder.CreateXor(X, Y);
6454 Op1 = Builder.CreateAnd(Op1, Z);
6455 return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
6456 }
6457 }
6458 }
6459
6460 {
6461 // Similar to above, but specialized for constant because invert is needed:
6462 // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
6463 Value *X, *Y;
6464 Constant *C;
6465 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
6466 match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
6467 Value *Xor = Builder.CreateXor(X, Y);
6468 Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
6469 return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
6470 }
6471 }
6472
6473 if (match(Op1, m_ZExt(m_Value(A))) &&
6474 (Op0->hasOneUse() || Op1->hasOneUse())) {
6475 // (B & (Pow2C-1)) == zext A --> A == trunc B
6476 // (B & (Pow2C-1)) != zext A --> A != trunc B
6477 const APInt *MaskC;
6478 if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
6479 MaskC->countr_one() == A->getType()->getScalarSizeInBits())
6480 return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
6481 }
6482
6483 // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
6484 // For lshr and ashr pairs.
6485 const APInt *AP1, *AP2;
6486 if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6487 match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowPoison(AP2))))) ||
6488 (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowPoison(AP1)))) &&
6489 match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowPoison(AP2)))))) {
6490 if (*AP1 != *AP2)
6491 return nullptr;
6492 unsigned TypeBits = AP1->getBitWidth();
6493 unsigned ShAmt = AP1->getLimitedValue(TypeBits);
6494 if (ShAmt < TypeBits && ShAmt != 0) {
6495 ICmpInst::Predicate NewPred =
6497 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6498 APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
6499 return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
6500 }
6501 }
6502
6503 // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
6504 ConstantInt *Cst1;
6505 if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
6506 match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
6507 unsigned TypeBits = Cst1->getBitWidth();
6508 unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
6509 if (ShAmt < TypeBits && ShAmt != 0) {
6510 Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
6511 APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
6512 Value *And =
6513 Builder.CreateAnd(Xor, Builder.getInt(AndVal), I.getName() + ".mask");
6514 return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
6515 }
6516 }
6517
6518 // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
6519 // "icmp (and X, mask), cst"
6520 uint64_t ShAmt = 0;
6521 if (Op0->hasOneUse() &&
6522 match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
6523 match(Op1, m_ConstantInt(Cst1)) &&
6524 // Only do this when A has multiple uses. This is most important to do
6525 // when it exposes other optimizations.
6526 !A->hasOneUse()) {
6527 unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
6528
6529 if (ShAmt < ASize) {
6530 APInt MaskV =
6532 MaskV <<= ShAmt;
6533
6534 APInt CmpV = Cst1->getValue().zext(ASize);
6535 CmpV <<= ShAmt;
6536
6537 Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
6538 return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
6539 }
6540 }
6541
6543 return ICmp;
6544
6545 // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks
6546 // the top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s
6547 // INT_MAX", which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a
6548 // few steps of instcombine.
6549 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6550 if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
6552 A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
6553 (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
6555 Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
6556 return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
6558 Add, ConstantInt::get(A->getType(), C.shl(1)));
6559 }
6560
6561 // Canonicalize:
6562 // Assume B_Pow2 != 0
6563 // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
6564 // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
6565 if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
6566 isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, &I))
6567 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
6569
6570 if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
6571 isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, &I))
6572 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
6573 ConstantInt::getNullValue(Op1->getType()));
6574
6575 // Canonicalize:
6576 // icmp eq/ne X, OneUse(rotate-right(X))
6577 // -> icmp eq/ne X, rotate-left(X)
6578 // We generally try to convert rotate-right -> rotate-left, this just
6579 // canonicalizes another case.
6580 if (match(&I, m_c_ICmp(m_Value(A),
6582 m_Deferred(A), m_Deferred(A), m_Value(B))))))
6583 return new ICmpInst(
6584 Pred, A,
6585 Builder.CreateIntrinsic(Op0->getType(), Intrinsic::fshl, {A, A, B}));
6586
6587 // Canonicalize:
6588 // icmp eq/ne OneUse(A ^ Cst), B --> icmp eq/ne (A ^ B), Cst
6589 Constant *Cst;
6592 return new ICmpInst(Pred, Builder.CreateXor(A, B), Cst);
6593
6594 {
6595 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6596 auto m_Matcher =
6599 m_Sub(m_Value(B), m_Deferred(A)));
6600 std::optional<bool> IsZero = std::nullopt;
6601 if (match(&I, m_c_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)),
6602 m_Deferred(A))))
6603 IsZero = false;
6604 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6605 else if (match(&I,
6606 m_ICmp(m_OneUse(m_c_And(m_Value(A), m_Matcher)), m_Zero())))
6607 IsZero = true;
6608
6609 if (IsZero && isKnownToBeAPowerOfTwo(A, /* OrZero */ true, &I))
6610 // (icmp eq/ne (and (add/sub/xor X, P2), P2), P2)
6611 // -> (icmp eq/ne (and X, P2), 0)
6612 // (icmp eq/ne (and (add/sub/xor X, P2), P2), 0)
6613 // -> (icmp eq/ne (and X, P2), P2)
6614 return new ICmpInst(Pred, Builder.CreateAnd(B, A),
6615 *IsZero ? A
6616 : ConstantInt::getNullValue(A->getType()));
6617 }
6618
6619 if (auto *Res = foldICmpEqualityWithOffset(
6620 I, Builder, getSimplifyQuery().getWithInstruction(&I)))
6621 return Res;
6622
6623 return nullptr;
6624}
6625
6627 ICmpInst::Predicate Pred = ICmp.getPredicate();
6628 Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
6629
6630 // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
6631 // The trunc masks high bits while the compare may effectively mask low bits.
6632 Value *X;
6633 const APInt *C;
6634 if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
6635 return nullptr;
6636
6637 // This matches patterns corresponding to tests of the signbit as well as:
6638 // (trunc X) pred C2 --> (X & Mask) == C
6639 if (auto Res = decomposeBitTestICmp(Op0, Op1, Pred, /*LookThroughTrunc=*/true,
6640 /*AllowNonZeroC=*/true)) {
6641 Value *And = Builder.CreateAnd(Res->X, Res->Mask);
6642 Constant *C = ConstantInt::get(Res->X->getType(), Res->C);
6643 return new ICmpInst(Res->Pred, And, C);
6644 }
6645
6646 unsigned SrcBits = X->getType()->getScalarSizeInBits();
6647 if (auto *II = dyn_cast<IntrinsicInst>(X)) {
6648 if (II->getIntrinsicID() == Intrinsic::cttz ||
6649 II->getIntrinsicID() == Intrinsic::ctlz) {
6650 unsigned MaxRet = SrcBits;
6651 // If the "is_zero_poison" argument is set, then we know at least
6652 // one bit is set in the input, so the result is always at least one
6653 // less than the full bitwidth of that input.
6654 if (match(II->getArgOperand(1), m_One()))
6655 MaxRet--;
6656
6657 // Make sure the destination is wide enough to hold the largest output of
6658 // the intrinsic.
6659 if (llvm::Log2_32(MaxRet) + 1 <= Op0->getType()->getScalarSizeInBits())
6660 if (Instruction *I =
6661 foldICmpIntrinsicWithConstant(ICmp, II, C->zext(SrcBits)))
6662 return I;
6663 }
6664 }
6665
6666 return nullptr;
6667}
6668
6670 assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
6671 auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
6672 Value *X;
6673 if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
6674 return nullptr;
6675
6676 bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
6677 bool IsSignedCmp = ICmp.isSigned();
6678
6679 // icmp Pred (ext X), (ext Y)
6680 Value *Y;
6681 if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
6682 bool IsZext0 = isa<ZExtInst>(ICmp.getOperand(0));
6683 bool IsZext1 = isa<ZExtInst>(ICmp.getOperand(1));
6684
6685 if (IsZext0 != IsZext1) {
6686 // If X and Y and both i1
6687 // (icmp eq/ne (zext X) (sext Y))
6688 // eq -> (icmp eq (or X, Y), 0)
6689 // ne -> (icmp ne (or X, Y), 0)
6690 if (ICmp.isEquality() && X->getType()->isIntOrIntVectorTy(1) &&
6691 Y->getType()->isIntOrIntVectorTy(1))
6692 return new ICmpInst(ICmp.getPredicate(), Builder.CreateOr(X, Y),
6693 Constant::getNullValue(X->getType()));
6694
6695 // If we have mismatched casts and zext has the nneg flag, we can
6696 // treat the "zext nneg" as "sext". Otherwise, we cannot fold and quit.
6697
6698 auto *NonNegInst0 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(0));
6699 auto *NonNegInst1 = dyn_cast<PossiblyNonNegInst>(ICmp.getOperand(1));
6700
6701 bool IsNonNeg0 = NonNegInst0 && NonNegInst0->hasNonNeg();
6702 bool IsNonNeg1 = NonNegInst1 && NonNegInst1->hasNonNeg();
6703
6704 if ((IsZext0 && IsNonNeg0) || (IsZext1 && IsNonNeg1))
6705 IsSignedExt = true;
6706 else
6707 return nullptr;
6708 }
6709
6710 // Not an extension from the same type?
6711 Type *XTy = X->getType(), *YTy = Y->getType();
6712 if (XTy != YTy) {
6713 // One of the casts must have one use because we are creating a new cast.
6714 if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
6715 return nullptr;
6716 // Extend the narrower operand to the type of the wider operand.
6717 CastInst::CastOps CastOpcode =
6718 IsSignedExt ? Instruction::SExt : Instruction::ZExt;
6719 if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
6720 X = Builder.CreateCast(CastOpcode, X, YTy);
6721 else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
6722 Y = Builder.CreateCast(CastOpcode, Y, XTy);
6723 else
6724 return nullptr;
6725 }
6726
6727 // (zext X) == (zext Y) --> X == Y
6728 // (sext X) == (sext Y) --> X == Y
6729 if (ICmp.isEquality())
6730 return new ICmpInst(ICmp.getPredicate(), X, Y);
6731
6732 // A signed comparison of sign extended values simplifies into a
6733 // signed comparison.
6734 if (IsSignedCmp && IsSignedExt)
6735 return new ICmpInst(ICmp.getPredicate(), X, Y);
6736
6737 // The other three cases all fold into an unsigned comparison.
6738 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
6739 }
6740
6741 // Below here, we are only folding a compare with constant.
6742 auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
6743 if (!C)
6744 return nullptr;
6745
6746 // If a lossless truncate is possible...
6747 Type *SrcTy = CastOp0->getSrcTy();
6748 Constant *Res = getLosslessInvCast(C, SrcTy, CastOp0->getOpcode(), DL);
6749 if (Res) {
6750 if (ICmp.isEquality())
6751 return new ICmpInst(ICmp.getPredicate(), X, Res);
6752
6753 // A signed comparison of sign extended values simplifies into a
6754 // signed comparison.
6755 if (IsSignedExt && IsSignedCmp)
6756 return new ICmpInst(ICmp.getPredicate(), X, Res);
6757
6758 // The other three cases all fold into an unsigned comparison.
6759 return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res);
6760 }
6761
6762 // The re-extended constant changed, partly changed (in the case of a vector),
6763 // or could not be determined to be equal (in the case of a constant
6764 // expression), so the constant cannot be represented in the shorter type.
6765 // All the cases that fold to true or false will have already been handled
6766 // by simplifyICmpInst, so only deal with the tricky case.
6767 if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
6768 return nullptr;
6769
6770 // Is source op positive?
6771 // icmp ult (sext X), C --> icmp sgt X, -1
6772 if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
6774
6775 // Is source op negative?
6776 // icmp ugt (sext X), C --> icmp slt X, 0
6777 assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
6779}
6780
6781/// Handle icmp (cast x), (cast or constant).
6783 // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
6784 // icmp compares only pointer's value.
6785 // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
6786 Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
6787 Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
6788 if (SimplifiedOp0 || SimplifiedOp1)
6789 return new ICmpInst(ICmp.getPredicate(),
6790 SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
6791 SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
6792
6793 auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
6794 Value *Op1 = ICmp.getOperand(1);
6795 if (!CastOp0)
6796 return nullptr;
6797 if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
6798 return nullptr;
6799
6800 Value *Op0Src = CastOp0->getOperand(0);
6801 Type *SrcTy = CastOp0->getSrcTy();
6802 Type *DestTy = CastOp0->getDestTy();
6803
6804 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6805 // integer type is the same size as the pointer type.
6806 auto CompatibleSizes = [&](Type *PtrTy, Type *IntTy) {
6807 unsigned IntWidth = IntTy->getScalarType()->getIntegerBitWidth();
6808 unsigned IndexWidth = DL.getAddressSizeInBits(PtrTy);
6809 unsigned PtrWidth = DL.getPointerTypeSizeInBits(PtrTy);
6810 // For ptrtoint/inttoptr, we must check that IntWidth == IndexWidth and also
6811 // IndexWidth == PtrWidth to (not) handle non-integral pointers.
6812 return IntWidth == IndexWidth && IndexWidth == PtrWidth;
6813 };
6814 if (isa<PtrToIntInst, PtrToAddrInst>(CastOp0)) {
6815 bool HasPtrToInt = isa<PtrToIntInst>(CastOp0);
6816 Value *NewOp1 = nullptr;
6817 if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(Op1)) {
6818 NewOp1 = PtrToIntOp1->getOperand(0);
6819 HasPtrToInt = true;
6820 } else if (auto *PtrToAddrOp1 = dyn_cast<PtrToAddrOperator>(Op1)) {
6821 NewOp1 = PtrToAddrOp1->getOperand(0);
6822 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6823 NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6824 }
6825
6826 // For ptrtoaddr, IntWidth == IndexWidth is implied and we don't need to
6827 // check PtrWidth.
6828 if ((!HasPtrToInt || CompatibleSizes(SrcTy, DestTy)) &&
6829 (NewOp1 && NewOp1->getType() == Op0Src->getType()))
6830 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6831 }
6832
6833 // Do the same in the other direction for icmp (inttoptr x), (inttoptr/c).
6834 if (CastOp0->getOpcode() == Instruction::IntToPtr &&
6835 CompatibleSizes(DestTy, SrcTy)) {
6836 Value *NewOp1 = nullptr;
6837 if (auto *IntToPtrOp1 = dyn_cast<IntToPtrInst>(Op1)) {
6838 Value *IntSrc = IntToPtrOp1->getOperand(0);
6839 if (IntSrc->getType() == Op0Src->getType())
6840 NewOp1 = IntToPtrOp1->getOperand(0);
6841 } else if (auto *RHSC = dyn_cast<Constant>(Op1)) {
6842 NewOp1 = ConstantFoldConstant(ConstantExpr::getPtrToInt(RHSC, SrcTy), DL);
6843 }
6844
6845 if (NewOp1)
6846 return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
6847 }
6848
6849 if (Instruction *R = foldICmpWithTrunc(ICmp))
6850 return R;
6851
6852 return foldICmpWithZextOrSext(ICmp);
6853}
6854
6856 bool IsSigned) {
6857 switch (BinaryOp) {
6858 default:
6859 llvm_unreachable("Unsupported binary op");
6860 case Instruction::Add:
6861 case Instruction::Sub:
6862 return match(RHS, m_Zero());
6863 case Instruction::Mul:
6864 return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
6865 match(RHS, m_One());
6866 }
6867}
6868
6871 bool IsSigned, Value *LHS, Value *RHS,
6872 Instruction *CtxI) const {
6873 switch (BinaryOp) {
6874 default:
6875 llvm_unreachable("Unsupported binary op");
6876 case Instruction::Add:
6877 if (IsSigned)
6878 return computeOverflowForSignedAdd(LHS, RHS, CtxI);
6879 else
6880 return computeOverflowForUnsignedAdd(LHS, RHS, CtxI);
6881 case Instruction::Sub:
6882 if (IsSigned)
6883 return computeOverflowForSignedSub(LHS, RHS, CtxI);
6884 else
6885 return computeOverflowForUnsignedSub(LHS, RHS, CtxI);
6886 case Instruction::Mul:
6887 if (IsSigned)
6888 return computeOverflowForSignedMul(LHS, RHS, CtxI);
6889 else
6890 return computeOverflowForUnsignedMul(LHS, RHS, CtxI);
6891 }
6892}
6893
6894bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
6895 bool IsSigned, Value *LHS,
6896 Value *RHS, Instruction &OrigI,
6897 Value *&Result,
6898 Constant *&Overflow) {
6899 if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
6900 std::swap(LHS, RHS);
6901
6902 // If the overflow check was an add followed by a compare, the insertion point
6903 // may be pointing to the compare. We want to insert the new instructions
6904 // before the add in case there are uses of the add between the add and the
6905 // compare.
6906 Builder.SetInsertPoint(&OrigI);
6907
6908 Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
6909 if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
6910 OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
6911
6912 if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
6913 Result = LHS;
6914 Overflow = ConstantInt::getFalse(OverflowTy);
6915 return true;
6916 }
6917
6918 switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
6920 return false;
6923 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6924 Result->takeName(&OrigI);
6925 Overflow = ConstantInt::getTrue(OverflowTy);
6926 return true;
6928 Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
6929 Result->takeName(&OrigI);
6930 Overflow = ConstantInt::getFalse(OverflowTy);
6931 if (auto *Inst = dyn_cast<Instruction>(Result)) {
6932 if (IsSigned)
6933 Inst->setHasNoSignedWrap();
6934 else
6935 Inst->setHasNoUnsignedWrap();
6936 }
6937 return true;
6938 }
6939
6940 llvm_unreachable("Unexpected overflow result");
6941}
6942
6943/// Recognize and process idiom involving test for unsigned
6944/// overflow.
6945///
6946/// The caller has matched a pattern of the form:
6947/// I = cmp u (add(zext A, zext B), V
6948/// I = cmp u (mul(zext A, zext B), V
6949/// The function checks if this is a test for overflow and if so replaces
6950/// addition/multiplication with call to the umul intrinsic or the canonical
6951/// form of uadd overflow.
6952///
6953/// \param I Compare instruction.
6954/// \param Val Result of add/mul instruction. It is one of the arguments of
6955/// the compare instruction. Must be of integer type.
6956/// \param OtherVal The other argument of compare instruction.
6957/// \returns Instruction which must replace the compare instruction, NULL if no
6958/// replacement required.
6960 const APInt *OtherVal,
6961 InstCombinerImpl &IC) {
6962 // Don't bother doing this transformation for pointers, don't do it for
6963 // vectors.
6964 if (!isa<IntegerType>(Val->getType()))
6965 return nullptr;
6966
6967 auto *Instr = cast<Instruction>(Val);
6968 unsigned Opcode = Instr->getOpcode();
6969 assert(Opcode == Instruction::Add || Opcode == Instruction::Mul);
6970
6971 auto *LHS = cast<ZExtInst>(Instr->getOperand(0)),
6972 *RHS = cast<ZExtInst>(Instr->getOperand(1));
6973 Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
6974
6975 // Calculate type and width of the result produced by add/mul.with.overflow.
6976 Type *TyA = A->getType(), *TyB = B->getType();
6977 unsigned WidthA = TyA->getPrimitiveSizeInBits(),
6978 WidthB = TyB->getPrimitiveSizeInBits();
6979 unsigned ResultWidth;
6980 Type *ResultType;
6981 if (WidthB > WidthA) {
6982 ResultWidth = WidthB;
6983 ResultType = TyB;
6984 } else {
6985 ResultWidth = WidthA;
6986 ResultType = TyA;
6987 }
6988
6989 // In order to replace the original result with a narrower one, all uses must
6990 // ignore upper bits of the result. The number of used low bits must be not
6991 // greater than the width of add or mul.with.overflow.
6992 if (Val->hasNUsesOrMore(2))
6993 for (User *U : Val->users()) {
6994 if (U == &I)
6995 continue;
6996 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
6997 // Check if truncation ignores bits above ResultWidth.
6998 unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
6999 if (TruncWidth > ResultWidth)
7000 return nullptr;
7001 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
7002 // Check if AND ignores bits above ResultWidth.
7003 if (BO->getOpcode() != Instruction::And)
7004 return nullptr;
7005 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7006 const APInt &CVal = CI->getValue();
7007 if (CVal.getBitWidth() - CVal.countl_zero() > ResultWidth)
7008 return nullptr;
7009 } else {
7010 // In this case we could have the operand of the binary operation
7011 // being defined in another block, and performing the replacement
7012 // could break the dominance relation.
7013 return nullptr;
7014 }
7015 } else {
7016 // Other uses prohibit this transformation.
7017 return nullptr;
7018 }
7019 }
7020
7021 // Recognize patterns
7022 switch (I.getPredicate()) {
7023 case ICmpInst::ICMP_UGT: {
7024 // Recognize pattern:
7025 // val = add/mul(zext A, zext B)
7026 // cmp ugt val, max
7027 APInt MaxVal = APInt::getMaxValue(ResultWidth);
7028 MaxVal = MaxVal.zext(OtherVal->getBitWidth());
7029 if (MaxVal.eq(*OtherVal))
7030 break; // Recognized
7031 return nullptr;
7032 }
7033
7034 case ICmpInst::ICMP_ULT: {
7035 // Recognize pattern:
7036 // val = add/mul(zext A, zext B)
7037 // cmp ult val, max + 1
7038 APInt MaxVal = APInt::getOneBitSet(OtherVal->getBitWidth(), ResultWidth);
7039 if (MaxVal.eq(*OtherVal))
7040 break; // Recognized
7041 return nullptr;
7042 }
7043
7044 default:
7045 return nullptr;
7046 }
7047
7048 InstCombiner::BuilderTy &Builder = IC.Builder;
7049 Builder.SetInsertPoint(Instr);
7050
7051 // Replace: add/mul(zext A, zext B) --> canonical add/mul + overflow check
7052 Value *ResultA = A, *ResultB = B;
7053 if (WidthA < ResultWidth)
7054 ResultA = Builder.CreateZExt(A, ResultType);
7055 if (WidthB < ResultWidth)
7056 ResultB = Builder.CreateZExt(B, ResultType);
7057
7058 Value *ArithResult;
7059 Value *OverflowCheck;
7060
7061 if (Opcode == Instruction::Add) {
7062 // Canonical add overflow check: add + compare
7063 ArithResult = Builder.CreateAdd(ResultA, ResultB, "add");
7064 // Overflow if result < either operand (for unsigned add)
7065 if (I.getPredicate() == ICmpInst::ICMP_ULT)
7066 OverflowCheck =
7067 Builder.CreateICmpUGE(ArithResult, ResultA, "not.add.overflow");
7068 else
7069 OverflowCheck =
7070 Builder.CreateICmpULT(ArithResult, ResultA, "add.overflow");
7071 } else {
7072 // For multiplication, the intrinsic is actually the canonical form
7073 Value *Call = Builder.CreateIntrinsic(Intrinsic::umul_with_overflow,
7074 ResultType, {ResultA, ResultB},
7075 /*FMFSource=*/nullptr, "umul");
7076 ArithResult = Builder.CreateExtractValue(Call, 0, "umul.value");
7077 OverflowCheck = Builder.CreateExtractValue(Call, 1, "umul.overflow");
7078 if (I.getPredicate() == ICmpInst::ICMP_ULT)
7079 OverflowCheck = Builder.CreateNot(OverflowCheck);
7080 }
7081
7082 IC.addToWorklist(Instr);
7083
7084 // Replace uses of the original add/mul result with the new arithmetic result
7085 if (Val->hasNUsesOrMore(2)) {
7086 for (User *U : make_early_inc_range(Val->users())) {
7087 if (U == &I)
7088 continue;
7089 if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
7090 if (TI->getType()->getPrimitiveSizeInBits() == ResultWidth)
7091 IC.replaceInstUsesWith(*TI, ArithResult);
7092 else
7093 TI->setOperand(0, ArithResult);
7094 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
7095 assert(BO->getOpcode() == Instruction::And);
7096 // Replace (ArithResult & mask) --> zext (ArithResult & short_mask)
7097 ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
7098 APInt ShortMask = CI->getValue().trunc(ResultWidth);
7099 Value *ShortAnd = Builder.CreateAnd(ArithResult, ShortMask);
7100 Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
7101 IC.replaceInstUsesWith(*BO, Zext);
7102 } else {
7103 llvm_unreachable("Unexpected Binary operation");
7104 }
7106 }
7107 }
7108
7109 return IC.replaceInstUsesWith(I, OverflowCheck);
7110}
7111
7112/// When performing a comparison against a constant, it is possible that not all
7113/// the bits in the LHS are demanded. This helper method computes the mask that
7114/// IS demanded.
7116 const APInt *RHS;
7117 if (!match(I.getOperand(1), m_APInt(RHS)))
7119
7120 // If this is a normal comparison, it demands all bits. If it is a sign bit
7121 // comparison, it only demands the sign bit.
7122 bool UnusedBit;
7123 if (isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
7125
7126 switch (I.getPredicate()) {
7127 // For a UGT comparison, we don't care about any bits that
7128 // correspond to the trailing ones of the comparand. The value of these
7129 // bits doesn't impact the outcome of the comparison, because any value
7130 // greater than the RHS must differ in a bit higher than these due to carry.
7131 case ICmpInst::ICMP_UGT:
7132 return APInt::getBitsSetFrom(BitWidth, RHS->countr_one());
7133
7134 // Similarly, for a ULT comparison, we don't care about the trailing zeros.
7135 // Any value less than the RHS must differ in a higher bit because of carries.
7136 case ICmpInst::ICMP_ULT:
7137 return APInt::getBitsSetFrom(BitWidth, RHS->countr_zero());
7138
7139 default:
7141 }
7142}
7143
7144/// Check that one use is in the same block as the definition and all
7145/// other uses are in blocks dominated by a given block.
7146///
7147/// \param DI Definition
7148/// \param UI Use
7149/// \param DB Block that must dominate all uses of \p DI outside
7150/// the parent block
7151/// \return true when \p UI is the only use of \p DI in the parent block
7152/// and all other uses of \p DI are in blocks dominated by \p DB.
7153///
7155 const Instruction *UI,
7156 const BasicBlock *DB) const {
7157 assert(DI && UI && "Instruction not defined\n");
7158 // Ignore incomplete definitions.
7159 if (!DI->getParent())
7160 return false;
7161 // DI and UI must be in the same block.
7162 if (DI->getParent() != UI->getParent())
7163 return false;
7164 // Protect from self-referencing blocks.
7165 if (DI->getParent() == DB)
7166 return false;
7167 for (const User *U : DI->users()) {
7168 auto *Usr = cast<Instruction>(U);
7169 if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
7170 return false;
7171 }
7172 return true;
7173}
7174
7175/// Return true when the instruction sequence within a block is select-cmp-br.
7177 const BasicBlock *BB = SI->getParent();
7178 if (!BB)
7179 return false;
7180 auto *BI = dyn_cast<CondBrInst>(BB->getTerminator());
7181 if (!BI)
7182 return false;
7183 auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
7184 if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
7185 return false;
7186 return true;
7187}
7188
7189/// True when a select result is replaced by one of its operands
7190/// in select-icmp sequence. This will eventually result in the elimination
7191/// of the select.
7192///
7193/// \param SI Select instruction
7194/// \param Icmp Compare instruction
7195/// \param SIOpd Operand that replaces the select
7196///
7197/// Notes:
7198/// - The replacement is global and requires dominator information
7199/// - The caller is responsible for the actual replacement
7200///
7201/// Example:
7202///
7203/// entry:
7204/// %4 = select i1 %3, %C* %0, %C* null
7205/// %5 = icmp eq %C* %4, null
7206/// br i1 %5, label %9, label %7
7207/// ...
7208/// ; <label>:7 ; preds = %entry
7209/// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
7210/// ...
7211///
7212/// can be transformed to
7213///
7214/// %5 = icmp eq %C* %0, null
7215/// %6 = select i1 %3, i1 %5, i1 true
7216/// br i1 %6, label %9, label %7
7217/// ...
7218/// ; <label>:7 ; preds = %entry
7219/// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
7220///
7221/// Similar when the first operand of the select is a constant or/and
7222/// the compare is for not equal rather than equal.
7223///
7224/// NOTE: The function is only called when the select and compare constants
7225/// are equal, the optimization can work only for EQ predicates. This is not a
7226/// major restriction since a NE compare should be 'normalized' to an equal
7227/// compare, which usually happens in the combiner and test case
7228/// select-cmp-br.ll checks for it.
7230 const ICmpInst *Icmp,
7231 const unsigned SIOpd) {
7232 assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
7234 BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
7235 // The check for the single predecessor is not the best that can be
7236 // done. But it protects efficiently against cases like when SI's
7237 // home block has two successors, Succ and Succ1, and Succ1 predecessor
7238 // of Succ. Then SI can't be replaced by SIOpd because the use that gets
7239 // replaced can be reached on either path. So the uniqueness check
7240 // guarantees that the path all uses of SI (outside SI's parent) are on
7241 // is disjoint from all other paths out of SI. But that information
7242 // is more expensive to compute, and the trade-off here is in favor
7243 // of compile-time. It should also be noticed that we check for a single
7244 // predecessor and not only uniqueness. This to handle the situation when
7245 // Succ and Succ1 points to the same basic block.
7246 if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
7247 NumSel++;
7248 SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
7249 return true;
7250 }
7251 }
7252 return false;
7253}
7254
7255/// Try to fold the comparison based on range information we can get by checking
7256/// whether bits are known to be zero or one in the inputs.
7258 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7259 Type *Ty = Op0->getType();
7260 ICmpInst::Predicate Pred = I.getPredicate();
7261
7262 // Get scalar or pointer size.
7263 unsigned BitWidth = Ty->isIntOrIntVectorTy()
7264 ? Ty->getScalarSizeInBits()
7265 : DL.getPointerTypeSizeInBits(Ty->getScalarType());
7266
7267 if (!BitWidth)
7268 return nullptr;
7269
7270 KnownBits Op0Known(BitWidth);
7271 KnownBits Op1Known(BitWidth);
7272
7273 {
7274 // Don't use dominating conditions when folding icmp using known bits. This
7275 // may convert signed into unsigned predicates in ways that other passes
7276 // (especially IndVarSimplify) may not be able to reliably undo.
7277 SimplifyQuery Q = SQ.getWithoutDomCondCache().getWithInstruction(&I);
7279 Op0Known, Q))
7280 return &I;
7281
7282 if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, Q))
7283 return &I;
7284 }
7285
7286 // If an unsigned samesign comparison is not poison, both operands have the
7287 // same sign bit. Propagate a known sign bit between the temporary KnownBits
7288 // values so the existing range folds can use that constraint.
7289 if (I.hasSameSign() && I.isUnsigned()) {
7290 auto PropagateSignBit = [](const KnownBits &From, KnownBits &To) {
7291 if (To.isNegative() || To.isNonNegative())
7292 return;
7293 if (From.isNegative())
7294 To.makeNegative();
7295 else if (From.isNonNegative())
7296 To.makeNonNegative();
7297 };
7298 PropagateSignBit(Op0Known, Op1Known);
7299 PropagateSignBit(Op1Known, Op0Known);
7300 }
7301
7302 if (!isa<Constant>(Op0) && Op0Known.isConstant())
7303 return new ICmpInst(
7304 Pred, ConstantExpr::getIntegerValue(Ty, Op0Known.getConstant()), Op1);
7305 if (!isa<Constant>(Op1) && Op1Known.isConstant())
7306 return new ICmpInst(
7307 Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Known.getConstant()));
7308
7309 if (std::optional<bool> Res = ICmpInst::compare(Op0Known, Op1Known, Pred))
7310 return replaceInstUsesWith(I, ConstantInt::getBool(I.getType(), *Res));
7311
7312 // Given the known and unknown bits, compute a range that the LHS could be
7313 // in. Compute the Min, Max and RHS values based on the known bits. For the
7314 // EQ and NE we use unsigned values.
7315 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
7316 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
7317 if (I.isSigned()) {
7318 Op0Min = Op0Known.getSignedMinValue();
7319 Op0Max = Op0Known.getSignedMaxValue();
7320 Op1Min = Op1Known.getSignedMinValue();
7321 Op1Max = Op1Known.getSignedMaxValue();
7322 } else {
7323 Op0Min = Op0Known.getMinValue();
7324 Op0Max = Op0Known.getMaxValue();
7325 Op1Min = Op1Known.getMinValue();
7326 Op1Max = Op1Known.getMaxValue();
7327 }
7328
7329 // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
7330 // min/max canonical compare with some other compare. That could lead to
7331 // conflict with select canonicalization and infinite looping.
7332 // FIXME: This constraint may go away if min/max intrinsics are canonical.
7333 auto isMinMaxCmp = [&](Instruction &Cmp) {
7334 if (!Cmp.hasOneUse())
7335 return false;
7336 Value *A, *B;
7337 SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
7339 return false;
7340 return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
7341 match(Op1, m_MaxOrMin(m_Value(), m_Value()));
7342 };
7343 if (!isMinMaxCmp(I)) {
7344 switch (Pred) {
7345 default:
7346 break;
7347 case ICmpInst::ICMP_ULT: {
7348 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
7349 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7350 const APInt *CmpC;
7351 if (match(Op1, m_APInt(CmpC))) {
7352 // A <u C -> A == C-1 if min(A)+1 == C
7353 if (*CmpC == Op0Min + 1)
7354 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7355 ConstantInt::get(Op1->getType(), *CmpC - 1));
7356 // X <u C --> X == 0, if the number of zero bits in the bottom of X
7357 // exceeds the log2 of C.
7358 if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
7359 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7360 Constant::getNullValue(Op1->getType()));
7361 }
7362 break;
7363 }
7364 case ICmpInst::ICMP_UGT: {
7365 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
7366 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7367 const APInt *CmpC;
7368 if (match(Op1, m_APInt(CmpC))) {
7369 // A >u C -> A == C+1 if max(a)-1 == C
7370 if (*CmpC == Op0Max - 1)
7371 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7372 ConstantInt::get(Op1->getType(), *CmpC + 1));
7373 // X >u C --> X != 0, if the number of zero bits in the bottom of X
7374 // exceeds the log2 of C.
7375 if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
7376 return new ICmpInst(ICmpInst::ICMP_NE, Op0,
7377 Constant::getNullValue(Op1->getType()));
7378 }
7379 break;
7380 }
7381 case ICmpInst::ICMP_SLT: {
7382 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
7383 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7384 const APInt *CmpC;
7385 if (match(Op1, m_APInt(CmpC))) {
7386 if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
7387 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7388 ConstantInt::get(Op1->getType(), *CmpC - 1));
7389 }
7390 break;
7391 }
7392 case ICmpInst::ICMP_SGT: {
7393 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
7394 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
7395 const APInt *CmpC;
7396 if (match(Op1, m_APInt(CmpC))) {
7397 if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
7398 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
7399 ConstantInt::get(Op1->getType(), *CmpC + 1));
7400 }
7401 break;
7402 }
7403 }
7404 }
7405
7406 // Based on the range information we know about the LHS, see if we can
7407 // simplify this comparison. For example, (x&4) < 8 is always true.
7408 switch (Pred) {
7409 default:
7410 break;
7411 case ICmpInst::ICMP_EQ:
7412 case ICmpInst::ICMP_NE: {
7413 // If all bits are known zero except for one, then we know at most one bit
7414 // is set. If the comparison is against zero, then this is a check to see if
7415 // *that* bit is set.
7416 APInt Op0KnownZeroInverted = ~Op0Known.Zero;
7417 if (Op1Known.isZero()) {
7418 // If the LHS is an AND with the same constant, look through it.
7419 Value *LHS = nullptr;
7420 const APInt *LHSC;
7421 if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
7422 *LHSC != Op0KnownZeroInverted)
7423 LHS = Op0;
7424
7425 Value *X;
7426 const APInt *C1;
7427 if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
7428 Type *XTy = X->getType();
7429 unsigned Log2C1 = C1->countr_zero();
7430 APInt C2 = Op0KnownZeroInverted;
7431 APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
7432 if (C2Pow2.isPowerOf2()) {
7433 // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
7434 // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
7435 // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
7436 unsigned Log2C2 = C2Pow2.countr_zero();
7437 auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
7438 auto NewPred =
7440 return new ICmpInst(NewPred, X, CmpC);
7441 }
7442 }
7443 }
7444
7445 // Op0 eq C_Pow2 -> Op0 ne 0 if Op0 is known to be C_Pow2 or zero.
7446 if (Op1Known.isConstant() && Op1Known.getConstant().isPowerOf2() &&
7447 (Op0Known & Op1Known) == Op0Known)
7448 return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
7449 ConstantInt::getNullValue(Op1->getType()));
7450 break;
7451 }
7452 case ICmpInst::ICMP_SGE:
7453 if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
7454 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7455 break;
7456 case ICmpInst::ICMP_SLE:
7457 if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
7458 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7459 break;
7460 case ICmpInst::ICMP_UGE:
7461 if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
7462 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7463 break;
7464 case ICmpInst::ICMP_ULE:
7465 if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
7466 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
7467 break;
7468 }
7469
7470 // Turn a signed comparison into an unsigned one if both operands are known to
7471 // have the same sign. Set samesign if possible (except for equality
7472 // predicates).
7473 if ((I.isSigned() || (I.isUnsigned() && !I.hasSameSign())) &&
7474 ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
7475 (Op0Known.One.isNegative() && Op1Known.One.isNegative()))) {
7476 I.setPredicate(I.getUnsignedPredicate());
7477 I.setSameSign();
7478 return &I;
7479 }
7480
7481 return nullptr;
7482}
7483
7484/// If one operand of an icmp is effectively a bool (value range of {0,1}),
7485/// then try to reduce patterns based on that limit.
7487 Value *X, *Y;
7488 CmpPredicate Pred;
7489
7490 // X must be 0 and bool must be true for "ULT":
7491 // X <u (zext i1 Y) --> (X == 0) & Y
7492 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
7493 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
7494 return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
7495
7496 // X must be 0 or bool must be true for "ULE":
7497 // X <=u (sext i1 Y) --> (X == 0) | Y
7498 if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
7499 Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
7500 return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
7501
7502 // icmp eq/ne X, (zext/sext (icmp eq/ne X, C))
7503 CmpPredicate Pred1, Pred2;
7504 const APInt *C;
7505 Instruction *ExtI;
7506 if (match(&I, m_c_ICmp(Pred1, m_Value(X),
7509 m_APInt(C)))))) &&
7510 ICmpInst::isEquality(Pred1) && ICmpInst::isEquality(Pred2)) {
7511 bool IsSExt = ExtI->getOpcode() == Instruction::SExt;
7512 bool HasOneUse = ExtI->hasOneUse() && ExtI->getOperand(0)->hasOneUse();
7513 auto CreateRangeCheck = [&] {
7514 Value *CmpV1 =
7515 Builder.CreateICmp(Pred1, X, Constant::getNullValue(X->getType()));
7516 Value *CmpV2 = Builder.CreateICmp(
7517 Pred1, X, ConstantInt::getSigned(X->getType(), IsSExt ? -1 : 1));
7519 Pred1 == ICmpInst::ICMP_EQ ? Instruction::Or : Instruction::And,
7520 CmpV1, CmpV2);
7521 };
7522 if (C->isZero()) {
7523 if (Pred2 == ICmpInst::ICMP_EQ) {
7524 // icmp eq X, (zext/sext (icmp eq X, 0)) --> false
7525 // icmp ne X, (zext/sext (icmp eq X, 0)) --> true
7526 return replaceInstUsesWith(
7527 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7528 } else if (!IsSExt || HasOneUse) {
7529 // icmp eq X, (zext (icmp ne X, 0)) --> X == 0 || X == 1
7530 // icmp ne X, (zext (icmp ne X, 0)) --> X != 0 && X != 1
7531 // icmp eq X, (sext (icmp ne X, 0)) --> X == 0 || X == -1
7532 // icmp ne X, (sext (icmp ne X, 0)) --> X != 0 && X != -1
7533 return CreateRangeCheck();
7534 }
7535 } else if (IsSExt ? C->isAllOnes() : C->isOne()) {
7536 if (Pred2 == ICmpInst::ICMP_NE) {
7537 // icmp eq X, (zext (icmp ne X, 1)) --> false
7538 // icmp ne X, (zext (icmp ne X, 1)) --> true
7539 // icmp eq X, (sext (icmp ne X, -1)) --> false
7540 // icmp ne X, (sext (icmp ne X, -1)) --> true
7541 return replaceInstUsesWith(
7542 I, ConstantInt::getBool(I.getType(), Pred1 == ICmpInst::ICMP_NE));
7543 } else if (!IsSExt || HasOneUse) {
7544 // icmp eq X, (zext (icmp eq X, 1)) --> X == 0 || X == 1
7545 // icmp ne X, (zext (icmp eq X, 1)) --> X != 0 && X != 1
7546 // icmp eq X, (sext (icmp eq X, -1)) --> X == 0 || X == -1
7547 // icmp ne X, (sext (icmp eq X, -1)) --> X != 0 && X == -1
7548 return CreateRangeCheck();
7549 }
7550 } else {
7551 // when C != 0 && C != 1:
7552 // icmp eq X, (zext (icmp eq X, C)) --> icmp eq X, 0
7553 // icmp eq X, (zext (icmp ne X, C)) --> icmp eq X, 1
7554 // icmp ne X, (zext (icmp eq X, C)) --> icmp ne X, 0
7555 // icmp ne X, (zext (icmp ne X, C)) --> icmp ne X, 1
7556 // when C != 0 && C != -1:
7557 // icmp eq X, (sext (icmp eq X, C)) --> icmp eq X, 0
7558 // icmp eq X, (sext (icmp ne X, C)) --> icmp eq X, -1
7559 // icmp ne X, (sext (icmp eq X, C)) --> icmp ne X, 0
7560 // icmp ne X, (sext (icmp ne X, C)) --> icmp ne X, -1
7561 return ICmpInst::Create(
7562 Instruction::ICmp, Pred1, X,
7563 ConstantInt::getSigned(X->getType(), Pred2 == ICmpInst::ICMP_NE
7564 ? (IsSExt ? -1 : 1)
7565 : 0));
7566 }
7567 }
7568
7569 return nullptr;
7570}
7571
7572/// If we have an icmp le or icmp ge instruction with a constant operand, turn
7573/// it into the appropriate icmp lt or icmp gt instruction. This transform
7574/// allows them to be folded in visitICmpInst.
7576 CmpPredicate Pred = I.getCmpPredicate();
7577 if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
7579 return nullptr;
7580
7581 Value *Op0 = I.getOperand(0);
7582 Value *Op1 = I.getOperand(1);
7583 auto *Op1C = dyn_cast<Constant>(Op1);
7584 if (!Op1C)
7585 return nullptr;
7586
7587 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
7588 if (!FlippedStrictness)
7589 return nullptr;
7590
7591 auto *NewCmp =
7592 new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
7593 NewCmp->setSameSign(FlippedStrictness->first.hasSameSign());
7594 return NewCmp;
7595}
7596
7597/// If we have a comparison with a non-canonical predicate, if we can update
7598/// all the users, invert the predicate and adjust all the users.
7600 // Is the predicate already canonical?
7601 CmpInst::Predicate Pred = I.getPredicate();
7603 return nullptr;
7604
7605 // Can all users be adjusted to predicate inversion?
7606 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
7607 return nullptr;
7608
7609 // Ok, we can canonicalize comparison!
7610 // Let's first invert the comparison's predicate.
7611 I.setPredicate(CmpInst::getInversePredicate(Pred));
7612 I.setName(I.getName() + ".not");
7613
7614 // And, adapt users.
7616
7617 return &I;
7618}
7619
7620/// Integer compare with boolean values can always be turned into bitwise ops.
7622 InstCombiner::BuilderTy &Builder) {
7623 Value *A = I.getOperand(0), *B = I.getOperand(1);
7624 assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
7625
7626 // A boolean compared to true/false can be simplified to Op0/true/false in
7627 // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
7628 // Cases not handled by InstSimplify are always 'not' of Op0.
7629 if (match(B, m_Zero())) {
7630 switch (I.getPredicate()) {
7631 case CmpInst::ICMP_EQ: // A == 0 -> !A
7632 case CmpInst::ICMP_ULE: // A <=u 0 -> !A
7633 case CmpInst::ICMP_SGE: // A >=s 0 -> !A
7635 default:
7636 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7637 }
7638 } else if (match(B, m_One())) {
7639 switch (I.getPredicate()) {
7640 case CmpInst::ICMP_NE: // A != 1 -> !A
7641 case CmpInst::ICMP_ULT: // A <u 1 -> !A
7642 case CmpInst::ICMP_SGT: // A >s -1 -> !A
7644 default:
7645 llvm_unreachable("ICmp i1 X, C not simplified as expected.");
7646 }
7647 }
7648
7649 switch (I.getPredicate()) {
7650 default:
7651 llvm_unreachable("Invalid icmp instruction!");
7652 case ICmpInst::ICMP_EQ:
7653 // icmp eq i1 A, B -> ~(A ^ B)
7654 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
7655
7656 case ICmpInst::ICMP_NE:
7657 // icmp ne i1 A, B -> A ^ B
7658 return BinaryOperator::CreateXor(A, B);
7659
7660 case ICmpInst::ICMP_UGT:
7661 // icmp ugt -> icmp ult
7662 std::swap(A, B);
7663 [[fallthrough]];
7664 case ICmpInst::ICMP_ULT:
7665 // icmp ult i1 A, B -> ~A & B
7666 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
7667
7668 case ICmpInst::ICMP_SGT:
7669 // icmp sgt -> icmp slt
7670 std::swap(A, B);
7671 [[fallthrough]];
7672 case ICmpInst::ICMP_SLT:
7673 // icmp slt i1 A, B -> A & ~B
7674 return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
7675
7676 case ICmpInst::ICMP_UGE:
7677 // icmp uge -> icmp ule
7678 std::swap(A, B);
7679 [[fallthrough]];
7680 case ICmpInst::ICMP_ULE:
7681 // icmp ule i1 A, B -> ~A | B
7682 return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
7683
7684 case ICmpInst::ICMP_SGE:
7685 // icmp sge -> icmp sle
7686 std::swap(A, B);
7687 [[fallthrough]];
7688 case ICmpInst::ICMP_SLE:
7689 // icmp sle i1 A, B -> A | ~B
7690 return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
7691 }
7692}
7693
7694// Transform pattern like:
7695// (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
7696// (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
7697// Into:
7698// (X l>> Y) != 0
7699// (X l>> Y) == 0
7701 InstCombiner::BuilderTy &Builder) {
7702 CmpPredicate Pred, NewPred;
7703 Value *X, *Y;
7704 if (match(&Cmp,
7705 m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
7706 switch (Pred) {
7707 case ICmpInst::ICMP_ULE:
7708 NewPred = ICmpInst::ICMP_NE;
7709 break;
7710 case ICmpInst::ICMP_UGT:
7711 NewPred = ICmpInst::ICMP_EQ;
7712 break;
7713 default:
7714 return nullptr;
7715 }
7716 } else if (match(&Cmp, m_c_ICmp(Pred,
7719 m_Add(m_Shl(m_One(), m_Value(Y)),
7720 m_AllOnes()))),
7721 m_Value(X)))) {
7722 // The variant with 'add' is not canonical, (the variant with 'not' is)
7723 // we only get it because it has extra uses, and can't be canonicalized,
7724
7725 switch (Pred) {
7726 case ICmpInst::ICMP_ULT:
7727 NewPred = ICmpInst::ICMP_NE;
7728 break;
7729 case ICmpInst::ICMP_UGE:
7730 NewPred = ICmpInst::ICMP_EQ;
7731 break;
7732 default:
7733 return nullptr;
7734 }
7735 } else
7736 return nullptr;
7737
7738 Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
7739 Constant *Zero = Constant::getNullValue(NewX->getType());
7740 return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
7741}
7742
7744 InstCombiner::BuilderTy &Builder) {
7745 const CmpInst::Predicate Pred = Cmp.getPredicate();
7746 Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
7747 Value *V1, *V2;
7748
7749 auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
7750 Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
7751 if (auto *I = dyn_cast<Instruction>(V))
7752 I->copyIRFlags(&Cmp);
7753 Module *M = Cmp.getModule();
7755 M, Intrinsic::vector_reverse, V->getType());
7756 return CallInst::Create(F, V);
7757 };
7758
7759 if (match(LHS, m_VecReverse(m_Value(V1)))) {
7760 // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
7761 if (match(RHS, m_VecReverse(m_Value(V2))) &&
7762 (LHS->hasOneUse() || RHS->hasOneUse()))
7763 return createCmpReverse(Pred, V1, V2);
7764
7765 // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
7766 if (LHS->hasOneUse() && isSplatValue(RHS))
7767 return createCmpReverse(Pred, V1, RHS);
7768 }
7769 // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
7770 else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
7771 return createCmpReverse(Pred, LHS, V2);
7772
7773 ArrayRef<int> M;
7774 if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
7775 return nullptr;
7776
7777 // If both arguments of the cmp are shuffles that use the same mask and
7778 // shuffle within a single vector, move the shuffle after the cmp:
7779 // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
7780 Type *V1Ty = V1->getType();
7781 if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
7782 V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
7783 Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
7784 return new ShuffleVectorInst(NewCmp, M);
7785 }
7786
7787 // Try to canonicalize compare with splatted operand and splat constant.
7788 // TODO: We could generalize this for more than splats. See/use the code in
7789 // InstCombiner::foldVectorBinop().
7790 Constant *C;
7791 if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
7792 return nullptr;
7793
7794 // Length-changing splats are ok, so adjust the constants as needed:
7795 // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
7796 Constant *ScalarC = C->getSplatValue(/* AllowPoison */ true);
7797 int MaskSplatIndex;
7798 if (ScalarC && match(M, m_SplatOrPoisonMask(MaskSplatIndex))) {
7799 // We allow poison in matching, but this transform removes it for safety.
7800 // Demanded elements analysis should be able to recover some/all of that.
7801 C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
7802 ScalarC);
7803 SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
7804 Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
7805 return new ShuffleVectorInst(NewCmp, NewM);
7806 }
7807
7808 return nullptr;
7809}
7810
7811// extract(uadd.with.overflow(A, B), 0) ult A
7812// -> extract(uadd.with.overflow(A, B), 1)
7814 CmpInst::Predicate Pred = I.getPredicate();
7815 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7816
7817 Value *UAddOv;
7818 Value *A, *B;
7819 auto UAddOvResultPat = m_ExtractValue<0>(
7821 if (match(Op0, UAddOvResultPat) &&
7822 ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
7823 (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
7824 (match(A, m_One()) || match(B, m_One()))) ||
7825 (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
7826 (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
7827 // extract(uadd.with.overflow(A, B), 0) < A
7828 // extract(uadd.with.overflow(A, 1), 0) == 0
7829 // extract(uadd.with.overflow(A, -1), 0) != -1
7830 UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
7831 else if (match(Op1, UAddOvResultPat) && Pred == ICmpInst::ICMP_UGT &&
7832 (Op0 == A || Op0 == B))
7833 // A > extract(uadd.with.overflow(A, B), 0)
7834 UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
7835 else
7836 return nullptr;
7837
7838 return ExtractValueInst::Create(UAddOv, 1);
7839}
7840
7842 if (!I.getOperand(0)->getType()->isPointerTy() ||
7844 I.getParent()->getParent(),
7845 I.getOperand(0)->getType()->getPointerAddressSpace())) {
7846 return nullptr;
7847 }
7848 Value *Ptr;
7849 if (match(I.getOperand(0),
7851 match(I.getOperand(1), m_Zero())) {
7852 return ICmpInst::Create(Instruction::ICmp, I.getPredicate(), Ptr,
7853 I.getOperand(1));
7854 }
7855 return nullptr;
7856}
7857
7859 IRBuilderBase &Builder) {
7860 if (!ICmpInst::isEquality(I.getPredicate()))
7861 return nullptr;
7862
7863 // The caller puts constants after non-constants.
7864 Value *Op = I.getOperand(0);
7865 Value *Const = I.getOperand(1);
7866
7867 // For Cond an equality condition, fold
7868 //
7869 // icmp (eq|ne) (vreduce_(or|and) Op), (Zero|AllOnes) ->
7870 // icmp (eq|ne) Op, (Zero|AllOnes)
7871 //
7872 // with a bitcast.
7873 Value *Vec;
7874 if ((match(Const, m_ZeroInt()) &&
7876 m_Value(Vec))))) ||
7877 (match(Const, m_AllOnes()) &&
7879 m_Value(Vec)))))) {
7880 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
7881 if (!VecTy)
7882 return nullptr;
7883 Type *VecEltTy = VecTy->getElementType();
7884 unsigned ScalarBW =
7885 DL.getTypeSizeInBits(VecEltTy) * VecTy->getNumElements();
7886 if (!DL.fitsInLegalInteger(ScalarBW))
7887 return nullptr;
7888 Type *ScalarTy = IntegerType::get(I.getContext(), ScalarBW);
7889 Value *NewConst = match(Const, m_ZeroInt())
7890 ? ConstantInt::get(ScalarTy, 0)
7891 : ConstantInt::getAllOnesValue(ScalarTy);
7892 return CmpInst::Create(Instruction::ICmp, I.getPredicate(),
7893 Builder.CreateBitCast(Vec, ScalarTy), NewConst);
7894 }
7895 return nullptr;
7896}
7897
7898/// This function folds patterns produced by lowering of reduce idioms, such as
7899/// llvm.vector.reduce.and which are lowered into instruction chains. This code
7900/// attempts to generate fewer number of scalar comparisons instead of vector
7901/// comparisons when possible.
7903 InstCombiner::BuilderTy &Builder,
7904 const DataLayout &DL) {
7905 if (I.getType()->isVectorTy())
7906 return nullptr;
7907 CmpPredicate OuterPred, InnerPred;
7908 Value *LHS, *RHS;
7909
7910 // Match lowering of @llvm.vector.reduce.and. Turn
7911 /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
7912 /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
7913 /// %res = icmp <pred> i8 %scalar_ne, 0
7914 ///
7915 /// into
7916 ///
7917 /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
7918 /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
7919 /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
7920 ///
7921 /// for <pred> in {ne, eq}.
7922 if (!match(&I, m_ICmp(OuterPred,
7924 m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
7925 m_Zero())))
7926 return nullptr;
7927 auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
7928 if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
7929 return nullptr;
7930 unsigned NumBits =
7931 LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
7932 // TODO: Relax this to "not wider than max legal integer type"?
7933 if (!DL.isLegalInteger(NumBits))
7934 return nullptr;
7935
7936 if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
7937 auto *ScalarTy = Builder.getIntNTy(NumBits);
7938 LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
7939 RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
7940 return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
7941 I.getName());
7942 }
7943
7944 return nullptr;
7945}
7946
7947// This helper will be called with icmp operands in both orders.
7949 Value *Op0, Value *Op1,
7950 ICmpInst &CtxI) {
7951 // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
7952 if (auto *GEP = dyn_cast<GEPOperator>(Op0))
7953 if (Instruction *NI = foldGEPICmp(GEP, Op1, Pred, CtxI))
7954 return NI;
7955
7956 if (auto *SI = dyn_cast<SelectInst>(Op0))
7957 if (Instruction *NI = foldSelectICmp(Pred, SI, Op1, CtxI))
7958 return NI;
7959
7960 if (auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op0)) {
7961 if (Instruction *Res = foldICmpWithMinMax(CtxI, MinMax, Op1, Pred))
7962 return Res;
7963
7964 if (Instruction *Res = foldICmpWithClamp(CtxI, Op1, MinMax))
7965 return Res;
7966 }
7967
7968 {
7969 Value *X;
7970 const APInt *C;
7971 // icmp X+Cst, X
7972 if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
7973 return foldICmpAddOpConst(X, *C, Pred);
7974 }
7975
7976 // abs(X) >= X --> true
7977 // abs(X) u<= X --> true
7978 // abs(X) < X --> false
7979 // abs(X) u> X --> false
7980 // abs(X) u>= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7981 // abs(X) <= X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7982 // abs(X) == X --> IsIntMinPosion ? `X > -1`: `X u<= INTMIN`
7983 // abs(X) u< X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7984 // abs(X) > X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7985 // abs(X) != X --> IsIntMinPosion ? `X < 0` : `X > INTMIN`
7986 {
7987 Value *X;
7988 Constant *C;
7990 match(Op1, m_Specific(X))) {
7991 Value *NullValue = Constant::getNullValue(X->getType());
7992 Value *AllOnesValue = Constant::getAllOnesValue(X->getType());
7993 const APInt SMin =
7994 APInt::getSignedMinValue(X->getType()->getScalarSizeInBits());
7995 bool IsIntMinPosion = C->isAllOnesValue();
7996 switch (Pred) {
7997 case CmpInst::ICMP_ULE:
7998 case CmpInst::ICMP_SGE:
7999 return replaceInstUsesWith(CtxI, ConstantInt::getTrue(CtxI.getType()));
8000 case CmpInst::ICMP_UGT:
8001 case CmpInst::ICMP_SLT:
8003 case CmpInst::ICMP_UGE:
8004 case CmpInst::ICMP_SLE:
8005 case CmpInst::ICMP_EQ: {
8006 return replaceInstUsesWith(
8007 CtxI, IsIntMinPosion
8008 ? Builder.CreateICmpSGT(X, AllOnesValue)
8009 : Builder.CreateICmpULT(
8010 X, ConstantInt::get(X->getType(), SMin + 1)));
8011 }
8012 case CmpInst::ICMP_ULT:
8013 case CmpInst::ICMP_SGT:
8014 case CmpInst::ICMP_NE: {
8015 return replaceInstUsesWith(
8016 CtxI, IsIntMinPosion
8017 ? Builder.CreateICmpSLT(X, NullValue)
8018 : Builder.CreateICmpUGT(
8019 X, ConstantInt::get(X->getType(), SMin)));
8020 }
8021 default:
8022 llvm_unreachable("Invalid predicate!");
8023 }
8024 }
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 }
8040
8041 const SimplifyQuery Q = SQ.getWithInstruction(&CtxI);
8042 if (Value *V = foldICmpWithLowBitMaskedVal(Pred, Op0, Op1, Q, *this))
8043 return replaceInstUsesWith(CtxI, V);
8044
8045 // Folding (X / Y) pred X => X swap(pred) 0 for constant Y other than 0 or 1
8046 auto CheckUGT1 = [](const APInt &Divisor) { return Divisor.ugt(1); };
8047 {
8048 if (match(Op0, m_UDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
8049 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8051 }
8052
8053 if (!ICmpInst::isUnsigned(Pred) &&
8054 match(Op0, m_SDiv(m_Specific(Op1), m_CheckedInt(CheckUGT1)))) {
8055 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8057 }
8058 }
8059
8060 // Another case of this fold is (X >> Y) pred X => X swap(pred) 0 if Y != 0
8061 auto CheckNE0 = [](const APInt &Shift) { return !Shift.isZero(); };
8062 {
8063 if (match(Op0, m_LShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
8064 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8066 }
8067
8068 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SGE) &&
8069 match(Op0, m_AShr(m_Specific(Op1), m_CheckedInt(CheckNE0)))) {
8070 return new ICmpInst(ICmpInst::getSwappedPredicate(Pred), Op1,
8072 }
8073 }
8074
8075 // icmp (shl nsw/nuw X, L), (add nsw/nuw (shl nsw/nuw Y, L), K)
8076 // -> icmp X, (add nsw/nuw Y, K >> L)
8077 // We use AShr for nsw and LShr for nuw to safely peel off the shift.
8078 Value *X;
8079 uint64_t ShAmt;
8080 if (match(Op0, m_NUWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
8081 !CtxI.isSigned()) {
8082 if (ShAmt >= X->getType()->getScalarSizeInBits())
8083 return nullptr;
8084 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
8085 ShiftSemantics::Unsigned, &CtxI)) {
8086 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
8088 return new ICmpInst(Pred, X, NewOp1);
8089 }
8090 }
8091
8092 if (match(Op0, m_NSWShl(m_Value(X), m_ConstantInt(ShAmt))) &&
8093 !CtxI.isUnsigned()) {
8094 if (ShAmt >= X->getType()->getScalarSizeInBits())
8095 return nullptr;
8096 if (canEvaluateShifted(Op1, ShAmt, /*IsLeftShift=*/false,
8097 ShiftSemantics::Signed, &CtxI)) {
8098 Value *NewOp1 = getShiftedValue(Op1, ShAmt, /*IsLeftShift=*/false,
8100 return new ICmpInst(Pred, X, NewOp1);
8101 }
8102 }
8103 return nullptr;
8104}
8105
8107 bool Changed = false;
8108 const SimplifyQuery Q = SQ.getWithInstruction(&I);
8109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8110 unsigned Op0Cplxity = getComplexity(Op0);
8111 unsigned Op1Cplxity = getComplexity(Op1);
8112
8113 /// Orders the operands of the compare so that they are listed from most
8114 /// complex to least complex. This puts constants before unary operators,
8115 /// before binary operators.
8116 if (Op0Cplxity < Op1Cplxity) {
8117 I.swapOperands();
8118 std::swap(Op0, Op1);
8119 Changed = true;
8120 }
8121
8122 if (Value *V = simplifyICmpInst(I.getCmpPredicate(), Op0, Op1, Q))
8123 return replaceInstUsesWith(I, V);
8124
8126 return Res;
8127
8128 if (Op0->getType()->isIntOrIntVectorTy(1))
8130 return Res;
8131
8133 return Res;
8134
8136 return Res;
8137
8139 return Res;
8140
8142 return Res;
8143
8145 return Res;
8146
8148 return Res;
8149
8151 return Res;
8152
8153 // Test if the ICmpInst instruction is used exclusively by a select as
8154 // part of a minimum or maximum operation. If so, refrain from doing
8155 // any other folding. This helps out other analyses which understand
8156 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
8157 // and CodeGen. And in this case, at least one of the comparison
8158 // operands has at least one user besides the compare (the select),
8159 // which would often largely negate the benefit of folding anyway.
8160 //
8161 // Do the same for the other patterns recognized by matchSelectPattern.
8162 if (I.hasOneUse())
8163 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
8164 Value *A, *B;
8166 if (SPR.Flavor != SPF_UNKNOWN)
8167 return nullptr;
8168 }
8169
8170 // Do this after checking for min/max to prevent infinite looping.
8171 if (Instruction *Res = foldICmpWithZero(I))
8172 return Res;
8173
8174 Value *X;
8175 const APInt *C;
8176 if (I.getPredicate() == ICmpInst::ICMP_UGT &&
8177 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8178 match(Op1, m_Not(m_Specific(X)))) {
8179 if (C->isNonNegative())
8180 return new ICmpInst(ICmpInst::ICMP_SLT, X,
8181 Constant::getNullValue(X->getType()));
8182 return new ICmpInst(ICmpInst::ICMP_UGT, X,
8183 ConstantInt::get(X->getType(), ~*C));
8184 }
8185
8186 if (I.getPredicate() == ICmpInst::ICMP_ULT &&
8187 match(Op0, m_UMax(m_Value(X), m_APInt(C))) &&
8188 match(Op1, m_Not(m_Specific(X)))) {
8189 if (C->isNonNegative())
8190 return new ICmpInst(ICmpInst::ICMP_SGT, X,
8191 Constant::getAllOnesValue(X->getType()));
8192 return new ICmpInst(ICmpInst::ICMP_ULT, X,
8193 ConstantInt::get(X->getType(), ~*C));
8194 }
8195
8196 // FIXME: We only do this after checking for min/max to prevent infinite
8197 // looping caused by a reverse canonicalization of these patterns for min/max.
8198 // FIXME: The organization of folds is a mess. These would naturally go into
8199 // canonicalizeCmpWithConstant(), but we can't move all of the above folds
8200 // down here after the min/max restriction.
8201 ICmpInst::Predicate Pred = I.getPredicate();
8202 if (match(Op1, m_APInt(C))) {
8203 // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
8204 if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
8205 Constant *Zero = Constant::getNullValue(Op0->getType());
8206 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
8207 }
8208
8209 // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
8210 if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
8212 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
8213 }
8214 }
8215
8216 // The folds in here may rely on wrapping flags and special constants, so
8217 // they can break up min/max idioms in some cases but not seemingly similar
8218 // patterns.
8219 // FIXME: It may be possible to enhance select folding to make this
8220 // unnecessary. It may also be moot if we canonicalize to min/max
8221 // intrinsics.
8222 if (Instruction *Res = foldICmpBinOp(I, Q))
8223 return Res;
8224
8226 return Res;
8227
8228 // Try to match comparison as a sign bit test. Intentionally do this after
8229 // foldICmpInstWithConstant() to potentially let other folds to happen first.
8230 if (Instruction *New = foldSignBitTest(I))
8231 return New;
8232
8233 if (auto *PN = dyn_cast<PHINode>(Op0))
8234 if (Instruction *NV = foldOpIntoPhi(I, PN))
8235 return NV;
8236 if (auto *PN = dyn_cast<PHINode>(Op1))
8237 if (Instruction *NV = foldOpIntoPhi(I, PN))
8238 return NV;
8239
8241 return Res;
8242
8243 if (Instruction *Res = foldICmpCommutative(I.getCmpPredicate(), Op0, Op1, I))
8244 return Res;
8245 if (Instruction *Res =
8246 foldICmpCommutative(I.getSwappedCmpPredicate(), Op1, Op0, I))
8247 return Res;
8248
8249 if (I.isCommutative()) {
8250 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
8251 replaceOperand(I, 0, Pair->first);
8252 replaceOperand(I, 1, Pair->second);
8253 return &I;
8254 }
8255 }
8256
8257 // Fold icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8258 // when all select arms are constants, via truth table.
8260 return R;
8261
8262 // In case of a comparison with two select instructions having the same
8263 // condition, check whether one of the resulting branches can be simplified.
8264 // If so, just compare the other branch and select the appropriate result.
8265 // For example:
8266 // %tmp1 = select i1 %cmp, i32 %y, i32 %x
8267 // %tmp2 = select i1 %cmp, i32 %z, i32 %x
8268 // %cmp2 = icmp slt i32 %tmp2, %tmp1
8269 // The icmp will result false for the false value of selects and the result
8270 // will depend upon the comparison of true values of selects if %cmp is
8271 // true. Thus, transform this into:
8272 // %cmp = icmp slt i32 %y, %z
8273 // %sel = select i1 %cond, i1 %cmp, i1 false
8274 // This handles similar cases to transform.
8275 {
8276 Value *Cond, *A, *B, *C, *D;
8277 if (match(Op0, m_Select(m_Value(Cond), m_Value(A), m_Value(B))) &&
8279 (Op0->hasOneUse() || Op1->hasOneUse())) {
8280 // Check whether comparison of TrueValues can be simplified
8281 if (Value *Res = simplifyICmpInst(Pred, A, C, SQ)) {
8282 Value *NewICMP = Builder.CreateICmp(Pred, B, D);
8283 return SelectInst::Create(Cond, Res, NewICMP, /*NameStr=*/"",
8284 /*InsertBefore=*/nullptr,
8285 cast<Instruction>(Op0));
8286 }
8287 // Check whether comparison of FalseValues can be simplified
8288 if (Value *Res = simplifyICmpInst(Pred, B, D, SQ)) {
8289 Value *NewICMP = Builder.CreateICmp(Pred, A, C);
8290 return SelectInst::Create(Cond, NewICMP, Res, /*NameStr=*/"",
8291 /*InsertBefore=*/nullptr,
8292 cast<Instruction>(Op0));
8293 }
8294 }
8295 }
8296
8297 // icmp slt (sub nsw x, y), (add nsw x, y) --> icmp sgt y, 0
8298 // icmp ult (sub nuw x, y), (add nuw x, y) --> icmp ugt y, 0
8299 // icmp eq (sub nsw/nuw x, y), (add nsw/nuw x, y) --> icmp eq y, 0
8300 {
8301 Value *A, *B;
8302 CmpPredicate CmpPred;
8303 if (match(&I, m_c_ICmp(CmpPred, m_Sub(m_Value(A), m_Value(B)),
8305 auto *I0 = cast<OverflowingBinaryOperator>(Op0);
8306 auto *I1 = cast<OverflowingBinaryOperator>(Op1);
8307 bool I0NUW = I0->hasNoUnsignedWrap();
8308 bool I1NUW = I1->hasNoUnsignedWrap();
8309 bool I0NSW = I0->hasNoSignedWrap();
8310 bool I1NSW = I1->hasNoSignedWrap();
8311 if ((ICmpInst::isUnsigned(Pred) && I0NUW && I1NUW) ||
8312 (ICmpInst::isSigned(Pred) && I0NSW && I1NSW) ||
8313 (ICmpInst::isEquality(Pred) &&
8314 ((I0NUW || I0NSW) && (I1NUW || I1NSW)))) {
8315 return new ICmpInst(CmpPredicate::getSwapped(CmpPred), B,
8316 ConstantInt::get(Op0->getType(), 0));
8317 }
8318 }
8319 }
8320
8321 // Try to optimize equality comparisons against alloca-based pointers.
8322 if (Op0->getType()->isPointerTy() && I.isEquality()) {
8323 assert(Op1->getType()->isPointerTy() &&
8324 "Comparing pointer with non-pointer?");
8325 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
8326 if (foldAllocaCmp(Alloca))
8327 return nullptr;
8328 if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
8329 if (foldAllocaCmp(Alloca))
8330 return nullptr;
8331 }
8332
8333 if (Instruction *Res = foldICmpBitCast(I))
8334 return Res;
8335
8336 // TODO: Hoist this above the min/max bailout.
8338 return R;
8339
8340 // icmp (zext X), (and (trunc Y), Mask) -> icmp X, trunc Y IFF Mask exactly
8341 // covers the bits of X
8342 {
8343 Value *Y;
8344 const APInt *Mask;
8345 if (match(I.getOperand(1), m_ZExt(m_Value(X))) &&
8346 match(I.getOperand(0),
8347 m_OneUse(m_And(m_Trunc(m_Value(Y)), m_APInt(Mask))))) {
8348 Type *SmallType = X->getType();
8349 unsigned SmallWidth = SmallType->getScalarSizeInBits();
8350 if (Mask->isMask(SmallWidth) &&
8351 shouldChangeType(I.getOperand(0)->getType(), SmallType)) {
8352 Value *NewTrunc = Builder.CreateTrunc(Y, SmallType);
8353 return new ICmpInst(I.getUnsignedPredicate(), NewTrunc, X);
8354 }
8355 }
8356 }
8357
8358 {
8359 Value *X, *Y;
8360 // Transform (X & ~Y) == 0 --> (X & Y) != 0
8361 // and (X & ~Y) != 0 --> (X & Y) == 0
8362 // if A is a power of 2.
8363 if (match(Op0, m_And(m_Value(X), m_Not(m_Value(Y)))) &&
8364 match(Op1, m_Zero()) && isKnownToBeAPowerOfTwo(X, false, &I) &&
8365 I.isEquality())
8366 return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(X, Y),
8367 Op1);
8368
8369 // Op0 pred Op1 -> ~Op1 pred ~Op0, if this allows us to drop an instruction.
8370 if (Op0->getType()->isIntOrIntVectorTy()) {
8371 bool ConsumesOp0, ConsumesOp1;
8372 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
8373 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
8374 (ConsumesOp0 || ConsumesOp1)) {
8375 Value *InvOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
8376 Value *InvOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
8377 assert(InvOp0 && InvOp1 &&
8378 "Mismatch between isFreeToInvert and getFreelyInverted");
8379 return new ICmpInst(I.getSwappedPredicate(), InvOp0, InvOp1);
8380 }
8381 }
8382
8383 Instruction *AddI = nullptr;
8385 m_Instruction(AddI))) &&
8386 isa<IntegerType>(X->getType())) {
8387 Value *Result;
8388 Constant *Overflow;
8389 // m_UAddWithOverflow can match patterns that do not include an explicit
8390 // "add" instruction, so check the opcode of the matched op.
8391 if (AddI->getOpcode() == Instruction::Add &&
8392 OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, X, Y, *AddI,
8393 Result, Overflow)) {
8394 replaceInstUsesWith(*AddI, Result);
8395 eraseInstFromFunction(*AddI);
8396 return replaceInstUsesWith(I, Overflow);
8397 }
8398 }
8399
8400 // (zext X) + (zext Y) --> add + overflow check.
8401 // (zext X) * (zext Y) --> llvm.umul.with.overflow.
8402 if ((match(Op0, m_NUWAdd(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y)))) ||
8403 match(Op0, m_NUWMul(m_ZExt(m_Value(X)), m_ZExt(m_Value(Y))))) &&
8404 match(Op1, m_APInt(C))) {
8405 if (Instruction *R = processUZExtIdiom(I, Op0, C, *this))
8406 return R;
8407 }
8408
8409 // Signbit test folds
8410 // Fold (X u>> BitWidth - 1 Pred ZExt(i1)) --> X s< 0 Pred i1
8411 // Fold (X s>> BitWidth - 1 Pred SExt(i1)) --> X s< 0 Pred i1
8412 Instruction *ExtI;
8413 if ((I.isUnsigned() || I.isEquality()) &&
8414 match(Op1,
8416 Y->getType()->getScalarSizeInBits() == 1 &&
8417 (Op0->hasOneUse() || Op1->hasOneUse())) {
8418 unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
8419 Instruction *ShiftI;
8420 if (match(Op0, m_CombineAnd(m_Instruction(ShiftI),
8422 OpWidth - 1))))) {
8423 unsigned ExtOpc = ExtI->getOpcode();
8424 unsigned ShiftOpc = ShiftI->getOpcode();
8425 if ((ExtOpc == Instruction::ZExt && ShiftOpc == Instruction::LShr) ||
8426 (ExtOpc == Instruction::SExt && ShiftOpc == Instruction::AShr)) {
8427 Value *SLTZero =
8428 Builder.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
8429 Value *Cmp = Builder.CreateICmp(Pred, SLTZero, Y, I.getName());
8430 return replaceInstUsesWith(I, Cmp);
8431 }
8432 }
8433 }
8434 }
8435
8436 if (Instruction *Res = foldICmpEquality(I))
8437 return Res;
8438
8440 return Res;
8441
8442 if (Instruction *Res = foldICmpOfUAddOv(I))
8443 return Res;
8444
8446 return Res;
8447
8448 // The 'cmpxchg' instruction returns an aggregate containing the old value and
8449 // an i1 which indicates whether or not we successfully did the swap.
8450 //
8451 // Replace comparisons between the old value and the expected value with the
8452 // indicator that 'cmpxchg' returns.
8453 //
8454 // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
8455 // spuriously fail. In those cases, the old value may equal the expected
8456 // value but it is possible for the swap to not occur.
8457 if (I.getPredicate() == ICmpInst::ICMP_EQ)
8458 if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
8459 if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
8460 if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
8461 !ACXI->isWeak())
8462 return ExtractValueInst::Create(ACXI, 1);
8463
8465 return Res;
8466
8467 if (I.getType()->isVectorTy())
8468 if (Instruction *Res = foldVectorCmp(I, Builder))
8469 return Res;
8470
8472 return Res;
8473
8475 return Res;
8476
8477 {
8478 Value *A;
8479 const APInt *C1, *C2;
8480 ICmpInst::Predicate Pred = I.getPredicate();
8481 if (ICmpInst::isEquality(Pred)) {
8482 // sext(a) & c1 == c2 --> a & c3 == trunc(c2)
8483 // sext(a) & c1 != c2 --> a & c3 != trunc(c2)
8484 if (match(Op0, m_And(m_SExt(m_Value(A)), m_APInt(C1))) &&
8485 match(Op1, m_APInt(C2))) {
8486 Type *InputTy = A->getType();
8487 unsigned InputBitWidth = InputTy->getScalarSizeInBits();
8488 // c2 must be non-negative at the bitwidth of a.
8489 if (C2->getActiveBits() < InputBitWidth) {
8490 APInt TruncC1 = C1->trunc(InputBitWidth);
8491 // Check if there are 1s in C1 high bits of size InputBitWidth.
8492 if (C1->uge(APInt::getOneBitSet(C1->getBitWidth(), InputBitWidth)))
8493 TruncC1.setBit(InputBitWidth - 1);
8494 Value *AndInst = Builder.CreateAnd(A, TruncC1);
8495 return new ICmpInst(
8496 Pred, AndInst,
8497 ConstantInt::get(InputTy, C2->trunc(InputBitWidth)));
8498 }
8499 }
8500 }
8501 }
8502
8503 return Changed ? &I : nullptr;
8504}
8505
8506/// Fold fcmp ([us]itofp x, cst) if possible.
8508 Instruction *LHSI,
8509 Constant *RHSC) {
8510 const APFloat *RHS;
8511 if (!match(RHSC, m_APFloat(RHS)))
8512 return nullptr;
8513
8514 // Get the width of the mantissa. We don't want to hack on conversions that
8515 // might lose information from the integer, e.g. "i64 -> float"
8516 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
8517 if (MantissaWidth == -1)
8518 return nullptr; // Unknown.
8519
8520 Type *IntTy = LHSI->getOperand(0)->getType();
8521 unsigned IntWidth = IntTy->getScalarSizeInBits();
8522 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
8523
8524 if (I.isEquality()) {
8525 FCmpInst::Predicate P = I.getPredicate();
8526 bool IsExact = false;
8527 APSInt RHSCvt(IntWidth, LHSUnsigned);
8528 RHS->convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
8529
8530 // If the floating point constant isn't an integer value, we know if we will
8531 // ever compare equal / not equal to it.
8532 if (!IsExact) {
8533 // TODO: Can never be -0.0 and other non-representable values
8534 APFloat RHSRoundInt(*RHS);
8536 if (*RHS != RHSRoundInt) {
8538 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8539
8541 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8542 }
8543 }
8544
8545 // TODO: If the constant is exactly representable, is it always OK to do
8546 // equality compares as integer?
8547 }
8548
8549 // Check to see that the input is converted from an integer type that is small
8550 // enough that preserves all bits. TODO: check here for "known" sign bits.
8551 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
8552
8553 // Following test does NOT adjust IntWidth downwards for signed inputs,
8554 // because the most negative value still requires all the mantissa bits
8555 // to distinguish it from one less than that value.
8556 if ((int)IntWidth > MantissaWidth) {
8557 // Conversion would lose accuracy. Check if loss can impact comparison.
8558 int Exp = ilogb(*RHS);
8559 if (Exp == APFloat::IEK_Inf) {
8560 int MaxExponent = ilogb(APFloat::getLargest(RHS->getSemantics()));
8561 if (MaxExponent < (int)IntWidth - !LHSUnsigned)
8562 // Conversion could create infinity.
8563 return nullptr;
8564 } else {
8565 // Note that if RHS is zero or NaN, then Exp is negative
8566 // and first condition is trivially false.
8567 if (MantissaWidth <= Exp && Exp <= (int)IntWidth - !LHSUnsigned)
8568 // Conversion could affect comparison.
8569 return nullptr;
8570 }
8571 }
8572
8573 // Otherwise, we can potentially simplify the comparison. We know that it
8574 // will always come through as an integer value and we know the constant is
8575 // not a NAN (it would have been previously simplified).
8576 assert(!RHS->isNaN() && "NaN comparison not already folded!");
8577
8579 switch (I.getPredicate()) {
8580 default:
8581 llvm_unreachable("Unexpected predicate!");
8582 case FCmpInst::FCMP_UEQ:
8583 case FCmpInst::FCMP_OEQ:
8584 Pred = ICmpInst::ICMP_EQ;
8585 break;
8586 case FCmpInst::FCMP_UGT:
8587 case FCmpInst::FCMP_OGT:
8588 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
8589 break;
8590 case FCmpInst::FCMP_UGE:
8591 case FCmpInst::FCMP_OGE:
8592 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
8593 break;
8594 case FCmpInst::FCMP_ULT:
8595 case FCmpInst::FCMP_OLT:
8596 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
8597 break;
8598 case FCmpInst::FCMP_ULE:
8599 case FCmpInst::FCMP_OLE:
8600 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
8601 break;
8602 case FCmpInst::FCMP_UNE:
8603 case FCmpInst::FCMP_ONE:
8604 Pred = ICmpInst::ICMP_NE;
8605 break;
8606 case FCmpInst::FCMP_ORD:
8607 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8608 case FCmpInst::FCMP_UNO:
8609 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8610 }
8611
8612 // Now we know that the APFloat is a normal number, zero or inf.
8613
8614 // See if the FP constant is too large for the integer. For example,
8615 // comparing an i8 to 300.0.
8616 if (!LHSUnsigned) {
8617 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
8618 // and large values.
8619 APFloat SMax(RHS->getSemantics());
8620 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
8622 if (SMax < *RHS) { // smax < 13123.0
8623 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
8624 Pred == ICmpInst::ICMP_SLE)
8625 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8626 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8627 }
8628 } else {
8629 // If the RHS value is > UnsignedMax, fold the comparison. This handles
8630 // +INF and large values.
8631 APFloat UMax(RHS->getSemantics());
8632 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
8634 if (UMax < *RHS) { // umax < 13123.0
8635 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
8636 Pred == ICmpInst::ICMP_ULE)
8637 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8638 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8639 }
8640 }
8641
8642 if (!LHSUnsigned) {
8643 // See if the RHS value is < SignedMin.
8644 APFloat SMin(RHS->getSemantics());
8645 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
8647 if (SMin > *RHS) { // smin > 12312.0
8648 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
8649 Pred == ICmpInst::ICMP_SGE)
8650 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8651 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8652 }
8653 } else {
8654 // See if the RHS value is < UnsignedMin.
8655 APFloat UMin(RHS->getSemantics());
8656 UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
8658 if (UMin > *RHS) { // umin > 12312.0
8659 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
8660 Pred == ICmpInst::ICMP_UGE)
8661 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8662 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8663 }
8664 }
8665
8666 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
8667 // [0, UMAX], but it may still be fractional. Check whether this is the case
8668 // using the IsExact flag.
8669 // Don't do this for zero, because -0.0 is not fractional.
8670 APSInt RHSInt(IntWidth, LHSUnsigned);
8671 bool IsExact;
8672 RHS->convertToInteger(RHSInt, APFloat::rmTowardZero, &IsExact);
8673 if (!RHS->isZero()) {
8674 if (!IsExact) {
8675 // If we had a comparison against a fractional value, we have to adjust
8676 // the compare predicate and sometimes the value. RHSC is rounded towards
8677 // zero at this point.
8678 switch (Pred) {
8679 default:
8680 llvm_unreachable("Unexpected integer comparison!");
8681 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
8682 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8683 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
8684 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8685 case ICmpInst::ICMP_ULE:
8686 // (float)int <= 4.4 --> int <= 4
8687 // (float)int <= -4.4 --> false
8688 if (RHS->isNegative())
8689 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8690 break;
8691 case ICmpInst::ICMP_SLE:
8692 // (float)int <= 4.4 --> int <= 4
8693 // (float)int <= -4.4 --> int < -4
8694 if (RHS->isNegative())
8695 Pred = ICmpInst::ICMP_SLT;
8696 break;
8697 case ICmpInst::ICMP_ULT:
8698 // (float)int < -4.4 --> false
8699 // (float)int < 4.4 --> int <= 4
8700 if (RHS->isNegative())
8701 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
8702 Pred = ICmpInst::ICMP_ULE;
8703 break;
8704 case ICmpInst::ICMP_SLT:
8705 // (float)int < -4.4 --> int < -4
8706 // (float)int < 4.4 --> int <= 4
8707 if (!RHS->isNegative())
8708 Pred = ICmpInst::ICMP_SLE;
8709 break;
8710 case ICmpInst::ICMP_UGT:
8711 // (float)int > 4.4 --> int > 4
8712 // (float)int > -4.4 --> true
8713 if (RHS->isNegative())
8714 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8715 break;
8716 case ICmpInst::ICMP_SGT:
8717 // (float)int > 4.4 --> int > 4
8718 // (float)int > -4.4 --> int >= -4
8719 if (RHS->isNegative())
8720 Pred = ICmpInst::ICMP_SGE;
8721 break;
8722 case ICmpInst::ICMP_UGE:
8723 // (float)int >= -4.4 --> true
8724 // (float)int >= 4.4 --> int > 4
8725 if (RHS->isNegative())
8726 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
8727 Pred = ICmpInst::ICMP_UGT;
8728 break;
8729 case ICmpInst::ICMP_SGE:
8730 // (float)int >= -4.4 --> int >= -4
8731 // (float)int >= 4.4 --> int > 4
8732 if (!RHS->isNegative())
8733 Pred = ICmpInst::ICMP_SGT;
8734 break;
8735 }
8736 }
8737 }
8738
8739 // Lower this FP comparison into an appropriate integer version of the
8740 // comparison.
8741 return new ICmpInst(Pred, LHSI->getOperand(0),
8742 ConstantInt::get(LHSI->getOperand(0)->getType(), RHSInt));
8743}
8744
8745/// Fold fcmp/icmp pred (select C1, TV1, FV1), (select C2, TV2, FV2)
8746/// where all true/false values are constants that allow the compare to be
8747/// constant-folded for every combination of C1 and C2.
8748/// We compute a 4-entry truth table and use createLogicFromTable to
8749/// synthesize a boolean expression of C1 and C2.
8751 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
8752 Value *C1, *C2;
8753 Constant *TV1, *FV1, *TV2, *FV2;
8754
8755 if (!match(Op0, m_Select(m_Value(C1), m_Constant(TV1), m_Constant(FV1))) ||
8756 !match(Op1, m_Select(m_Value(C2), m_Constant(TV2), m_Constant(FV2))))
8757 return nullptr;
8758
8759 if (I.getType() != C1->getType() || I.getType() != C2->getType())
8760 return nullptr;
8761
8762 unsigned Pred = I.getPredicate();
8763 const DataLayout &DL = I.getDataLayout();
8764
8765 Constant *Res00 = ConstantFoldCompareInstOperands(Pred, FV1, FV2, DL);
8766 Constant *Res01 = ConstantFoldCompareInstOperands(Pred, FV1, TV2, DL);
8767 Constant *Res10 = ConstantFoldCompareInstOperands(Pred, TV1, FV2, DL);
8768 Constant *Res11 = ConstantFoldCompareInstOperands(Pred, TV1, TV2, DL);
8769
8770 if (!Res00 || !Res01 || !Res10 || !Res11)
8771 return nullptr;
8772
8773 if ((!Res00->isNullValue() && !Res00->isAllOnesValue()) ||
8774 (!Res01->isNullValue() && !Res01->isAllOnesValue()) ||
8775 (!Res10->isNullValue() && !Res10->isAllOnesValue()) ||
8776 (!Res11->isNullValue() && !Res11->isAllOnesValue()))
8777 return nullptr;
8778
8779 std::bitset<4> Table;
8780 if (!Res00->isNullValue())
8781 Table.set(0);
8782 if (!Res01->isNullValue())
8783 Table.set(1);
8784 if (!Res10->isNullValue())
8785 Table.set(2);
8786 if (!Res11->isNullValue())
8787 Table.set(3);
8788
8790 Op0->hasOneUse() && Op1->hasOneUse());
8791 if (!Res)
8792 return nullptr;
8793 return replaceInstUsesWith(I, Res);
8794}
8795
8796/// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
8798 Constant *RHSC) {
8799 // When C is not 0.0 and infinities are not allowed:
8800 // (C / X) < 0.0 is a sign-bit test of X
8801 // (C / X) < 0.0 --> X < 0.0 (if C is positive)
8802 // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
8803 //
8804 // Proof:
8805 // Multiply (C / X) < 0.0 by X * X / C.
8806 // - X is non zero, if it is the flag 'ninf' is violated.
8807 // - C defines the sign of X * X * C. Thus it also defines whether to swap
8808 // the predicate. C is also non zero by definition.
8809 //
8810 // Thus X * X / C is non zero and the transformation is valid. [qed]
8811
8812 FCmpInst::Predicate Pred = I.getPredicate();
8813
8814 // Check that predicates are valid.
8815 if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
8816 (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
8817 return nullptr;
8818
8819 // Check that RHS operand is zero.
8820 if (!match(RHSC, m_AnyZeroFP()))
8821 return nullptr;
8822
8823 // Check fastmath flags ('ninf').
8824 if (!LHSI->hasNoInfs() || !I.hasNoInfs())
8825 return nullptr;
8826
8827 // Check the properties of the dividend. It must not be zero to avoid a
8828 // division by zero (see Proof).
8829 const APFloat *C;
8830 if (!match(LHSI->getOperand(0), m_APFloat(C)))
8831 return nullptr;
8832
8833 if (C->isZero())
8834 return nullptr;
8835
8836 // Get swapped predicate if necessary.
8837 if (C->isNegative())
8838 Pred = I.getSwappedPredicate();
8839
8840 return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
8841}
8842
8843// Transform 'fptrunc(x) cmp C' to 'x cmp ext(C)' if possible.
8844// Patterns include:
8845// fptrunc(x) < C --> x < ext(C)
8846// fptrunc(x) <= C --> x <= ext(C)
8847// fptrunc(x) > C --> x > ext(C)
8848// fptrunc(x) >= C --> x >= ext(C)
8849// fptrunc(x) ord/uno C --> x ord/uno 0
8850// where 'ext(C)' is the extension of 'C' to the type of 'x' with a small bias
8851// due to precision loss.
8853 const Constant &C) {
8854 FCmpInst::Predicate Pred = I.getPredicate();
8855 Type *DestType = FPTrunc.getOperand(0)->getType();
8856
8857 const APFloat *CValue;
8858 // TODO: support vec
8859 if (!match(&C, m_APFloat(CValue)))
8860 return nullptr;
8861
8862 // Handle ord/uno
8863 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
8864 assert(!CValue->isNaN() &&
8865 "X ord/uno NaN should be folded away by simplifyFCmpInst()");
8866 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8867 ConstantFP::getZero(DestType), "", &I);
8868 }
8869
8870 // Handle <, >, <=, >=
8871 bool RoundDown = false;
8872
8873 if (Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE ||
8874 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT)
8875 RoundDown = true;
8876 else if (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT ||
8877 Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)
8878 RoundDown = false;
8879 else
8880 return nullptr;
8881
8882 if (CValue->isNaN() || CValue->isInfinity())
8883 return nullptr;
8884
8885 auto ConvertFltSema = [](const APFloat &Src, const fltSemantics &Sema) {
8886 bool LosesInfo;
8887 APFloat Dest = Src;
8888 Dest.convert(Sema, APFloat::rmNearestTiesToEven, &LosesInfo);
8889 return Dest;
8890 };
8891
8892 auto NextValue = [](const APFloat &Value, bool RoundDown) {
8893 APFloat NextValue = Value;
8894 NextValue.next(RoundDown);
8895 return NextValue;
8896 };
8897
8898 APFloat NextCValue = NextValue(*CValue, RoundDown);
8899
8900 const fltSemantics &DestFltSema =
8901 DestType->getScalarType()->getFltSemantics();
8902
8903 APFloat ExtCValue = ConvertFltSema(*CValue, DestFltSema);
8904 APFloat ExtNextCValue = ConvertFltSema(NextCValue, DestFltSema);
8905
8906 // When 'NextCValue' is infinity, use an imaged 'NextCValue' that equals
8907 // 'CValue + bias' to avoid the infinity after conversion. The bias is
8908 // estimated as 'CValue - PrevCValue', where 'PrevCValue' is the previous
8909 // value of 'CValue'.
8910 if (NextCValue.isInfinity()) {
8911 APFloat PrevCValue = NextValue(*CValue, !RoundDown);
8912 APFloat Bias = ConvertFltSema(*CValue - PrevCValue, DestFltSema);
8913
8914 ExtNextCValue = ExtCValue + Bias;
8915 }
8916
8917 APFloat ExtMidValue =
8918 scalbn(ExtCValue + ExtNextCValue, -1, APFloat::rmNearestTiesToEven);
8919
8920 const fltSemantics &SrcFltSema =
8921 C.getType()->getScalarType()->getFltSemantics();
8922
8923 // 'MidValue' might be rounded to 'NextCValue'. Correct it here.
8924 APFloat MidValue = ConvertFltSema(ExtMidValue, SrcFltSema);
8925 if (MidValue != *CValue)
8926 ExtMidValue.next(!RoundDown);
8927
8928 // Check whether 'ExtMidValue' is a valid result since the assumption on
8929 // imaged 'NextCValue' might not hold for new float types.
8930 // ppc_fp128 can't pass here when converting from max float because of
8931 // APFloat implementation.
8932 if (NextCValue.isInfinity()) {
8933 // ExtMidValue --- narrowed ---> Finite
8934 if (ConvertFltSema(ExtMidValue, SrcFltSema).isInfinity())
8935 return nullptr;
8936
8937 // NextExtMidValue --- narrowed ---> Infinity
8938 APFloat NextExtMidValue = NextValue(ExtMidValue, RoundDown);
8939 if (ConvertFltSema(NextExtMidValue, SrcFltSema).isFinite())
8940 return nullptr;
8941 }
8942
8943 return new FCmpInst(Pred, FPTrunc.getOperand(0),
8944 ConstantFP::get(DestType, ExtMidValue), "", &I);
8945}
8946
8947/// Optimize fabs(X) compared with zero.
8949 Value *X;
8950 if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
8951 return nullptr;
8952
8953 const APFloat *C;
8954 if (!match(I.getOperand(1), m_APFloat(C)))
8955 return nullptr;
8956
8957 if (!C->isPosZero()) {
8958 if (!C->isSmallestNormalized())
8959 return nullptr;
8960
8961 const Function *F = I.getFunction();
8962 DenormalMode Mode = F->getDenormalMode(C->getSemantics());
8963 if (Mode.Input == DenormalMode::PreserveSign ||
8965
8966 auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8967 Constant *Zero = ConstantFP::getZero(X->getType());
8968 return new FCmpInst(P, X, Zero, "", I);
8969 };
8970
8971 switch (I.getPredicate()) {
8972 case FCmpInst::FCMP_OLT:
8973 // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
8974 return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
8975 case FCmpInst::FCMP_UGE:
8976 // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
8977 return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
8978 case FCmpInst::FCMP_OGE:
8979 // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
8980 return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
8981 case FCmpInst::FCMP_ULT:
8982 // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
8983 return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
8984 default:
8985 break;
8986 }
8987 }
8988
8989 return nullptr;
8990 }
8991
8992 auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
8993 I->setPredicate(P);
8994 return IC.replaceOperand(*I, 0, X);
8995 };
8996
8997 switch (I.getPredicate()) {
8998 case FCmpInst::FCMP_UGE:
8999 case FCmpInst::FCMP_OLT:
9000 // fabs(X) >= 0.0 --> true
9001 // fabs(X) < 0.0 --> false
9002 llvm_unreachable("fcmp should have simplified");
9003
9004 case FCmpInst::FCMP_OGT:
9005 // fabs(X) > 0.0 --> X != 0.0
9006 return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
9007
9008 case FCmpInst::FCMP_UGT:
9009 // fabs(X) u> 0.0 --> X u!= 0.0
9010 return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
9011
9012 case FCmpInst::FCMP_OLE:
9013 // fabs(X) <= 0.0 --> X == 0.0
9014 return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
9015
9016 case FCmpInst::FCMP_ULE:
9017 // fabs(X) u<= 0.0 --> X u== 0.0
9018 return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
9019
9020 case FCmpInst::FCMP_OGE:
9021 // fabs(X) >= 0.0 --> !isnan(X)
9022 assert(!I.hasNoNaNs() && "fcmp should have simplified");
9023 return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
9024
9025 case FCmpInst::FCMP_ULT:
9026 // fabs(X) u< 0.0 --> isnan(X)
9027 assert(!I.hasNoNaNs() && "fcmp should have simplified");
9028 return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
9029
9030 case FCmpInst::FCMP_OEQ:
9031 case FCmpInst::FCMP_UEQ:
9032 case FCmpInst::FCMP_ONE:
9033 case FCmpInst::FCMP_UNE:
9034 case FCmpInst::FCMP_ORD:
9035 case FCmpInst::FCMP_UNO:
9036 // Look through the fabs() because it doesn't change anything but the sign.
9037 // fabs(X) == 0.0 --> X == 0.0,
9038 // fabs(X) != 0.0 --> X != 0.0
9039 // isnan(fabs(X)) --> isnan(X)
9040 // !isnan(fabs(X) --> !isnan(X)
9041 return replacePredAndOp0(&I, I.getPredicate(), X);
9042
9043 default:
9044 return nullptr;
9045 }
9046}
9047
9048/// Optimize sqrt(X) compared with zero.
9050 Value *X;
9051 if (!match(I.getOperand(0), m_Sqrt(m_Value(X))))
9052 return nullptr;
9053
9054 if (!match(I.getOperand(1), m_PosZeroFP()))
9055 return nullptr;
9056
9057 auto ReplacePredAndOp0 = [&](FCmpInst::Predicate P) {
9058 I.setPredicate(P);
9059 return IC.replaceOperand(I, 0, X);
9060 };
9061
9062 // Clear ninf flag if sqrt doesn't have it.
9063 if (!cast<Instruction>(I.getOperand(0))->hasNoInfs())
9064 I.setHasNoInfs(false);
9065
9066 switch (I.getPredicate()) {
9067 case FCmpInst::FCMP_OLT:
9068 case FCmpInst::FCMP_UGE:
9069 // sqrt(X) < 0.0 --> false
9070 // sqrt(X) u>= 0.0 --> true
9071 llvm_unreachable("fcmp should have simplified");
9072 case FCmpInst::FCMP_ULT:
9073 case FCmpInst::FCMP_ULE:
9074 case FCmpInst::FCMP_OGT:
9075 case FCmpInst::FCMP_OGE:
9076 case FCmpInst::FCMP_OEQ:
9077 case FCmpInst::FCMP_UNE:
9078 // sqrt(X) u< 0.0 --> X u< 0.0
9079 // sqrt(X) u<= 0.0 --> X u<= 0.0
9080 // sqrt(X) > 0.0 --> X > 0.0
9081 // sqrt(X) >= 0.0 --> X >= 0.0
9082 // sqrt(X) == 0.0 --> X == 0.0
9083 // sqrt(X) u!= 0.0 --> X u!= 0.0
9084 return IC.replaceOperand(I, 0, X);
9085
9086 case FCmpInst::FCMP_OLE:
9087 // sqrt(X) <= 0.0 --> X == 0.0
9088 return ReplacePredAndOp0(FCmpInst::FCMP_OEQ);
9089 case FCmpInst::FCMP_UGT:
9090 // sqrt(X) u> 0.0 --> X u!= 0.0
9091 return ReplacePredAndOp0(FCmpInst::FCMP_UNE);
9092 case FCmpInst::FCMP_UEQ:
9093 // sqrt(X) u== 0.0 --> X u<= 0.0
9094 return ReplacePredAndOp0(FCmpInst::FCMP_ULE);
9095 case FCmpInst::FCMP_ONE:
9096 // sqrt(X) != 0.0 --> X > 0.0
9097 return ReplacePredAndOp0(FCmpInst::FCMP_OGT);
9098 case FCmpInst::FCMP_ORD:
9099 // !isnan(sqrt(X)) --> X >= 0.0
9100 return ReplacePredAndOp0(FCmpInst::FCMP_OGE);
9101 case FCmpInst::FCMP_UNO:
9102 // isnan(sqrt(X)) --> X u< 0.0
9103 return ReplacePredAndOp0(FCmpInst::FCMP_ULT);
9104 default:
9105 llvm_unreachable("Unexpected predicate!");
9106 }
9107}
9108
9110 CmpInst::Predicate Pred = I.getPredicate();
9111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9112
9113 // Canonicalize fneg as Op1.
9114 if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
9115 std::swap(Op0, Op1);
9116 Pred = I.getSwappedPredicate();
9117 }
9118
9119 if (!match(Op1, m_FNeg(m_Specific(Op0))))
9120 return nullptr;
9121
9122 // Replace the negated operand with 0.0:
9123 // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
9124 Constant *Zero = ConstantFP::getZero(Op0->getType());
9125 return new FCmpInst(Pred, Op0, Zero, "", &I);
9126}
9127
9129 Constant *RHSC, InstCombinerImpl &CI) {
9130 const CmpInst::Predicate Pred = I.getPredicate();
9131 Value *X = LHSI->getOperand(0);
9132 Value *Y = LHSI->getOperand(1);
9133 switch (Pred) {
9134 default:
9135 break;
9136 case FCmpInst::FCMP_UGT:
9137 case FCmpInst::FCMP_ULT:
9138 case FCmpInst::FCMP_UNE:
9139 case FCmpInst::FCMP_OEQ:
9140 case FCmpInst::FCMP_OGE:
9141 case FCmpInst::FCMP_OLE:
9142 // The optimization is not valid if X and Y are infinities of the same
9143 // sign, i.e. the inf - inf = nan case. If the fsub has the ninf or nnan
9144 // flag then we can assume we do not have that case. Otherwise we might be
9145 // able to prove that either X or Y is not infinity.
9146 if (!LHSI->hasNoNaNs() && !LHSI->hasNoInfs() &&
9150 break;
9151
9152 [[fallthrough]];
9153 case FCmpInst::FCMP_OGT:
9154 case FCmpInst::FCMP_OLT:
9155 case FCmpInst::FCMP_ONE:
9156 case FCmpInst::FCMP_UEQ:
9157 case FCmpInst::FCMP_UGE:
9158 case FCmpInst::FCMP_ULE:
9159 // fcmp pred (x - y), 0 --> fcmp pred x, y
9160 if (match(RHSC, m_AnyZeroFP()) &&
9161 I.getFunction()->getDenormalMode(
9162 LHSI->getType()->getScalarType()->getFltSemantics()) ==
9164 CI.replaceOperand(I, 0, X);
9165 CI.replaceOperand(I, 1, Y);
9166 I.setHasNoInfs(LHSI->hasNoInfs());
9167 if (LHSI->hasNoNaNs())
9168 I.setHasNoNaNs(true);
9169 return &I;
9170 }
9171 // fcmp `pred (C - Y), C` -> `fcmp swap(pred), Y, 0`
9172 // where C and Y can't be arbitrary floating-point values.
9173 // For example, with `C = 1.0f` and `Y = 0x1p-149`, `1.0f - Y` rounds back
9174 // to `1.0f`, so the source compare is false while the rewritten compare is
9175 // true.
9176 // We need to make sure (C - Y) never rounds back to C
9177 const APFloat *C;
9178 Value *IntSrc;
9179 if (match(RHSC, m_APFloat(C)) &&
9180 match(LHSI, m_FSub(m_Specific(RHSC), m_IToFP(m_Value(IntSrc)))) &&
9181 C->isNormal()) {
9182 // Requirements on C and Y:
9183 // 1. C is finite, nonzero, normal.
9184 // 2. C shouldn't be too large, that is, ULP(C) <= 1.
9185 // 3. Y must be the form of `[su]itofp`, so the finite nonzero result of Y
9186 // must be integer-valued with an absolute value of at least 1;
9187 // as long as the step size near C does not exceed 1,
9188 // C - Y cannot be rounded back to C when Y != 0.
9189 // 4. If Y = 0, `fcmp pred (C - 0), C` are equivalent to `fcmp swap(pred)
9190 // 0, 0` for ordered and unordered predicates as long as C is finite and
9191 // nonzero.
9192 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
9193 if (MantissaWidth != -1 && ilogb(*C) < MantissaWidth) {
9194 Constant *ZeroC = ConstantFP::getZero(LHSI->getType());
9195 I.setPredicate(I.getSwappedPredicate());
9196 CI.replaceOperand(I, 0, Y);
9197 CI.replaceOperand(I, 1, ZeroC);
9198 return &I;
9199 }
9200 }
9201 break;
9202 }
9203
9204 return nullptr;
9205}
9206
9207/// Fold: fabs(uitofp(a) - uitofp(b)) pred C --> a == b
9208/// where 'pred' is olt, ult, ogt, ugt, oge or uge and C is a positive, Non-NaN
9209/// float when the uitofp casts are exact and C is in the valid range.
9210///
9211/// Since exact uitofp means distinct integers map to distinct floats, the only
9212/// values fabs(uitofp(a) - uitofp(b)) can take are {0.0, 1.0, 2.0, ...}.
9213/// There are no values in the open interval (0, 1), so:
9214/// fabs(...) < C where 0 < C <= 1.0 --> a == b (strict lt: C=1.0 ok)
9215// fabs(..) >= C where C >= 1.0 -> a != b
9216///
9217/// The same logic applies to sitofp.
9219 Value *FAbsArg;
9220 if (!match(I.getOperand(0), m_FAbs(m_Value(FAbsArg))))
9221 return nullptr;
9222
9223 const APFloat *C;
9224 if (!match(I.getOperand(1), PatternMatch::m_FiniteNonZero(C)))
9225 return nullptr;
9226
9227 FCmpInst::Predicate Pred = I.getPredicate();
9228 bool IsStrictLt = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT;
9229 bool IsLe = Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE;
9230 bool IsStrictGt = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT;
9231 bool IsGe = Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
9232 if (!IsStrictLt && !IsStrictGt && !IsGe)
9233 return nullptr;
9234
9235 APFloat One = APFloat::getOne(C->getSemantics());
9236 APFloat::cmpResult Cmp = C->compare(One);
9237
9238 // For strict-lt (olt/ult): C must be in (0, 1.0] -- C == 1.0 is fine since
9239 // the next possible value after 0.0 is 1.0, and < 1.0 excludes it.
9240 if (IsStrictLt && Cmp == APFloat::cmpGreaterThan)
9241 return nullptr;
9242 if (IsGe && Cmp == APFloat::cmpGreaterThan)
9243 return nullptr;
9244 if (IsLe && Cmp != APFloat::cmpGreaterThan)
9245 return nullptr;
9246 if (IsStrictGt && Cmp != APFloat::cmpLessThan)
9247 return nullptr;
9248
9249 // Match: fsub(uitofp(A), uitofp(B)) where both casts are uitofp or sitofp
9250 Value *A, *B;
9251 bool IsSigned;
9252 if (match(FAbsArg, m_FSub(m_UIToFP(m_Value(A)), m_UIToFP(m_Value(B))))) {
9253 IsSigned = false;
9254 } else if (match(FAbsArg,
9256 IsSigned = true;
9257 } else {
9258 return nullptr;
9259 }
9260
9261 // A and B must have the same integer type
9262 if (A->getType() != B->getType())
9263 return nullptr;
9264
9265 Type *FPTy = FAbsArg->getType();
9266 if (!IC.canBeCastedExactlyIntToFP(A, FPTy, IsSigned, &I) ||
9267 !IC.canBeCastedExactlyIntToFP(B, FPTy, IsSigned, &I))
9268 return nullptr;
9269 ICmpInst::Predicate ResultPred =
9270 IsStrictLt || IsLe ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
9271 return new ICmpInst(ResultPred, A, B);
9272}
9273
9275 InstCombinerImpl &IC) {
9276 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
9277 Type *OpType = LHS->getType();
9278 CmpInst::Predicate Pred = I.getPredicate();
9279
9282
9283 if (!FloorX && !CeilX) {
9286 std::swap(LHS, RHS);
9287 Pred = I.getSwappedPredicate();
9288 }
9289 }
9290
9291 if ((FloorX || CeilX) && FCmpInst::isCommutative(Pred) && LHS->hasOneUse()) {
9292 // fcmp pred floor(x), x => fcmp pred trunc(x), x
9293 // fcmp pred ceil(x), x => fcmp pred trunc(x), x
9294 // where pred is oeq, one, ord, ueq, une, uno.
9295 Value *TruncX = IC.Builder.CreateUnaryIntrinsic(Intrinsic::trunc, RHS);
9296 return new FCmpInst(Pred, TruncX, RHS, "", &I);
9297 }
9298
9299 switch (Pred) {
9300 case FCmpInst::FCMP_OLE:
9301 // fcmp ole floor(x), x => fcmp ord x, 0
9302 if (FloorX)
9304 "", &I);
9305 break;
9306 case FCmpInst::FCMP_OGT:
9307 // fcmp ogt floor(x), x => false
9308 if (FloorX)
9309 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9310 break;
9311 case FCmpInst::FCMP_OGE:
9312 // fcmp oge ceil(x), x => fcmp ord x, 0
9313 if (CeilX)
9315 "", &I);
9316 break;
9317 case FCmpInst::FCMP_OLT:
9318 // fcmp olt ceil(x), x => false
9319 if (CeilX)
9320 return IC.replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9321 break;
9322 case FCmpInst::FCMP_ULE:
9323 // fcmp ule floor(x), x => true
9324 if (FloorX)
9325 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9326 break;
9327 case FCmpInst::FCMP_UGT:
9328 // fcmp ugt floor(x), x => fcmp uno x, 0
9329 if (FloorX)
9331 "", &I);
9332 break;
9333 case FCmpInst::FCMP_UGE:
9334 // fcmp uge ceil(x), x => true
9335 if (CeilX)
9336 return IC.replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9337 break;
9338 case FCmpInst::FCMP_ULT:
9339 // fcmp ult ceil(x), x => fcmp uno x, 0
9340 if (CeilX)
9342 "", &I);
9343 break;
9344 default:
9345 break;
9346 }
9347
9348 return nullptr;
9349}
9350
9351/// Returns true if a select that implements a min/max is redundant and
9352/// select result can be replaced with its non-constant operand, e.g.,
9353/// select ( (si/ui-to-fp A) <= C ), C, (si/ui-to-fp A)
9354/// where C is the FP constant equal to the minimum integer value
9355/// representable by A.
9357 Value *B) {
9358 const APFloat *APF;
9359 if (!match(B, m_APFloat(APF)))
9360 return false;
9361
9362 auto *I = dyn_cast<Instruction>(A);
9363 if (!I || !(I->getOpcode() == Instruction::SIToFP ||
9364 I->getOpcode() == Instruction::UIToFP))
9365 return false;
9366
9367 bool IsUnsigned = I->getOpcode() == Instruction::UIToFP;
9368 unsigned BitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
9369 APSInt IntBoundary = (Flavor == SPF_FMAXNUM)
9370 ? APSInt::getMinValue(BitWidth, IsUnsigned)
9371 : APSInt::getMaxValue(BitWidth, IsUnsigned);
9372 APSInt ConvertedInt(BitWidth, IsUnsigned);
9373 bool IsExact;
9375 APF->convertToInteger(ConvertedInt, APFloat::rmTowardZero, &IsExact);
9376 return Status == APFloat::opOK && IsExact && ConvertedInt == IntBoundary;
9377}
9378
9380 bool Changed = false;
9381
9382 /// Orders the operands of the compare so that they are listed from most
9383 /// complex to least complex. This puts constants before unary operators,
9384 /// before binary operators.
9385 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
9386 I.swapOperands();
9387 Changed = true;
9388 }
9389
9390 const CmpInst::Predicate Pred = I.getPredicate();
9391 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
9392 if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
9393 SQ.getWithInstruction(&I)))
9394 return replaceInstUsesWith(I, V);
9395
9396 // Simplify 'fcmp pred X, X'
9397 Type *OpType = Op0->getType();
9398 assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
9399 if (Op0 == Op1) {
9400 switch (Pred) {
9401 default:
9402 break;
9403 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
9404 case FCmpInst::FCMP_ULT: // True if unordered or less than
9405 case FCmpInst::FCMP_UGT: // True if unordered or greater than
9406 case FCmpInst::FCMP_UNE: // True if unordered or not equal
9407 // Canonicalize these to be 'fcmp uno %X, 0.0'.
9408 I.setPredicate(FCmpInst::FCMP_UNO);
9409 I.setOperand(1, Constant::getNullValue(OpType));
9410 return &I;
9411
9412 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
9413 case FCmpInst::FCMP_OEQ: // True if ordered and equal
9414 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
9415 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
9416 // Canonicalize these to be 'fcmp ord %X, 0.0'.
9417 I.setPredicate(FCmpInst::FCMP_ORD);
9418 I.setOperand(1, Constant::getNullValue(OpType));
9419 return &I;
9420 }
9421 }
9422
9423 if (I.isCommutative()) {
9424 if (auto Pair = matchSymmetricPair(I.getOperand(0), I.getOperand(1))) {
9425 replaceOperand(I, 0, Pair->first);
9426 replaceOperand(I, 1, Pair->second);
9427 return &I;
9428 }
9429 }
9430
9431 // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
9432 // then canonicalize the operand to 0.0.
9433 if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
9434 if (!match(Op0, m_PosZeroFP()) &&
9435 isKnownNeverNaN(Op0, getSimplifyQuery().getWithInstruction(&I)))
9436 return replaceOperand(I, 0, ConstantFP::getZero(OpType));
9437
9438 if (!match(Op1, m_PosZeroFP()) &&
9439 isKnownNeverNaN(Op1, getSimplifyQuery().getWithInstruction(&I)))
9440 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9441 }
9442
9443 // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
9444 Value *X, *Y;
9445 if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
9446 return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
9447
9449 return R;
9450
9451 // Test if the FCmpInst instruction is used exclusively by a select as
9452 // part of a minimum or maximum operation. If so, refrain from doing
9453 // any other folding. This helps out other analyses which understand
9454 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
9455 // and CodeGen. And in this case, at least one of the comparison
9456 // operands has at least one user besides the compare (the select),
9457 // which would often largely negate the benefit of folding anyway.
9458 if (I.hasOneUse())
9459 if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
9460 Value *A, *B;
9462 bool IsRedundantMinMaxClamp =
9463 (SPR.Flavor == SPF_FMAXNUM || SPR.Flavor == SPF_FMINNUM) &&
9465 if (SPR.Flavor != SPF_UNKNOWN && !IsRedundantMinMaxClamp)
9466 return nullptr;
9467 }
9468
9469 // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
9470 // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
9471 if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
9472 return replaceOperand(I, 1, ConstantFP::getZero(OpType));
9473
9474 // Canonicalize:
9475 // fcmp olt X, +inf -> fcmp one X, +inf
9476 // fcmp ole X, +inf -> fcmp ord X, 0
9477 // fcmp ogt X, +inf -> false
9478 // fcmp oge X, +inf -> fcmp oeq X, +inf
9479 // fcmp ult X, +inf -> fcmp une X, +inf
9480 // fcmp ule X, +inf -> true
9481 // fcmp ugt X, +inf -> fcmp uno X, 0
9482 // fcmp uge X, +inf -> fcmp ueq X, +inf
9483 // fcmp olt X, -inf -> false
9484 // fcmp ole X, -inf -> fcmp oeq X, -inf
9485 // fcmp ogt X, -inf -> fcmp one X, -inf
9486 // fcmp oge X, -inf -> fcmp ord X, 0
9487 // fcmp ult X, -inf -> fcmp uno X, 0
9488 // fcmp ule X, -inf -> fcmp ueq X, -inf
9489 // fcmp ugt X, -inf -> fcmp une X, -inf
9490 // fcmp uge X, -inf -> true
9491 const APFloat *C;
9492 if (match(Op1, m_APFloat(C)) && C->isInfinity()) {
9493 switch (C->isNegative() ? FCmpInst::getSwappedPredicate(Pred) : Pred) {
9494 default:
9495 break;
9496 case FCmpInst::FCMP_ORD:
9497 case FCmpInst::FCMP_UNO:
9500 case FCmpInst::FCMP_OGT:
9501 case FCmpInst::FCMP_ULE:
9502 llvm_unreachable("Should be simplified by InstSimplify");
9503 case FCmpInst::FCMP_OLT:
9504 return new FCmpInst(FCmpInst::FCMP_ONE, Op0, Op1, "", &I);
9505 case FCmpInst::FCMP_OLE:
9506 return new FCmpInst(FCmpInst::FCMP_ORD, Op0, ConstantFP::getZero(OpType),
9507 "", &I);
9508 case FCmpInst::FCMP_OGE:
9509 return new FCmpInst(FCmpInst::FCMP_OEQ, Op0, Op1, "", &I);
9510 case FCmpInst::FCMP_ULT:
9511 return new FCmpInst(FCmpInst::FCMP_UNE, Op0, Op1, "", &I);
9512 case FCmpInst::FCMP_UGT:
9513 return new FCmpInst(FCmpInst::FCMP_UNO, Op0, ConstantFP::getZero(OpType),
9514 "", &I);
9515 case FCmpInst::FCMP_UGE:
9516 return new FCmpInst(FCmpInst::FCMP_UEQ, Op0, Op1, "", &I);
9517 }
9518 }
9519
9520 // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
9521 // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
9522 if (match(Op1, m_PosZeroFP()) &&
9524 X->getType()->isIntOrIntVectorTy() &&
9525 !F.getDenormalMode(Op1->getType()->getScalarType()->getFltSemantics())
9526 .inputsMayBeZero()) {
9528 if (Pred == FCmpInst::FCMP_OEQ)
9529 IntPred = ICmpInst::ICMP_EQ;
9530 else if (Pred == FCmpInst::FCMP_UNE)
9531 IntPred = ICmpInst::ICMP_NE;
9532
9533 if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
9534 Type *IntTy = X->getType();
9535 const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
9536 Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
9537 return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
9538 }
9539 }
9540
9541 // Handle fcmp with instruction LHS and constant RHS.
9542 Instruction *LHSI;
9543 Constant *RHSC;
9544 if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
9545 switch (LHSI->getOpcode()) {
9546 case Instruction::Select:
9547 // fcmp eq (cond ? x : -x), 0 --> fcmp eq x, 0
9548 if (FCmpInst::isEquality(Pred) && match(RHSC, m_AnyZeroFP()) &&
9550 return replaceOperand(I, 0, X);
9552 return NV;
9553 break;
9554 case Instruction::FSub:
9555 if (LHSI->hasOneUse())
9556 if (Instruction *NV = foldFCmpFSubIntoFCmp(I, LHSI, RHSC, *this))
9557 return NV;
9558 break;
9559 case Instruction::PHI:
9560 if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
9561 return NV;
9562 break;
9563 case Instruction::SIToFP:
9564 case Instruction::UIToFP:
9565 if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
9566 return NV;
9567 break;
9568 case Instruction::FDiv:
9569 if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
9570 return NV;
9571 break;
9572 case Instruction::Load:
9573 if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
9575 cast<LoadInst>(LHSI), GEP, I.getPredicate(), RHSC, I))
9576 return Res;
9577 break;
9578 case Instruction::FPTrunc:
9579 if (Instruction *NV = foldFCmpFpTrunc(I, *LHSI, *RHSC))
9580 return NV;
9581 break;
9582 }
9583 }
9584
9585 if (Instruction *R = foldFabsWithFcmpZero(I, *this))
9586 return R;
9587
9588 if (Instruction *R = foldFCmpFAbsFSubIntToFP(I, *this))
9589 return R;
9590
9591 if (Instruction *R = foldSqrtWithFcmpZero(I, *this))
9592 return R;
9593
9594 if (Instruction *R = foldFCmpWithFloorAndCeil(I, *this))
9595 return R;
9596
9598 return R;
9599
9600 if (match(Op0, m_FNeg(m_Value(X)))) {
9601 // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
9602 Constant *C;
9603 if (match(Op1, m_Constant(C)))
9604 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
9605 return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
9606 }
9607
9608 // fcmp (fadd X, 0.0), Y --> fcmp X, Y
9609 if (match(Op0, m_FAdd(m_Value(X), m_AnyZeroFP())))
9610 return new FCmpInst(Pred, X, Op1, "", &I);
9611
9612 // fcmp X, (fadd Y, 0.0) --> fcmp X, Y
9613 if (match(Op1, m_FAdd(m_Value(Y), m_AnyZeroFP())))
9614 return new FCmpInst(Pred, Op0, Y, "", &I);
9615
9616 // fcmp ord/uno (fptrunc X), (fptrunc Y) -> fcmp ord/uno X, Y
9617 if ((Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) &&
9618 match(Op0, m_FPTrunc(m_Value(X))) && match(Op1, m_FPTrunc(m_Value(Y))) &&
9619 X->getType() == Y->getType())
9620 return new FCmpInst(Pred, X, Y, "", &I);
9621
9622 if (match(Op0, m_FPExt(m_Value(X)))) {
9623 // fcmp (fpext X), (fpext Y) -> fcmp X, Y
9624 if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
9625 return new FCmpInst(Pred, X, Y, "", &I);
9626
9627 const APFloat *C;
9628 if (match(Op1, m_APFloat(C))) {
9629 const fltSemantics &FPSem =
9630 X->getType()->getScalarType()->getFltSemantics();
9631 bool Lossy;
9632 APFloat TruncC = *C;
9634
9635 if (Lossy) {
9636 // X can't possibly equal the higher-precision constant, so reduce any
9637 // equality comparison.
9638 // TODO: Other predicates can be handled via getFCmpCode().
9639 switch (Pred) {
9640 case FCmpInst::FCMP_OEQ:
9641 // X is ordered and equal to an impossible constant --> false
9642 return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
9643 case FCmpInst::FCMP_ONE:
9644 // X is ordered and not equal to an impossible constant --> ordered
9645 return new FCmpInst(FCmpInst::FCMP_ORD, X,
9646 ConstantFP::getZero(X->getType()));
9647 case FCmpInst::FCMP_UEQ:
9648 // X is unordered or equal to an impossible constant --> unordered
9649 return new FCmpInst(FCmpInst::FCMP_UNO, X,
9650 ConstantFP::getZero(X->getType()));
9651 case FCmpInst::FCMP_UNE:
9652 // X is unordered or not equal to an impossible constant --> true
9653 return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
9654 default:
9655 break;
9656 }
9657 }
9658
9659 // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
9660 // Avoid lossy conversions and denormals.
9661 // Zero is a special case that's OK to convert.
9662 APFloat Fabs = TruncC;
9663 Fabs.clearSign();
9664 if (!Lossy &&
9665 (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
9666 Constant *NewC = ConstantFP::get(X->getType(), TruncC);
9667 return new FCmpInst(Pred, X, NewC, "", &I);
9668 }
9669 }
9670 }
9671
9672 // Convert a sign-bit test of an FP value into a cast and integer compare.
9673 // TODO: Simplify if the copysign constant is 0.0 or NaN.
9674 // TODO: Handle non-zero compare constants.
9675 // TODO: Handle other predicates.
9677 m_Value(X)))) &&
9678 match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
9679 Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
9680 if (auto *VecTy = dyn_cast<VectorType>(OpType))
9681 IntType = VectorType::get(IntType, VecTy->getElementCount());
9682
9683 // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
9684 if (Pred == FCmpInst::FCMP_OLT) {
9685 Value *IntX = Builder.CreateBitCast(X, IntType);
9686 return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
9687 ConstantInt::getNullValue(IntType));
9688 }
9689 }
9690
9691 {
9692 Value *CanonLHS = nullptr;
9694 // (canonicalize(x) == x) => (x == x)
9695 if (CanonLHS == Op1)
9696 return new FCmpInst(Pred, Op1, Op1, "", &I);
9697
9698 Value *CanonRHS = nullptr;
9700 // (x == canonicalize(x)) => (x == x)
9701 if (CanonRHS == Op0)
9702 return new FCmpInst(Pred, Op0, Op0, "", &I);
9703
9704 // (canonicalize(x) == canonicalize(y)) => (x == y)
9705 if (CanonLHS && CanonRHS)
9706 return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
9707 }
9708
9709 if (I.getType()->isVectorTy())
9710 if (Instruction *Res = foldVectorCmp(I, Builder))
9711 return Res;
9712
9713 return Changed ? &I : nullptr;
9714}
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:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
#define P(N)
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
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:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:338
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6044
void clearSign()
Definition APFloat.h:1402
bool isNaN() const
Definition APFloat.h:1581
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1192
bool isZero() const
Definition APFloat.h:1579
static APFloat getSmallestNormalized(const fltSemantics &Sem, bool Negative=false)
Returns the smallest (by magnitude) normalized finite number in the given semantics.
Definition APFloat.h:1262
APInt bitcastToAPInt() const
Definition APFloat.h:1475
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
opStatus next(bool nextDown)
Definition APFloat.h:1358
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
LLVM_ABI FPClassTest classify() const
Return the FPClassTest which will return true for the value.
Definition APFloat.cpp:5973
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1352
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
static LLVM_ABI void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Dual division/remainder interface.
Definition APInt.cpp:1796
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1986
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
bool eq(const APInt &RHS) const
Equality comparison.
Definition APInt.h:1083
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
void negate()
Negate this APInt in place.
Definition APInt.h:1488
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
void flipAllBits()
Toggle every bit to its opposite value.
Definition APInt.h:1472
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1635
unsigned logBase2() const
Definition APInt.h:1781
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1676
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
static APSInt getMinValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the minimum integer value with the given bit width and signedness.
Definition APSInt.h:310
static APSInt getMaxValue(uint32_t numBits, bool Unsigned)
Return the APSInt representing the maximum integer value with the given bit width and signedness.
Definition APSInt.h:302
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate getStrictPredicate() const
For example, SGE -> SGT, SLE -> SLT, ULE -> ULT, UGE -> UGT.
Definition InstrTypes.h:921
bool isEquality() const
Determine if this is an equals/not equals predicate.
Definition InstrTypes.h:978
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getNonStrictPredicate() const
For example, SGT -> SGE, SLT -> SLE, ULT -> ULE, UGT -> UGE.
Definition InstrTypes.h:934
static LLVM_ABI bool isStrictPredicate(Predicate predicate)
This is a static version that you can use without an instruction available.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI CmpPredicate getSwapped(CmpPredicate P)
Get the swapped predicate of a CmpPredicate.
Conditional Branch instruction.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
LLVM_ABI 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:64
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h: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
bool isInBounds() const
GEPNoWrapFlags intersectForOffsetAdd(GEPNoWrapFlags Other) const
Given (gep (gep p, x), y), determine the nowrap flags for (gep p, x+y).
static GEPNoWrapFlags none()
bool isInBounds() const
Test whether this is an inbounds GEP, as defined by LangRef.html.
Definition Operator.h:390
LLVM_ABI Type * getSourceElementType() const
Definition Operator.cpp:86
Value * getPointerOperand()
Definition Operator.h:417
GEPNoWrapFlags getNoWrapFlags() const
Definition Operator.h:385
bool hasAllConstantIndices() const
Return true if all of the indices of this GEP are constant integers.
Definition Operator.h:464
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1566
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2492
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
ConstantInt * getInt(const APInt &AI)
Get a constant integer value.
Definition IRBuilder.h:480
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:2909
Instruction * foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr, const APInt &C)
Fold icmp ({al}shr X, Y), C.
Instruction * foldICmpWithZextOrSext(ICmpInst &ICmp)
Instruction * foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select, ConstantInt *C)
Instruction * foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv, const APInt &C)
Instruction * foldICmpBinOpWithConstant(ICmpInst &Cmp, BinaryOperator *BO, const APInt &C)
Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
Instruction * foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or, const APInt &C)
Fold icmp (or X, Y), C.
Instruction * foldICmpTruncWithTruncOrExt(ICmpInst &Cmp, const SimplifyQuery &Q)
Fold icmp (trunc nuw/nsw X), (trunc nuw/nsw Y).
Instruction * foldSignBitTest(ICmpInst &I)
Fold equality-comparison between zero and any (maybe truncated) right-shift by one-less-than-bitwidth...
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi, bool isSigned, bool Inside)
Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise (V < Lo || V >= Hi).
Instruction * foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ)
Try to fold icmp (binop), X or icmp X, (binop).
Instruction * 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 * 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 * foldCmpLoadFromIndexedGlobal(LoadInst *LI, GetElementPtrInst *GEP, CmpPredicate Pred, Constant *RHSC, Instruction &CtxI, ConstantInt *AndCst=nullptr)
This is called when we see this pattern: cmp pred (load (gep GV, ...)), cmpcst where GV is a global v...
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:338
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents min/max intrinsics.
Value * getLHS() const
Value * getRHS() const
static bool isMin(Intrinsic::ID ID)
Whether the intrinsic is a smin or umin.
static bool isSigned(Intrinsic::ID ID)
Whether the intrinsic is signed or unsigned.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Represents a saturating add/sub intrinsic.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This instruction constructs a fixed permutation of two input vectors.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition Type.h:167
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
LLVM_ABI int getFPMantissaWidth() const
Return the width of the mantissa of this type.
Definition Type.cpp:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:151
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:708
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:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
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
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
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:2801
LLVM_ABI APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition APInt.cpp:2819
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
auto m_PosZeroFP()
Matches a floating-point positive zero.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
cst_pred_ty< is_negative > m_Negative()
Match an integer or vector of negative values.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
auto m_Sqrt(const Opnd0 &Op0)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWNeg(const ValTy &V)
Matches a 'Neg' as 'sub nsw 0, V'.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
match_combine_or< CastInst_match< OpTy, UIToFPInst >, CastInst_match< OpTy, SIToFPInst > > m_IToFP(const OpTy &Op)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
NoWrapTrunc_match< OpTy, TruncInst::NoSignedWrap > m_NSWTrunc(const OpTy &Op)
Matches trunc nsw.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
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)
auto m_FAbs(const Opnd0 &Op0)
Signum_match< Val_t > m_Signum(const Val_t &V)
Matches a signum pattern.
CastInst_match< OpTy, SIToFPInst > m_SIToFP(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_MaxOrMin(const Opnd0 &Op0, const Opnd1 &Op1)
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
cst_pred_ty< icmp_pred_with_threshold > m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold)
Match an integer or vector with every element comparing 'pred' (eg/ne/...) to Threshold.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ BinaryOp
One of the operands is a binary op.
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI Value * simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q)
Given operands for an FCmpInst, fold the result or return null.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool 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 isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI Value * emitGEPOffset(IRBuilderBase *Builder, const DataLayout &DL, User *GEP, bool NoAssumptions=false)
Given a getelementptr instruction/constantexpr, emit the code necessary to compute the offset from th...
Definition Local.cpp:22
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
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 LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:976
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1701
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI Value * simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for an ICmpInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, unsigned MaxUsesToExplore=0)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
@ Continue
Definition DWP.h:26
@ 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:880
#define NC
Definition regutils.h:42
Value * materialize(InstCombiner::BuilderTy &Builder) const
static OffsetResult select(Value *Cond, Value *TrueV, Value *FalseV, Instruction *MDFrom)
static OffsetResult value(Value *V)
static OffsetResult invalid()
This callback is used in conjunction with PointerMayBeCaptured.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Represent subnormal handling kind for floating point instruction inputs and outputs.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
static constexpr DenormalMode getIEEE()
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
APInt getSignedMaxValue() const
Return the maximal signed value possible given these KnownBits.
Definition KnownBits.h:152
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:300
APInt getSignedMinValue() const
Return the minimal signed value possible given these KnownBits.
Definition KnownBits.h:136
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:226
GEPNoWrapFlags Flags
Definition Loads.h:231
Matching combinators.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const Instruction * CtxI
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342
Capture information for a specific Use.